Codebase list resteasy / b2ad05b
Imported Upstream version 3.5.0 Timo Aaltonen 6 years ago
2250 changed file(s) with 57322 addition(s) and 80713 deletion(s). Raw diff Collapse all Expand all
+0
-1
.mvn/jvm.config less more
0 -DdownloadSources=true
00 install:
11 - mvn clean
22 script:
3 - travis_wait 30 mvn -B -fae -Dserver.version=$SERVER_VERSION install
3 - mvn -B -fae -Dserver.version=$SERVER_VERSION install
44
55 language: java
66 jdk:
77 - oraclejdk8
8 - oraclejdk9
89 env:
910 - SERVER_VERSION=10.1.0.Final
1011 - SERVER_VERSION=10.0.0.Final
11 - SERVER_VERSION=11.0.0.Alpha1
12 - SERVER_VERSION=11.0.0.Final
13 matrix:
14 exclude:
15 - jdk: oraclejdk9
16 env: SERVER_VERSION=10.0.0.Final
17 - jdk: oraclejdk9
18 env: SERVER_VERSION=10.1.0.Final
1219 cache:
1320 directories:
1421 - $HOME/.m2
1724 packages:
1825 - oracle-java8-installer
1926 before_install:
20 - "sudo unzip -j -o travis-libs/jce_policy-8.zip *.jar -d $JAVA_HOME/jre/lib/security"
27 - "if [ -d \"$JAVA_HOME/jre\" ]; then SEC_LIB=$JAVA_HOME/jre; else SEC_LIB=$JAVA_HOME; fi; sudo unzip -j -o travis-libs/jce_policy-8.zip *.jar -d $SEC_LIB/lib/security;"
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>RESTEASY-1056-jetty-bv11</artifactId>
4949 </dependency>
5050 <dependency>
5151 <groupId>org.jboss.spec.javax.ws.rs</groupId>
52 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
52 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
53 </dependency>
54 <dependency>
55 <groupId>org.jboss.spec.javax.xml.bind</groupId>
56 <artifactId>jboss-jaxb-api_2.3_spec</artifactId>
5357 </dependency>
5458 <dependency>
5559 <groupId>com.sun.xml.bind</groupId>
56 <artifactId>jaxb-impl</artifactId>
60 <artifactId>jaxb-core</artifactId>
5761 </dependency>
5862 <dependency>
5963 <groupId>org.jboss.resteasy</groupId>
7474 Assert.assertEquals(returnValueCount, e.getReturnValueViolations().size());
7575 }
7676 }
77
2323 <container qualifier="jetty" default="true">
2424 <configuration>
2525 <property name="bindHttpPort">0</property>
26 <property name="javaVmArguments">${additionalJvmArgs}</property>
27 <!--property name="javaVmArguments">${additionalJvmArgs} -Xdebug -Xrunjdwp:transport=dt_socket,address=8585,server=y, suspend=y</property-->
26 <!--property name="javaVmArguments">-Xdebug -Xrunjdwp:transport=dt_socket,address=8585,server=y, suspend=y</property-->
2827 </configuration>
2928 </container>
3029 </arquillian>
+0
-104
arquillian/RESTEASY-1630-jetty-resteasy-servlet-initializer/pom.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4 <modelVersion>4.0.0</modelVersion>
5 <parent>
6 <groupId>org.jboss.resteasy</groupId>
7 <artifactId>resteasy-jaxrs-all</artifactId>
8 <version>3.1.4.Final</version>
9 <relativePath>../../pom.xml</relativePath>
10 </parent>
11 <artifactId>RESTEASY-1630-jetty-resteasy-servlet-initializer</artifactId>
12 <packaging>jar</packaging>
13 <name>RESTEASY-1630-jetty-resteasy-servlet-initializer</name>
14
15 <properties>
16 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
17 <version.shrinkwrap.resolvers>2.2.4</version.shrinkwrap.resolvers>
18 </properties>
19
20 <dependencies>
21 <dependency>
22 <groupId>org.jboss.shrinkwrap.resolver</groupId>
23 <artifactId>shrinkwrap-resolver-depchain</artifactId>
24 <version>${version.shrinkwrap.resolvers}</version>
25 <scope>test</scope>
26 <type>pom</type>
27 </dependency>
28 <dependency>
29 <groupId>org.jboss.arquillian.container</groupId>
30 <artifactId>arquillian-jetty-embedded-9</artifactId>
31 <version>1.0.0.CR3</version>
32 <scope>test</scope>
33 </dependency>
34 <dependency>
35 <groupId>org.eclipse.jetty</groupId>
36 <artifactId>jetty-deploy</artifactId>
37 <scope>test</scope>
38 </dependency>
39 <dependency>
40 <groupId>org.eclipse.jetty</groupId>
41 <artifactId>jetty-annotations</artifactId>
42 <scope>test</scope>
43 </dependency>
44 <dependency>
45 <groupId>org.eclipse.jetty</groupId>
46 <artifactId>jetty-webapp</artifactId>
47 <scope>test</scope>
48 </dependency>
49 <dependency>
50 <groupId>org.eclipse.jetty</groupId>
51 <artifactId>jetty-plus</artifactId>
52 <scope>test</scope>
53 </dependency>
54
55 <dependency>
56 <groupId>org.jboss.arquillian.protocol</groupId>
57 <artifactId>arquillian-protocol-servlet</artifactId>
58 <scope>test</scope>
59 </dependency>
60 <dependency>
61 <groupId>org.jboss.spec.javax.ws.rs</groupId>
62 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
63 </dependency>
64 <dependency>
65 <groupId>org.jboss.resteasy</groupId>
66 <artifactId>resteasy-servlet-initializer</artifactId>
67 <version>${project.version}</version>
68 </dependency>
69 <dependency>
70 <groupId>org.jboss.resteasy</groupId>
71 <artifactId>resteasy-jaxrs</artifactId>
72 <version>${project.version}</version>
73 </dependency>
74 <dependency>
75 <groupId>org.jboss.resteasy</groupId>
76 <artifactId>resteasy-client</artifactId>
77 <version>${project.version}</version>
78 </dependency>
79 <dependency>
80 <groupId>junit</groupId>
81 <artifactId>junit</artifactId>
82 </dependency>
83 <dependency>
84 <groupId>org.jboss.arquillian.junit</groupId>
85 <artifactId>arquillian-junit-container</artifactId>
86 <scope>test</scope>
87 </dependency>
88 <dependency>
89 <groupId>org.jboss.resteasy</groupId>
90 <artifactId>resteasy-validator-provider-11</artifactId>
91 <version>${project.version}</version>
92 </dependency>
93 <dependency>
94 <groupId>org.jboss.spec.javax.el</groupId>
95 <artifactId>jboss-el-api_3.0_spec</artifactId>
96 <scope>test</scope>
97 </dependency>
98 <dependency>
99 <groupId>com.sun.xml.bind</groupId>
100 <artifactId>jaxb-impl</artifactId>
101 </dependency>
102 </dependencies>
103 </project>
+0
-18
arquillian/RESTEASY-1630-jetty-resteasy-servlet-initializer/src/main/java/org/jboss/resteasy/resteasy1630/TestApplication.java less more
0 package org.jboss.resteasy.resteasy1630;
1
2 import java.util.HashSet;
3 import java.util.Set;
4
5 import javax.ws.rs.core.Application;
6 import javax.ws.rs.ext.Provider;
7
8 @Provider
9 public class TestApplication extends Application
10 {
11 public Set<Class<?>> getClasses()
12 {
13 HashSet<Class<?>> classes = new HashSet<Class<?>>();
14 classes.add(TestResource.class);
15 return classes;
16 }
17 }
+0
-9
arquillian/RESTEASY-1630-jetty-resteasy-servlet-initializer/src/main/java/org/jboss/resteasy/resteasy1630/TestApplicationPath.java less more
0 package org.jboss.resteasy.resteasy1630;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4
5 @ApplicationPath("/two")
6 public class TestApplicationPath extends Application
7 {
8 }
+0
-24
arquillian/RESTEASY-1630-jetty-resteasy-servlet-initializer/src/main/java/org/jboss/resteasy/resteasy1630/TestResource.java less more
0 package org.jboss.resteasy.resteasy1630;
1
2 import javax.validation.constraints.Min;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.PathParam;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.Response;
9
10 /**
11 */
12 @Path("/")
13 public class TestResource
14 {
15 @GET
16 @Path("test/{param}")
17 @Produces(MediaType.TEXT_PLAIN)
18 public Response test(@Min(7) @PathParam("param") int param)
19 {
20 System.out.println("param: " + param);
21 return Response.ok().entity(param).build();
22 }
23 }
+0
-75
arquillian/RESTEASY-1630-jetty-resteasy-servlet-initializer/src/test/java/org/jboss/resteasy/test/resteasy1630/ServletInitializerTest.java less more
0 package org.jboss.resteasy.test.resteasy1630;
1
2 import java.net.URI;
3 import java.io.File;
4 import javax.ws.rs.core.Response;
5 import org.jboss.arquillian.container.test.api.Deployment;
6 import org.jboss.arquillian.container.test.api.RunAsClient;
7 import org.jboss.arquillian.junit.Arquillian;
8 import org.jboss.arquillian.test.api.ArquillianResource;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.resteasy1630.TestApplication;
11 import org.jboss.resteasy.resteasy1630.TestResource;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.ShrinkWrap;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.jboss.shrinkwrap.resolver.api.maven.MavenFormatStage;
16 import org.jboss.shrinkwrap.resolver.api.maven.MavenResolverSystem;
17 import org.jboss.shrinkwrap.resolver.api.maven.MavenStrategyStage;
18 import org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage;
19 import org.junit.Assert;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 import static org.junit.Assert.assertEquals;
24 import org.jboss.shrinkwrap.resolver.api.maven.Maven;
25
26 /**
27 See the Servlet 3.0 spec, section 8.2.4 for implementation and processing the details
28 of ServletContainerInitializer.
29
30 Resteasy's implementation of ServletContainerInitializer is declared in the
31 META-INF/services directory of archive org.jboss.resteasy:resteasy-servlet-initializer
32 as required by the spec. This archive MUST be included in the generated WAR file
33 so the server can find and call it. Shrinkwrap's Maven class and .addAsLibraries
34 method is used to achieve this.
35
36 This test checks that the implementation properly handles a jaxrs app that provides
37 resource and provider classes as well as no web.xml file.
38 */
39
40 @RunWith(Arquillian.class)
41 @RunAsClient
42 public class ServletInitializerTest {
43
44 @Deployment
45 public static Archive<?> createTestArchive() {
46 File pomFile = Maven.resolver().loadPomFromFile("pom.xml").resolve("org.jboss.resteasy:resteasy-servlet-initializer")
47 .withoutTransitivity().asSingleFile();
48
49 WebArchive war = ShrinkWrap.create(WebArchive.class, "RESTEASY-1630-two.war")
50 .addClasses(TestApplication.class)
51 .addClasses(TestResource.class)
52 .addAsLibraries(pomFile)
53 .addAsWebInfResource("web.xml");
54 return war;
55 }
56
57 @ArquillianResource
58 URI baseUri;
59
60 /**
61 * App declares files via the web.xml
62 * @throws Exception
63 */
64 @Test
65 public void testEndpoint() throws Exception {
66 Response response = ResteasyClientBuilder.newClient()
67 .target(baseUri.toString() + "test/17").request().get();
68 System.out.println("Status: " + response.getStatus());
69 String entity = response.readEntity(String.class);
70 System.out.println("Result: " + entity);
71 assertEquals(200, response.getStatus());
72 Assert.assertEquals("17", entity);
73 }
74 }
+0
-70
arquillian/RESTEASY-1630-jetty-resteasy-servlet-initializer/src/test/java/org/jboss/resteasy/test/resteasy1630/ServletInitializerTwoTest.java less more
0 package org.jboss.resteasy.test.resteasy1630;
1
2 import java.io.File;
3 import java.net.URI;
4 import javax.ws.rs.core.Response;
5 import org.jboss.arquillian.container.test.api.Deployment;
6 import org.jboss.arquillian.container.test.api.RunAsClient;
7 import org.jboss.arquillian.junit.Arquillian;
8 import org.jboss.arquillian.test.api.ArquillianResource;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.resteasy1630.TestApplicationPath;
11 import org.jboss.resteasy.resteasy1630.TestResource;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.ShrinkWrap;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.jboss.shrinkwrap.resolver.api.maven.Maven;
16 import org.junit.Assert;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 import static org.junit.Assert.assertEquals;
21
22 /**
23 See the Servlet 3.0 spec, section 8.2.4 for implementation and processing the details
24 of ServletContainerInitializer.
25
26 Resteasy's implementation of ServletContainerInitializer is declared in the
27 META-INF/services directory of archive org.jboss.resteasy:resteasy-servlet-initializer
28 as required by the spec. This archive MUST be included in the generated WAR file
29 so the server can find and call it. Shrinkwrap's Maven class and .addAsLibraries
30 method is used to achieve this.
31
32 This test checks that the implementation properly handles a jaxrs app that provides
33 resource and provider classes but no web.xml file.
34 */
35
36 @RunWith(Arquillian.class)
37 @RunAsClient
38 public class ServletInitializerTwoTest {
39
40 @Deployment
41 public static Archive<?> createTestArchiveTwo() {
42 File pomFile = Maven.resolver().loadPomFromFile("pom.xml").resolve("org.jboss.resteasy:resteasy-servlet-initializer")
43 .withoutTransitivity().asSingleFile();
44
45 WebArchive war = ShrinkWrap.create(WebArchive.class, "RESTEASY-1630-two.war")
46 .addClasses(TestApplicationPath.class)
47 .addAsLibraries(pomFile)
48 .addClasses(TestResource.class);
49 return war;
50 }
51
52 @ArquillianResource
53 URI baseUri;
54
55 /**
56 * No web.xml provided in app. The server must auto scan for files.
57 * @throws Exception
58 */
59 @Test
60 public void testEndpoint() throws Exception {
61 Response response = ResteasyClientBuilder.newClient()
62 .target(baseUri.toString() + "two/test/17").request().get();
63 System.out.println("Status: " + response.getStatus());
64 String entity = response.readEntity(String.class);
65 System.out.println("Result: " + entity);
66 assertEquals(200, response.getStatus());
67 Assert.assertEquals("17", entity);
68 }
69 }
+0
-33
arquillian/RESTEASY-1630-jetty-resteasy-servlet-initializer/src/test/resources/arquillian.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <!-- JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc.
2 and/or its affiliates, and individual contributors by the @authors tag. See
3 the copyright.txt in the distribution for a full listing of individual contributors.
4 Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 use this file except in compliance with the License. You may obtain a copy
6 of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
7 by applicable law or agreed to in writing, software distributed under the
8 License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
9 OF ANY KIND, either express or implied. See the License for the specific
10 language governing permissions and limitations under the License. -->
11 <arquillian xmlns="http://jboss.org/schema/arquillian"
12 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
13 xsi:schemaLocation="http://jboss.org/schema/arquillian
14 http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
15
16 <!-- Force the use of the Servlet 3.0 protocol with all containers, as it is the most mature -->
17 <defaultProtocol type="Servlet 3.0" />
18
19 <engine>
20 <property name="deploymentExportPath">target/deployments</property>
21 </engine>
22
23 <container qualifier="jetty" default="true">
24 <configuration>
25 <property name="bindHttpPort">0</property>
26 <property name="javaVmArguments">${additionalJvmArgs}</property>
27 <!--
28 <property name="javaVmArguments">${additionalJvmArgs} -Xdebug -Xrunjdwp:transport=dt_socket,address=8585,server=y, suspend=n</property>
29 -->
30 </configuration>
31 </container>
32 </arquillian>
+0
-21
arquillian/RESTEASY-1630-jetty-resteasy-servlet-initializer/src/test/resources/web.xml less more
0 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
3
4 <display-name>RESTEASY-1630</display-name>
5
6 <servlet>
7 <servlet-name>Resteasy</servlet-name>
8 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
9 <init-param>
10 <param-name>javax.ws.rs.Application</param-name>
11 <param-value>org.jboss.resteasy.resteasy1630.TestApplication</param-value>
12 </init-param>
13 </servlet>
14
15 <servlet-mapping>
16 <servlet-name>Resteasy</servlet-name>
17 <url-pattern>/*</url-pattern>
18 </servlet-mapping>
19
20 </web-app>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>RESTEASY-736-jetty</artifactId>
6464 </dependency>
6565 <dependency>
6666 <groupId>org.jboss.spec.javax.ws.rs</groupId>
67 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
67 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
6868 </dependency>
6969 <dependency>
7070 <groupId>org.jboss.resteasy</groupId>
00 package org.jboss.resteasy.resteasy736;
11
2 import java.util.concurrent.TimeUnit;
2 import org.jboss.resteasy.annotations.Suspend;
3 import org.jboss.resteasy.spi.AsynchronousResponse;
34
45 import javax.ws.rs.GET;
56 import javax.ws.rs.Path;
67 import javax.ws.rs.Produces;
7 import javax.ws.rs.container.AsyncResponse;
8 import javax.ws.rs.container.Suspended;
98 import javax.ws.rs.core.MediaType;
109 import javax.ws.rs.core.Response;
1110
2221 {
2322 @GET
2423 @Path("test")
25 public void test(final @Suspended AsyncResponse response)
24 public void test(final @Suspend(5000) AsynchronousResponse response)
2625 {
27 response.setTimeout(5000, TimeUnit.MILLISECONDS);
2826 Thread t = new Thread()
2927 {
3028 @Override
3533 System.out.println("TestResource: async thread started");
3634 Thread.sleep(10000);
3735 Response jaxrs = Response.ok("test").type(MediaType.TEXT_PLAIN).build();
38 response.resume(jaxrs);
36 response.setResponse(jaxrs);
3937 System.out.println("TestResource: async thread finished");
4038 }
4139 catch (Exception e)
4947
5048 @GET
5149 @Path("default")
52 public void defaultTest(final @Suspended AsyncResponse response)
50 public void defaultTest(final @Suspend AsynchronousResponse response)
5351 {
5452 Thread t = new Thread()
5553 {
6159 System.out.println("TestResource: async thread started");
6260 Thread.sleep(35000); // Jetty async timeout defaults to 30000.
6361 Response jaxrs = Response.ok("test").type(MediaType.TEXT_PLAIN).build();
64 response.resume(jaxrs);
62 response.setResponse(jaxrs);
6563 System.out.println("TestResource: async thread finished");
6664 }
6765 catch (Exception e)
22 <parent>
33 <groupId>org.jboss.resteasy</groupId>
44 <artifactId>resteasy-jaxrs-all</artifactId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../pom.xml</relativePath>
77 </parent>
88 <name>RESTEasy Misc Arquillian-based tests</name>
1313 <modules>
1414 <module>RESTEASY-736-jetty</module>
1515 <module>RESTEASY-1056-jetty-bv11</module>
16 <module>RESTEASY-1630-jetty-resteasy-servlet-initializer</module>
1716 </modules>
1817
1918 <artifactId>resteasy-misc-arquillian-tests</artifactId>
3433 <skip>true</skip>
3534 </configuration>
3635 </plugin>
37 <plugin>
38 <artifactId>maven-surefire-plugin</artifactId>
39 <configuration>
40 <systemPropertyVariables>
41 <additionalJvmArgs>${modular.jdk.props}</additionalJvmArgs>
42 </systemPropertyVariables>
43 </configuration>
44 </plugin>
4536 </plugins>
4637 </build>
4738
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 </parent>
88
99 <groupId>org.jboss.as</groupId>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 </parent>
88
99 <groupId>org.jboss.as</groupId>
1010 <artifactId>jboss-as-dist</artifactId>
11 <version>8.0.0m-alpha-20130417-resteasy-3.1.4.Final</version>
11 <version>8.0.0m-alpha-20130417-resteasy-3.5.0.Final</version>
1212 <packaging>pom</packaging>
1313 <name>Custom AS8 Resteasy Distribution</name>
1414 <description/>
4343 <include>org.jboss.resteasy:resteasy-atom-provider</include>
4444 <include>org.jboss.resteasy:resteasy-multipart-provider</include>
4545 <include>org.jboss.resteasy:resteasy-json-p-provider</include>
46 <include>org.jboss.resteasy:resteasy-json-binding-provider</include>
4647 <include>org.jboss.resteasy:resteasy-jackson-provider</include>
4748 <include>org.jboss.resteasy:resteasy-jackson2-provider</include>
4849 <include>org.jboss.resteasy:resteasy-yaml-provider</include>
5253 <include>org.jboss.resteasy:resteasy-oauth</include>
5354 <include>org.jboss.resteasy:resteasy-cdi</include>
5455 <include>org.jboss.resteasy:resteasy-jsapi</include>
55 <include>org.jboss.resteasy:resteasy-legacy</include>
5656 <include>org.jboss.resteasy:resteasy-links</include>
5757 <include>org.jboss.resteasy:resteasy-crypto</include>
5858 <include>org.jboss.resteasy:jose-jwt</include>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 </parent>
88
99 <artifactId>resteasy-jaxrs-dist</artifactId>
4040
4141 <dependency>
4242 <groupId>org.jboss.spec.javax.ws.rs</groupId>
43 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
43 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
4444 </dependency>
4545 <dependency>
4646 <groupId>org.jboss.resteasy</groupId>
5555 <dependency>
5656 <groupId>org.jboss.resteasy</groupId>
5757 <artifactId>resteasy-json-p-provider</artifactId>
58 <version>${project.version}</version>
59 </dependency>
60 <dependency>
61 <groupId>org.jboss.resteasy</groupId>
62 <artifactId>resteasy-json-binding-provider</artifactId>
5863 <version>${project.version}</version>
5964 </dependency>
6065 <dependency>
165170 <dependency>
166171 <groupId>org.jboss.resteasy</groupId>
167172 <artifactId>resteasy-vertx</artifactId>
168 <version>${project.version}</version>
169 </dependency>
170 <dependency>
171 <groupId>org.jboss.resteasy</groupId>
172 <artifactId>resteasy-legacy</artifactId>
173173 <version>${project.version}</version>
174174 </dependency>
175175 <dependency>
185185 <plugin>
186186 <groupId>org.apache.maven.plugins</groupId>
187187 <artifactId>maven-enforcer-plugin</artifactId>
188 <version>1.4</version> <!-- https://issues.apache.org/jira/browse/MENFORCER-248 -->
189188 </plugin>
190189 </plugins>
191190 </pluginManagement>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-dist</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 </parent>
88
99 <artifactId>resteasy-jaxrs-src-dist</artifactId>
55
66 <groupId>org.jboss.resteasy</groupId>
77 <artifactId>resteasy-reference-guide-${translation}</artifactId>
8 <version>3.1.4.Final</version>
8 <version>3.5.0.Final</version>
99 <packaging>jdocbook</packaging>
1010 <name>RESTEasy Reference Guide (${translation})</name>
1111 <description/>
2626 <!ENTITY Configuring_Individual_JAX-RS_Resource_Beans SYSTEM "modules/Configuring_Individual_JAX-RS_Resource_Beans.xml">
2727 <!ENTITY Asynchronous_HTTP SYSTEM "modules/Asynchronous_HTTP.xml">
2828 <!ENTITY Asynchronous_Job SYSTEM "modules/Async_job_service.xml">
29 <!ENTITY Reactive SYSTEM "modules/Reactive.xml">
2930 <!ENTITY RESTEasy_Embedded_Container SYSTEM "modules/RESTEasy_Embedded_Container.xml">
3031 <!ENTITY RESTEasy_Server-side_Mock_Framework SYSTEM "modules/RESTEasy_Server-side_Mock_Framework.xml">
3132 <!ENTITY Securing_JAX-RS_and_RESTeasy SYSTEM "modules/Securing_JAX-RS_and_RESTeasy.xml">
5556 <!ENTITY Validation SYSTEM "modules/Validation.xml">
5657 <!ENTITY CORS SYSTEM "modules/cors.xml">
5758 <!ENTITY I18N SYSTEM "modules/I18N.xml">
59 <!ENTITY JAX-RS_2.1_additions SYSTEM "modules/JAX-RS_2.1_additions.xml">
5860 <!ENTITY Deprecated_security_modules SYSTEM "modules/Deprecated_security_modules.xml">
5961 ]>
6062
6365 <bookinfo>
6466 <title>RESTEasy JAX-RS</title>
6567 <subtitle>RESTFul Web Services for Java</subtitle>
66 <releaseinfo>3.1.4.Final</releaseinfo>
68 <releaseinfo>3.5.0.Final</releaseinfo>
6769 </bookinfo>
6870
6971 <toc/>
120122 &Json-p;
121123 &Multipart;
122124 &Yaml;
125 &JAX-RS_2.1_additions;
123126 &StringConverter;
124127 &Responses_using_javax.ws.rs.core.Response;
125128 &ExceptionMappers;
131134 &Interceptors;
132135 &Asynchronous_HTTP;
133136 &Asynchronous_Job;
137 &Reactive;
134138 &RESTEasy_Embedded_Container;
135139 &RESTEasy_Server-side_Mock_Framework;
136140 &Securing_JAX-RS_and_RESTeasy;
149153 &I18N;
150154 &Maven_and_RESTEasy;
151155 &Deprecated_security_modules;
156 &Migration_to_3_5;
152157 &Migration_to_3_1;
153158 &Migration_from_older_versions;
154159 &Books;
00 <chapter id="async_job_service">
11 <title>Asynchronous Job Service</title>
22 <para>
3 The Resteasy Asynchronous Job Service is an implementation of the Asynchronous Job pattern defined in O'Reilly's "Restful Web Services" book. The idea of it is to bring asynchronicity to a synchronous protocol.
3 The RESTEasy Asynchronous Job Service is an implementation of the Asynchronous Job pattern defined in O'Reilly's "Restful Web Services" book. The idea of it is to bring asynchronicity to a synchronous protocol.
44 </para>
55 <sect1 id="async_job">
66 <title>Using Async Jobs</title>
77 <para>While HTTP is a synchronous protocol
88 it does have a faint idea of asynchronous invocations. The HTTP 1.1 response code 202, "Accepted" means that the server
9 has received and accepted the response for processing, but the processing has not yet been completed. The Resteasy
9 has received and accepted the response for processing, but the processing has not yet been completed. The RESTEasy
1010 Asynchronous Job Service builds around this idea.
1111 </para>
1212 <programlisting>
1313 POST http://example.com/myservice?asynch=true
1414 </programlisting>
1515 <para>
16 For example, if you make the above post with the asynch query parameter set to true, Resteasy will return a 202, "Accepted" response code and run the invocation in the background. It also sends back a Location header with a URL pointing to where the response of the background method is located.
16 For example, if you make the above post with the asynch query parameter set to true, RESTEasy will return a 202, "Accepted" response code and run the invocation in the background. It also sends back a Location header with a URL pointing to where the response of the background method is located.
1717 </para>
1818 <programlisting>
1919 HTTP/1.1 202 Accepted
2626 /asynch/jobs/{job-id}?wait={millisconds}|nowait=true
2727 </programlisting>
2828 <para>You can perform the GET, POST, and DELETE operations on this job URL. GET returns whatever the JAX-RS resource method you invoked
29 returned as a response if the job was completed. If the job has not completed, this GET will return a response code of 202, Accepted. Invoking GET does not remove the job, so you can call it multiple times. When Resteasy's job queue gets full, it will evict
29 returned as a response if the job was completed. If the job has not completed, this GET will return a response code of 202, Accepted. Invoking GET does not remove the job, so you can call it multiple times. When RESTEasy's job queue gets full, it will evict
3030 the least recently used job from memory. You can manually clean up after yourself by calling DELETE on the URI. POST does
3131 a read of the JOB response and will remove the JOB it has been completed.
3232 </para>
3939 <para> If you do not specify a "wait" parameter, the GET or POST will not wait at all if the job is not complete.</para>
4040 <para> NOTE!! While you can invoke GET, DELETE, and PUT methods asynchronously, this breaks the HTTP 1.1 contract of these methods. While these invocations may not change the state of the resource if invoked more than once, they do change the state of the server as new Job entries with each invocation. If you want to be a purist, stick with only invoking POST methods asynchronously.
4141 </para>
42 <para> Security NOTE! Resteasy role-based security (annotations) does not work with the Asynchronous Job Service. You must use
42 <para> Security NOTE! RESTEasy role-based security (annotations) does not work with the Asynchronous Job Service. You must use
4343 XML declarative security within your web.xml file. Why? It is impossible to implement role-based security portably. In the future, we may have specific JBoss integration, but will not support other environments.</para>
4444 <para>NOTE. A <classname>SecureRandom</classname> object is used to generate unique job ids. For security purposes, the
4545 <classname>SecureRandom</classname> is periodically reseeded. By default, it is reseeded after 100 uses. This value
4949 <sect1 id="oneway">
5050 <title>Oneway: Fire and Forget</title>
5151 <para>
52 Resteasy also supports the notion of fire and forget. This will also return a 202, Accepted response, but no Job will
52 RESTEasy also supports the notion of fire and forget. This will also return a 202, Accepted response, but no Job will
5353 be created. This is as simple as using the oneway query parameter instead of asynch. For example:
5454 </para>
5555 <programlisting>
5656 POST http://example.com/myservice?oneway=true
5757 </programlisting>
58 <para> Security NOTE! Resteasy role-based security (annotations) does not work with the Asynchronous Job Service. You must use
58 <para> Security NOTE! RESTEasy role-based security (annotations) does not work with the Asynchronous Job Service. You must use
5959 XML declaritive security within your web.xml file. Why? It is impossible to implement role-based security portably. In the future, we may have specific JBoss integration, but will not support other environments.</para>
6060 </sect1>
6161 <sect1 id="async_job_setup">
1212 getting a lot of concurrent clients that are blocking like this, there’s a lot of wasted resources and your
1313 server does not scale that well.
1414 </para>
15 <para>
16 The JAX-RS 2.0 specification has added asynchronous HTTP support via two classes. The @Suspended annotation,
17 and AsyncResponse interface.
18 </para>
19 <para>
20 Injecting an AsynchronousResponse as a parameter to your jax-rs methods tells Resteasy that the HTTP request/response should be detached from the currently
21 executing thread and that the current thread should not try to automatically process the response.
22 </para>
23 <para>
24 The AsyncResponse is the callback object.
25 The act of calling one of the resume() methods will cause a response to be sent back to the client and will also terminate the
26 HTTP request. Here is an example of asynchronous processing:
27 </para>
28
29
30 <programlisting>
15 <sect1>
16 <title>Using the <code>@Suspended</code> annotation</title>
17 <para>
18 The JAX-RS 2.0 specification has added asynchronous HTTP support via two classes. The <code>@Suspended</code> annotation,
19 and AsyncResponse interface.
20 </para>
21 <para>
22 Injecting an AsynchronousResponse as a parameter to your jax-rs methods tells RESTEasy that the HTTP request/response should be detached from the currently
23 executing thread and that the current thread should not try to automatically process the response.
24 </para>
25 <para>
26 The AsyncResponse is the callback object.
27 The act of calling one of the resume() methods will cause a response to be sent back to the client and will also terminate the
28 HTTP request. Here is an example of asynchronous processing:
29 </para>
30
31 <programlisting>
3132 import javax.ws.rs.Suspend;
3233 import javax.ws.rs.core.AsynchronousResponse;
3334
5253 }
5354 catch (Exception e)
5455 {
55 e.printStackTrace();
56 response.resume(e);
5657 }
5758 }
5859 };
5960 t.start();
6061 }
6162 }
62 </programlisting>
63 <para>
64 AsyncResponse also has other methods to cancel the execution. See javadoc for more details.
65 </para>
66 <para>
67 <emphasis role="bold">NOTE:</emphasis> The old Resteasy proprietary API for async http has been deprecated and may be removed as soon as Resteasy 3.1.
68 In particular, the Resteasy @Suspend annotation is replaced by <classname>javax.ws.rs.container.Suspended</classname>, and
69 <classname>org.jboss.resteasy.spi.AsynchronousResponse</classname> is replaced by
70 <classname>javax.ws.rs.container.AsyncResponse</classname>. Note that @Suspended does not have a value field,
71 which represented a timeout limit. Instead, <methodname>AsyncResponse.setTimeout()</methodname> may be called.
72 </para>
63 </programlisting>
64 <para>
65 AsyncResponse also has other methods to cancel the execution. See javadoc for more details.
66 </para>
67 <para>
68 <emphasis role="bold">NOTE:</emphasis> The old RESTEasy proprietary API for async http has been deprecated and may be removed as soon as RESTEasy 3.1.
69 In particular, the RESTEasy @Suspend annotation is replaced by <classname>javax.ws.rs.container.Suspended</classname>, and
70 <classname>org.jboss.resteasy.spi.AsynchronousResponse</classname> is replaced by
71 <classname>javax.ws.rs.container.AsyncResponse</classname>. Note that @Suspended does not have a value field,
72 which represented a timeout limit. Instead, <methodname>AsyncResponse.setTimeout()</methodname> may be called.
73 </para>
74 </sect1>
75 <sect1>
76 <title>Using Reactive return types</title>
77 <para id="CompletionStage">
78 The JAX-RS 2.1 specification adds support for declaring asynchronous resource methods by
79 returning a <code>CompletionStage</code> instead of using the <code>@Suspended</code>
80 annotation.
81 </para>
82 <para>
83 Whenever a resource method returns a <code>CompletionStage</code>, it will be subscribed to,
84 the request will be suspended, and only resumed when the <code>CompletionStage</code> is
85 resolved either to a value (which is then treated as the return value for the method), or
86 as an error case, in which case the exception will be processed as if it were thrown by the
87 resource method.
88 </para>
89 <para>
90 Here is an example of asynchronous processing using <code>CompletionStage</code>:
91 </para>
92 <programlisting>
93 import javax.ws.rs.Suspend;
94 import javax.ws.rs.core.AsynchronousResponse;
95
96 @Path("/")
97 public class SimpleResource
98 {
99
100 @GET
101 @Path("basic")
102 @Produces("text/plain")
103 public CompletionStage&lt;Response&gt; getBasic() throws Exception
104 {
105 final CompletableFuture&lt;Response&gt; response = new CompletableFuture&lt;&gt;();
106 Thread t = new Thread()
107 {
108 @Override
109 public void run()
110 {
111 try
112 {
113 Response jaxrs = Response.ok("basic").type(MediaType.TEXT_PLAIN).build();
114 response.complete(jaxrs);
115 }
116 catch (Exception e)
117 {
118 response.completeExceptionally(e);
119 }
120 }
121 };
122 t.start();
123 return response;
124 }
125 }
126 </programlisting>
127 <note>
128 <para>
129 RESTEasy <link linkend="Reactive">supports more reactive types for asynchronous programming</link>.
130 </para>
131 </note>
132 </sect1>
133 <sect1>
134 <title>Asynchronous filters</title>
135 <para>
136 It is possible to write <link linkend="Asynchronous_Filter">filters that also turn the request asynchronous</link>.
137 Whether or not filters turned the request asynchronous
138 before execution of your method makes absolutely no difference to your method: it does not need to be declared asynchronous in
139 order to function as specified. Synchronous methods and asynchronous methods will work as specified by the spec.
140 </para>
141 </sect1>
73142 </chapter>
00 <chapter id="Atom">
1 <title>Resteasy Atom Support</title>
1 <title>RESTEasy Atom Support</title>
22 <para>
33 From W3.org (http://tools.ietf.org/html/rfc4287):
44 </para>
1818 queues, or simply a nice format for sending or receiving data in bulk from a service.
1919 </para>
2020 <sect1 id="resteasy_atom">
21 <title>Resteasy Atom API and Provider</title>
21 <title>RESTEasy Atom API and Provider</title>
2222 <para>RESTEasy has defined a simple object model in Java to represent Atom and uses JAXB to marshal and unmarshal
2323 it. The
2424 main classes are in the org.jboss.resteasy.plugins.providers.atom package and are Feed, Entry, Content, and
2525 Link. If you
2626 look at the source, you'd see that these are annotated with JAXB annotations. The distribution contains
2727 the javadocs for this project and are a must to learn the model. Here is a simple example of sending
28 an atom feed using the Resteasy API.
28 an atom feed using the RESTEasy API.
2929 </para>
3030 <programlisting><![CDATA[
3131 import org.jboss.resteasy.plugins.providers.atom.Content;
6161 return feed;
6262 }
6363 }]]></programlisting>
64 <para>Because Resteasy's atom provider is JAXB based, you are not limited to sending atom objects using XML.
65 You can automatically re-use all the other JAXB providers that Resteasy has like JSON and fastinfoset.
64 <para>Because RESTEasy's atom provider is JAXB based, you are not limited to sending atom objects using XML.
65 You can automatically re-use all the other JAXB providers that RESTEasy has like JSON and fastinfoset.
6666 All you have to do is have "atom+" in front of the main subtype. i.e. @Produces("application/atom+json") or
6767 @Consumes("application/atom+fastinfoset")
6868 </para>
00 <chapter id="Cache_NoCache_CacheControl">
1 <title>Resteasy Caching Features</title>
1 <title>RESTEasy Caching Features</title>
22 <para>
3 Resteasy provides numerous annotations and facilities to support HTTP caching semantics. Annotations to make setting Cache-Control
3 RESTEasy provides numerous annotations and facilities to support HTTP caching semantics. Annotations to make setting Cache-Control
44 headers easier and both server-side and client-side in-memory caches are available.
55 </para>
66 <sect1 id="Cache_Annotation">
77 <title>@Cache and @NoCache Annotations</title>
88 <para>
9 Resteasy provides an extension to JAX-RS that allows you to automatically set Cache-Control headers on a successful
9 RESTEasy provides an extension to JAX-RS that allows you to automatically set Cache-Control headers on a successful
1010 GET request. It can only be used on @GET annotated methods. A successful @GET request is any request
1111 that returns 200 OK response.
1212 </para>
3232 </programlisting>
3333 <para>
3434 While @Cache builds a complex Cache-Control header, @NoCache is a simplified notation to say that you don't
35 want anything cached; i.e. Cache-Control: nocache.
35 want anything cached i.e. Cache-Control: nocache.
3636 </para>
3737 <para>
3838 These annotations can be put on the resource class or interface and specifies a default cache value for each
4242 <sect1 id="client_cache">
4343 <title>Client "Browser" Cache</title>
4444 <para>
45 Resteasy has the ability to set up a client-side, browser-like, cache. You can use it with the Client Proxy Framework, or with
46 ordinary requests. This cache looks for Cache-Control headers sent back with a server response. If the Cache-Control headers specify
47 that the client is allowed to cache the response, Resteasy caches it within local memory. The cache obeys max-age requirements
45 RESTEasy has the ability to set up a client-side, browser-like, cache. You can use it with the Client Proxy Framework, or with raw
46 ClientRequests. This cache looks for Cache-Control headers sent back with a server response. If the Cache-Control headers specify
47 that the client is allowed to cache the response, RESTEasy caches it within local memory. The cache obeys max-age requirements
4848 and will also automatically do HTTP 1.1 cache revalidation if either or both the Last-Modified and/or ETag headers are sent back with the
4949 original response. See the HTTP 1.1 specification for details on how Cache-Control or cache revalidation works.
5050 </para>
5959 public Order getOrder(@PathParam("id") String id);
6060 }
6161 </programlisting>
62 <para>To create a proxy for this interface and enable caching for that proxy requires only a few simple steps:</para>
63 <programlisting>
64 import org.jboss.resteasy.client.ProxyFactory;
65 import org.jboss.resteasy.client.cache.CacheFactory;
66 import org.jboss.resteasy.client.cache.LightweightBrowserCache;
6267
63 <para>To create a proxy for this interface and enable caching for that proxy requires only a few simple steps
64 in which the <classname>BrowserCacheFeature</classname> is registered:</para>
65
68 public static void main(String[] args) throws Exception
69 {
70 RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
71 OrderServiceClient proxy = ProxyFactory.create(OrderServiceClient.class, generateBaseUrl());
72
73 // This line enables caching
74 LightweightBrowserCache cache = CacheFactory.makeCacheable(proxy);
75 }
76 </programlisting>
77 <para>If you are using the ClientRequest class to make invocations rather than the proxy framework, it is just as easy</para>
6678 <programlisting>
67 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target("http://localhost:8081");
68 BrowserCacheFeature cacheFeature = new BrowserCacheFeature();
69 OrderServiceClient orderService = target.register(cacheFeature).proxy(OrderServiceClient.class);
79 import org.jboss.resteasy.client.ProxyFactory;
80 import org.jboss.resteasy.client.cache.CacheFactory;
81 import org.jboss.resteasy.client.cache.LightweightBrowserCache;
82
83 public static void main(String[] args) throws Exception
84 {
85 RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
86
87 // This line enables caching
88 LightweightBrowserCache cache = new LightweightBrowserCache();
89
90 ClientRequest request = new ClientRequest("http://example.com/orders/333");
91 CacheFactory.makeCacheable(request, cache);
92 }
7093 </programlisting>
71
72 <para>
73 <classname>BrowserCacheFeature</classname> will create a Resteasy
74 <classname>LightweightBrowserCache</classname> by default. It is also possible to configure
75 the cache, or install a completely different cache implementation:
76 </para>
77
78 <programlisting>
79 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target("http://localhost:8081");
80 LightweightBrowserCache cache = new LightweightBrowserCache();
81 cache.setMaxBytes(20);
82 BrowserCacheFeature cacheFeature = new BrowserCacheFeature();
83 cacheFeature.setCache(cache);
84 OrderServiceClient orderService = target.register(cacheFeature).proxy(OrderServiceClient.class);
85 </programlisting>
86
87 <para>If you are using the standard JAX-RS client framework to make invocations rather than the
88 proxy framework, it is just as easy:</para>
89
90 <programlisting>
91 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target("http://localhost:8081/orders/{id}");
92 BrowserCacheFeature cacheFeature = new BrowserCacheFeature();
93 target.register(cacheFeature);
94 String rtn = target.resolveTemplate("id", "1").request().get(String.class);
95 </programlisting>
96
9794 <para>The LightweightBrowserCache, by default, has a maximum 2 megabytes of caching space. You can change this programmatically by callings
9895 its setMaxBytes() method. If the cache gets full, the cache completely wipes itself of all cached data. This may seem
9996 a bit draconian, but the cache was written to avoid unnecessary synchronizations in a concurrent environment where the cache is
103100 </sect1>
104101 <sect1 id="server_cache">
105102 <title>Local Server-Side Response Cache</title>
106 <para>Resteasy has a server-side cache that can sit in front of your JAX-RS services.
103 <para>RESTEasy has a server-side cache that can sit in front of your JAX-RS services.
107104 It automatically caches marshalled responses from HTTP GET JAX-RS invocations if, and only if your
108 JAX-RS resource method sets a Cache-Control header. When a GET comes in, the Resteasy Server Cache checks
105 JAX-RS resource method sets a Cache-Control header. When a GET comes in, the RESTEasy Server Cache checks
109106 to see if the URI is stored in the cache. If it does, it returns the already marshalled response without
110107 invoking your JAX-RS method. Each cache entry has a max age to whatever is specified in the Cache-Control
111108 header of the initial request. The cache also will automatically generate an ETag using an MD5 hash on the
130127 </programlisting>
131128 <para>To set up the server-side cache you must register an instance of org.jboss.resteasy.plugins.cache.server.ServerCacheFeature
132129 via your Application getSingletons() or getClasses() methods. The underlying cache is Infinispan. By default,
133 Resteasy will create an Infinispan cache for you. Alternatively, you can create and pass in an instance
130 RESTEasy will create an Infinispan cache for you. Alternatively, you can create and pass in an instance
134131 of your cache to the ServerCacheFeature constructor. You can also configure Infinispan by specifying
135132 various context-param variables in your web.xml. First, if you are using Maven you must depend on the resteasy-cache-core artifact:</para>
136133 <programlisting>
138135 <dependency>
139136 <groupId>org.jboss.resteasy</groupId>
140137 <artifactId>resteasy-cache-core</artifactId>
141 <version>3.1.4.Final</version>
138 <version>3.5.0.Final</version>
142139 </dependency>
143140 ]]>
144141 </programlisting>
173170 Response.ResponseBuilder rb = request.evaluatePreconditions(lastModified, etag);
174171 </programlisting>
175172 <para>
176 By default Resteasy will return status code 304 (Not modified) or 412 (Precondition failed) if any of conditions fails.
173 By default RESTEasy will return status code 304 (Not modified) or 412 (Precondition failed) if any of conditions fails.
177174 However it is not compliant with RFC 7232 which states that headers <literal>"If-Match"</literal>, <literal>"If-None-Match"</literal> MUST have higher precedence.
178175 You can enable RFC 7232 compatible mode by setting <literal>resteasy.rfc7232preconditions</literal> context parameter to <literal>true</literal>
179176 </para>
44
55 <para>
66
7 Resteasy can automatically marshal and unmarshal a few different message bodies.
7 RESTEasy can automatically marshal and unmarshal a few different message bodies.
88 </para>
99 <para>
1010
9898 </tgroup>
9999 </table>
100100
101 </para>
102101 <para>
103102 <emphasis role="bold">Note. </emphasis> When a <classname>java.io.File</classname> is created, as in
104103 </para>
122121 delete the temporary file.
123122 </para>
124123
124
125 </para>
125126 <para>
126127
127128 </para>
185186 <para>
186187
187188
188 The Resteasy ServletContextLoader will automatically scan your WEB-INF/lib and classes directories for classes
189 The RESTEasy ServletContextLoader will automatically scan your WEB-INF/lib and classes directories for classes
189190 annotated with @Provider or you can manually configure them in web.xml. See Installation/Configuration.
190191 </para>
191192 <para>
361362
362363 <para>
363364
364 By default, Resteasy's built-in unmarshaller for org.w3c.dom.Document documents will not expand external entities,
365 By default, RESTEasy's built-in unmarshaller for org.w3c.dom.Document documents will not expand external entities,
365366 replacing them by the empty string instead. It can be configured to replace external entities by values defined in the
366367 DTD by setting the context parameter
367368
380381
381382 <para>
382383
383 Another way of dealing with the problem is by prohibiting DTDs, which Resteasy does by default. This behavior
384 Another way of dealing with the problem is by prohibiting DTDs, which RESTEasy does by default. This behavior
384385 can be changed by setting the context parameter
385386
386387 </para>
408409
409410 <para>
410411 then the expansion of &amp;foo6;
411 would result in 1,000,000 foos. By default, Resteasy will limit the number of expansions and
412 would result in 1,000,000 foos. By default, RESTEasy will limit the number of expansions and
412413 the number of attributes per entity. The exact behavior depends on the underlying parser. The limits
413414 can be turned off by setting the context parameter
414415 </para>
444445
445446 <para>
446447 It follows that, in the absence of a character set specified by a resource or resource method,
447 Resteasy SHOULD use UTF-8 as the character set for text media types, and, if it does, it MUST add an explicit
448 charset parameter to the Content-Type response header. Resteasy started adding the explicit charset
448 RESTEasy SHOULD use UTF-8 as the character set for text media types, and, if it does, it MUST add an explicit
449 charset parameter to the Content-Type response header. RESTEasy started adding the explicit charset
449450 parameter in releases 3.1.2.Final and 3.0.22.Final, and that new behavior could cause some compatibility problems. To
450451 specify the previous behavior, in which UTF-8 was used for text media types, but the explicit charset
451452 was not appended, the context parameter "resteasy.add.charset" may be set to "false". It defaults to "true".
55 <para>
66
77 ExceptionMappers are custom, application provided, components that can catch thrown application exceptions and
8 write specific HTTP responses. The are classes annotated with @Provider and that implement this interface
8 write specific HTTP responses. They are classes annotated with @Provider and that implement this interface
99 </para>
1010 <para>
1111
6565 </para>
6666 </sect1>
6767 <sect1 id="builtinException">
68 <title>Resteasy Built-in Internally-Thrown Exceptions</title>
69 <para>Resteasy has a set of built-in exceptions that are thrown by it when it encounters errors during dispatching or marshalling. They all
68 <title>RESTEasy Built-in Internally-Thrown Exceptions</title>
69 <para>RESTEasy has a set of built-in exceptions that are thrown by it when it encounters errors during dispatching or marshalling. They all
7070 revolve around specific HTTP error codes. You can find them in RESTEasy's javadoc under the package org.jboss.resteasy.spi. Here's
7171 a list of them:</para>
7272 <table frame="topbot">
110110 <row>
111111 <entry>Failure</entry>
112112 <entry>N/A</entry>
113 <entry>Internal Resteasy. Not logged</entry>
113 <entry>Internal RESTEasy. Not logged</entry>
114114 </row>
115115 <row>
116116 <entry>LoggableFailure</entry>
117117 <entry>N/A</entry>
118 <entry>Internal Resteasy error. Logged</entry>
118 <entry>Internal RESTEasy error. Logged</entry>
119119 </row>
120120 <row>
121121 <entry>DefaultOptionsMethodException</entry>
122122 <entry>N/A</entry>
123 <entry>If the user invokes HTTP OPTIONS and no JAX-RS method for it, Resteasy provides a default behavior by throwing this exception</entry>
123 <entry>If the user invokes HTTP OPTIONS and no JAX-RS method for it, RESTEasy provides a default behavior by throwing this exception</entry>
124 </row>
125 <row>
126 <entry>UnrecognizedPropertyExceptionHandler</entry>
127 <entry>400</entry>
128 <entry>A Jackson provider throws this exception when JSON data is determine to be invalid.</entry>
124129 </row>
125130 </tbody>
126131 </tgroup>
127132 </table>
128133 </sect1>
129134 <sect1 id="overring_resteasy_exceptions">
130 <title>Overriding Resteasy Builtin Exceptions</title>
131 <para>You may override Resteasy built-in exceptions by writing an ExceptionMapper for the exception. For that matter, you can write an ExceptionMapper
135 <title>Overriding RESTEasy Builtin Exceptions</title>
136 <para>You may override RESTEasy built-in exceptions by writing an ExceptionMapper for the exception. For that matter, you can write an ExceptionMapper
132137 for any thrown exception including WebApplicationException</para>
133138 </sect1>
134139 </chapter>
6969 <title>Request Scope</title>
7070 <para>
7171 Add the RequestScopeModule to your modules to allow objects to be scoped to the HTTP request by adding
72 the @RequestScoped annotation to your class. All the objects injectable via the @Context annotation are
72 the @RequestScoped annotation to your fields in resource classes. All the objects injectable via the @Context annotation are
7373 also injectable, except ServletConfig and ServletContext.
74 Note that RequestScopeModule will already be added if any of your modules extends com.google.inject.servlet.ServletModule.
75 In such cases you should not add it again to avoid injector creation errors.
7476 </para>
7577 <programlisting>
7678 <![CDATA[
8082
8183 import org.jboss.resteasy.plugins.guice.RequestScoped;
8284
83 @RequestScoped
8485 public class MyClass
8586 {
86 @Inject @Context
87 @Inject @RequestScoped @Context
8788 private HttpRequest request;
8889 }
8990 ]]>
99100 <title>Configuring Stage</title>
100101 <para>
101102 You can configure the stage Guice uses to deploy your modules by specific a context param, resteasy.guice.stage.
102 If this value is not specified, Resteasy uses whatever Guice's default is.
103 If this value is not specified, RESTEasy uses whatever Guice's default is.
103104 </para>
104105 <programlisting>
105106 <![CDATA[
11 <title>Internationalization and Localization</title>
22
33 <para>
4 With the help of the JBoss Logging project, all log and exception messages in Resteasy are internationalized. That is, they
4 With the help of the JBoss Logging project, all log and exception messages in RESTEasy are internationalized. That is, they
55 have a default value in English which can be overridden in any given locale by a file which gives translated values. For
66 more information about internationalization and localization in Java, see, for example,
77 <ulink url="http://docs.oracle.com/javase/tutorial/i18n">http://docs.oracle.com/javase/tutorial/i18n</ulink>. For more about
1414 <section>
1515 <title>Internationalization</title>
1616 <para>
17 Each module in Resteasy that produces any text in the form of logging messages or exception messages
17 Each module in RESTEasy that produces any text in the form of logging messages or exception messages
1818 has an interface named org.jboss.resteasy...i18n.Messages which contains the default messages. Those
1919 modules which do any logging also have an interface named org.jboss.resteasy...i18n.LogMessages which gives access to an
2020 underlying logger. With the exception of the resteasy-jaxrs module, all messages are in the Messages class. resteasy-jaxrs
2222 </para>
2323
2424 <para>
25 Each message is prefixed by the project code "RESTEASY" followed by an ID which is unique to Resteasy. These IDs belong to the
25 Each message is prefixed by the project code "RESTEASY" followed by an ID which is unique to RESTEasy. These IDs belong to the
2626 following ranges:
2727 </para>
2828
204204 <title>Localization</title>
205205
206206 <para>
207 When Resteasy is built with the "i18n" profile, a template properties file containing the default messages
207 When RESTEasy is built with the "i18n" profile, a template properties file containing the default messages
208208 is created in a subdirectory of target/generated-translation-files. In the jaxb provider, for example,
209209 the
210210 </para>
11 <title>Installation/Configuration</title>
22
33 <para>
4 Resteasy is installed and configured in different ways depending on which environment you are running in.
5 If you are running in WildFly, Resteasy is already bundled and integrated completely
4 RESTEasy is installed and configured in different ways depending on which environment you are running in.
5 If you are running in WildFly, RESTEasy is already bundled and integrated completely
66 so there is very little you have to do. If you are running in a different environment, there is some manual
77 installation and configuration you will have to do.
88 </para>
99
1010 <section id="resteasy_modules_in_wildfly">
11 <title>Resteasy modules in WildFly</title>
12 <para>
13 In WildFly, Resteasy and the JAX-RS 2.0 API are automatically loaded into your deployment's classpath
11 <title>RESTEasy modules in WildFly</title>
12 <para>
13 In WildFly, RESTEasy and the JAX-RS API are automatically loaded into your deployment's classpath
1414 if and only if you are deploying a JAX-RS application (as determined by the presence
15 of JAX-RS annotations). However, only some Resteasy features are automatically loaded. See Table 3.1.
16 If you need any of those libraries which are not loaded automatically, you'll have bring them in
15 of JAX-RS annotations). However, only some RESTEasy features are automatically loaded. See Table 3.1.
16 If you need any of those libraries which are not loaded automatically, you'll have to bring them in
1717 with a jboss-deployment-structure.xml file in the WEB-INF directory of your WAR file. Here's an example:
1818 </para>
1919 <programlisting><![CDATA[
2828 in a META-INF/services/javax.ws.rs.ext.Providers file.
2929 </para>
3030 <para>
31 The following table specifies which of the Resteasy modules currently shipped with WildFly are loaded by default
32 when JAX-RS services are deployed and which aren't.
31 To get an idea of which RESTEasy modules are loaded by default when JAX-RS services are deployed, please
32 see the table below, which refers to a recent WildFly ditribution patched with the current RESTEasy
33 distribution. Clearly, future and unpatched WildFly distributions might differ a bit in terms of modules
34 enabled by default, as the container actually controls this too.
3335 </para>
3436 <para>
3537 <table>
5759 yes
5860 </entry>
5961 <entry>
60 Resteasy's atom library
62 RESTEasy's atom library
6163 </entry>
6264 </row>
6365 <row>
6870 yes
6971 </entry>
7072 <entry>
71 Resteasy CDI integration
73 RESTEasy CDI integration
7274 </entry>
7375 </row>
7476 <row>
123125 yes
124126 </entry>
125127 <entry>
126 Core Resteasy libraries for server and client. You will need to include this in your deployment
128 Core RESTEasy libraries for server and client. You will need to include this in your deployment
127129 if you are only using JAX-RS client.
128130 </entry>
129131 </row>
157159 yes
158160 </entry>
159161 <entry>
160 Resteasy's Javascript API
162 RESTEasy's Javascript API
161163 </entry>
162164 </row>
163165 <row>
173175 </row>
174176 <row>
175177 <entry>
178 org.jboss.resteasy.resteasy-json-binding-provider
179 </entry>
180 <entry>
181 yes
182 </entry>
183 <entry>
184 JSON binding API
185 </entry>
186 </row>
187 <row>
188 <entry>
189 javax.json.bind-api
190 </entry>
191 <entry>
192 yes
193 </entry>
194 <entry>
195 JSON binding API
196 </entry>
197 </row>
198 <row>
199 <entry>
200 org.eclipse.yasson
201 </entry>
202 <entry>
203 yes
204 </entry>
205 <entry>
206 RI implementation of JSON binding API
207 </entry>
208 </row>
209 <row>
210 <entry>
176211 org.jboss.resteasy.resteasy-multipart-provider
177212 </entry>
178213 <entry>
212247 yes
213248 </entry>
214249 <entry>
215 Resteasy's interface to Hibernate Bean Validation 1.1
250 RESTEasy's interface to Hibernate Bean Validation 1.1
216251 </entry>
217252 </row>
218253 <row>
232267 </para>
233268
234269 <section id="other_resteasy_modules">
235 <title>Other Resteasy modules</title>
270 <title>Other RESTEasy modules</title>
236271 <para>
237 Not all Resteasy modules are bundled with WildFly. For example,
272 Not all RESTEasy modules are bundled with WildFly. For example,
238273 resteasy-fastinfoset-provider and resteasy-wadl are not included among the
239274 modules listed in <xref linkend="resteasy_modules_in_wildfly"/>. If you want
240275 to use them in your application, you can include them in your WAR as you would if you were
242277 </para>
243278 </section>
244279 <section id="upgrading-wildfly">
245 <title>Upgrading Resteasy within WildFly</title>
280 <title>Upgrading RESTEasy within WildFly</title>
246281 <para>
247 Resteasy is bundled with WildFly, but you may want to upgrade Resteasy in WildFly to the latest version. The Resteasy
282 RESTEasy is bundled with WildFly, but you may want to upgrade RESTEasy in WildFly to the latest version. The RESTEasy
248283 distribution comes with a zip file called resteasy-jboss-modules-&lt;version&gt;.zip. Unzip this file
249284 within the modules/system/layers/base/ directory of the WildFly distribution. This will configure WildFly
250285 to use new versions of the modules listed in <xref linkend="resteasy_modules_in_wildfly"/>.
253288 </section>
254289
255290 <section>
256 <title>Deploying a Resteasy application to WildFly</title>
257 <para>
258 Resteasy is bundled with WildFly and completely integrated as per the requirements of Java EE 7.
291 <title>Deploying a RESTEasy application to WildFly</title>
292 <para>
293 RESTEasy is bundled with WildFly and completely integrated as per the requirements of Java EE.
259294 You can use it with EJB and CDI and you can rely completely on WildFly to scan for and deploy your JAX-RS services and providers.
260295 All you have to provide is your JAX-RS service and provider classes packaged
261296 within a WAR either as POJOs, CDI beans, or EJBs.
271306 </web-app>]]></programlisting>
272307 </para>
273308 <para>
274 Also, Resteasy context-params (see <xref linkend="configuration_switches"/>)
275 are available if you want to tweak or turn on/off any specific Resteasy feature.
309 Also, RESTEasy context-params (see <xref linkend="configuration_switches"/>)
310 are available if you want to tweak or turn on/off any specific RESTEasy feature.
276311 </para>
277312 <para>
278313 Since we're not using a &lt;servlet-mapping&gt; element, we must define a
302337
303338 <para>
304339 <emphasis role="bold">Note.</emphasis> As mentioned in <xref linkend="other_resteasy_modules"/>,
305 not all Resteasy modules are bundled with WildFly. For example,
340 not all RESTEasy modules are bundled with WildFly. For example,
306341 resteasy-fastinfoset-provider and resteasy-wadl are not included among the
307342 modules listed in <xref linkend="resteasy_modules_in_wildfly"/>. If you want
308343 to use them in your application, you can include them in your WAR as you would if you were
313348 <section id="standalone_resteasy">
314349 <title>Deploying to other servlet containers</title>
315350 <para>
316 If you are using Resteasy outside of WildFly, in a standalone servlet container like Tomcat or Jetty, for example,
317 you will need to include the appropriate Resteasy jars in your WAR file. You will need the core classes
351 If you are using RESTEasy outside of WildFly, in a standalone servlet container like Tomcat or Jetty, for example,
352 you will need to include the appropriate RESTEasy jars in your WAR file. You will need the core classes
318353 in the resteasy-jaxrs module, and you may need additional facilities like the resteasy-jaxb-provider module.
319 We strongly suggest that you use Maven to build your WAR files as Resteasy is split into
354 We strongly suggest that you use Maven to build your WAR files as RESTEasy is split into
320355 a bunch of different modules:
321356 </para>
322357 <programlisting><![CDATA[
337372 </para>
338373 <para>
339374 If you are not using Maven, you can include the necessary jars by hand. If you download
340 Resteasy (from <ulink url="http://resteasy.jboss.org/downloads.html">http://resteasy.jboss.org/downloads.html</ulink>,
375 RESTEasy (from <ulink url="http://resteasy.jboss.org/downloads.html">http://resteasy.jboss.org/downloads.html</ulink>,
341376 for example) you will get a file like resteasy-jaxrs-&lt;version&gt;-all.zip.
342 If you unzip it you will see a lib/ directory that contains the libraries needed by Resteasy.
377 If you unzip it you will see a lib/ directory that contains the libraries needed by RESTEasy.
343378 Copy these, as needed, into your /WEB-INF/lib directory. Place your JAX-RS annotated class resources and providers
344379 within one or more jars within /WEB-INF/lib or your raw class files within /WEB-INF/classes.
345380 </para>
348383 <title>Servlet 3.0 containers</title>
349384
350385 <para>
351 Resteasy uses the <literal>ServletContainerInitializer</literal> integration interface in Servlet 3.0 containers
386 RESTEasy uses the <literal>ServletContainerInitializer</literal> integration interface in Servlet 3.0 containers
352387 to initialize an application, automatically scanning for resources and providers. To enable automatic
353388 scanning, you must also include the <literal>resteasy-servlet-initializer</literal> artifact in your WAR
354389 file as well:
366401 <title>Older servlet containers</title>
367402 <para>
368403 The <literal>resteasy-servlet-initializer</literal> artifact will not work in Servlet versions older than
369 3.0. You'll then have to manually declare the Resteasy servlet in your WEB-INF/web.xml file of your WAR project,
404 3.0. You'll then have to manually declare the RESTEasy servlet in your WEB-INF/web.xml file of your WAR project,
370405 and you'll have to use an <classname>Application</classname> class (see <xref linkend="javax.ws.rs.core.Application"/>)
371406 which explicitly lists resources and providers. For example:
372407 </para>
394429 </web-app>]]></programlisting>
395430 </para>
396431 <para>
397 The Resteasy servlet is responsible for initializing some basic components of Resteasy.
432 The RESTEasy servlet is responsible for initializing some basic components of RESTEasy.
398433 </para>
399434 <para>
400435 <emphasis role="bold">Note.</emphasis> It is likely that support for pre-3.0 Servlet specifications
404439 </section>
405440 <section id="configuration_switches">
406441 <title>Configuration switches</title>
407 <para>Resteasy receives configuration options from &lt;context-param&gt; elements.</para>
442 <para>RESTEasy receives configuration options from &lt;context-param&gt; elements.</para>
408443 <para>
409444 <table frame="topbot">
410445 <tgroup cols="3" rowsep="1" colsep="1">
430465 no default
431466 </entry>
432467 <entry>
433 If the url-pattern for the Resteasy servlet-mapping is not /*
468 If the url-pattern for the RESTEasy servlet-mapping is not /*
434469 </entry>
435470 </row>
436471 <row>
698733 </entry>
699734 <entry>
700735 If a resource method returns a text/* or application/xml* media type without
701 an explicit charset, Resteasy will add "charset=UTF-8" to the returned
736 an explicit charset, RESTEasy will add "charset=UTF-8" to the returned
702737 Content-Type header. Note that the charset defaults to UTF-8 in this case,
703738 independent of the setting of this parameter.
704739 </entry>
710745 <para>
711746 <emphasis role="bold">Note. </emphasis>
712747 The resteasy.servlet.mapping.prefix &lt;context param&gt; variable must be set if your servlet-mapping for
713 the Resteasy servlet has a url-pattern other than /*. For example, if the url-pattern is
748 the RESTEasy servlet has a url-pattern other than /*. For example, if the url-pattern is
714749 </para>
715750 <para>
716751 <programlisting>
806841 </section>
807842
808843 <section id="listener">
809 <title>Resteasy as a ServletContextListener</title>
844 <title>RESTEasy as a ServletContextListener</title>
810845
811846 <para>
812847 This section is pretty much deprecated if you are using a Servlet 3.0 container or higher. Skip it if
813848 you are and read the configuration section above on installing in Servlet 3.0.
814 The initialization of Resteasy can be performed within a ServletContextListener instead of within the
815 Servlet. You may need this if you are writing custom Listeners that need to interact with Resteasy at boot
816 time. An example of this is the Resteasy Spring integration that requires a Spring ServletContextListener.
849 The initialization of RESTEasy can be performed within a ServletContextListener instead of within the
850 Servlet. You may need this if you are writing custom Listeners that need to interact with RESTEasy at boot
851 time. An example of this is the RESTEasy Spring integration that requires a Spring ServletContextListener.
817852 The org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap class is a ServletContextListener that
818853 configures an instance of an ResteasyProviderFactory and Registry. You can obtain instances of a
819854 ResteasyProviderFactory and Registry from the ServletContext attributes
820855 org.jboss.resteasy.spi.ResteasyProviderFactory and org.jboss.resteasy.spi.Registry. From these instances you
821 can programmatically interact with Resteasy registration interfaces.
856 can programmatically interact with RESTEasy registration interfaces.
822857 </para>
823858
824859 <programlisting><![CDATA[
846881 </web-app>]]></programlisting>
847882 </section>
848883 <section id="filter">
849 <title>Resteasy as a Servlet Filter</title>
884 <title>RESTEasy as a Servlet Filter</title>
850885
851886 <para>
852887 This section is pretty much deprecated if you are using a Servlet 3.0 container or higher. Skip it if
853888 you are and read the configuration section above on installing in Servlet 3.0.
854 The downside of running Resteasy as a Servlet is that you cannot have static resources like .html and .jpeg
889 The downside of running RESTEasy as a Servlet is that you cannot have static resources like .html and .jpeg
855890 files in the
856 same path as your JAX-RS services. Resteasy allows you to run as a Filter instead. If a JAX-RS resource is
891 same path as your JAX-RS services. RESTEasy allows you to run as a Filter instead. If a JAX-RS resource is
857892 not
858 found under the URL requested, Resteasy will delegate back to the base servlet container to resolve URLs.
893 found under the URL requested, RESTEasy will delegate back to the base servlet container to resolve URLs.
859894 </para>
860895
861896 <programlisting><![CDATA[
883918 <title>Client side</title>
884919
885920 <para>
886 JAX-RS 2.0 conforming implementations such as Resteasy support a client side framework which simplifies
887 communicating with restful applications. In Resteasy, the minimal set of modules needed for the client framework
921 JAX-RS 2.0 conforming implementations such as RESTEasy support a client side framework which simplifies
922 communicating with restful applications. In RESTEasy, the minimal set of modules needed for the client framework
888923 consists of resteasy-jaxrs and resteasy-client. You can access them by way of maven:
889924 </para>
890925
4848 filter.filter(requestContext, responseContext);
4949 }
5050 </programlisting>
51 <sect2>
52 <title id="Asynchronous_Filter">Asynchronous filters</title>
53 <para>
54 It is possible to turn filters into asynchronous filters, if you need to suspend execution of your filter
55 until a certain resource has become available. This turns the request asynchronous, but requires no change
56 to your resource method declaration. In particular, <link linkend="Asynchronous_HTTP_Request_Processing">synchronous
57 and asynchronous resource methods</link> continue
58 to work as specified, regardless of whether or not a filter turned the request asynchronous. Similarly,
59 one filter turning the request asynchronous requires no change in the declaration of further filters.
60 </para>
61 <para>
62 In order to turn a filter's execution asynchronous, you need to cast the <code>ContainerRequestContext</code> into
63 a <code>SuspendableContainerRequestContext</code> (for pre/post request filters), or cast the <code>ContainerResponseContext</code> into
64 a <code>SuspendableContainerResponseContext</code> (for response filters).
65 </para>
66 <para>
67 These context objects can turn the current filter's execution to asynchronous by calling the <code>suspend()</code>
68 method. Once asynchronous, the filter chain is suspended, and will only resume after one of the following method
69 is called on the context object:
70 </para>
71 <variablelist>
72 <varlistentry>
73 <term><code>abortWith(Response)</code></term>
74 <listitem>Terminate the filter chain, return the given <code>Response</code> to the client (only for <code>ContainerRequestFilter</code>).</listitem>
75 </varlistentry>
76 <varlistentry>
77 <term><code>resume()</code></term>
78 <listitem>Resume execution of the filter chain by calling the next filter.</listitem>
79 </varlistentry>
80 <varlistentry>
81 <term><code>resume(Throwable)</code></term>
82 <listitem>
83 Abort execution of the filter chain by throwing the given exception. This behaves as if the filter were synchronous
84 and threw the given exception.
85 </listitem>
86 </varlistentry>
87 </variablelist>
88 </sect2>
5189 </sect1>
5290 <sect1>
5391 <title>Client Side Filters</title>
96134 to register the filters and interceptors you want for the specific resource method. @NameBinding works a lot
97135 like CDI interceptors. You annotate a custom annotation with @NameBinding and then apply that custom annotation
98136 to your filter and resource method. The custom annotation must use @Retention(RetentionPolicy.RUNTIME) in order for the
99 attribute to be picked up by the Resteasy runtime code when it is deployed.
137 attribute to be picked up by the RESTEasy runtime code when it is deployed.
100138 </para>
101139 <programlisting>
102140 @NameBinding
0 <chapter id="JAX-RS_2.1_additions">
1 <title>JAX-RS 2.1 Additions</title>
2 <para>JAX-RS 2.1 adds more asynchronous processing support in both the
3 Client and the Server API. The specification adds a Reactive programming
4 style to the Client side and Server-Sent Events (SSE) protocol support to
5 both client and server.
6 </para>
7
8 <sect1>
9 <title><code>CompletionStage</code> support</title>
10 <para>
11 The specification adds support for declaring <link linkend="CompletionStage">asynchronous resource methods by
12 returning a <code>CompletionStage</code></link> instead of using the <code>@Suspended</code>
13 annotation.
14 </para>
15 <note>
16 <para>
17 RESTEasy <link linkend="Reactive">supports more reactive types than the specification</link>.
18 </para>
19 </note>
20 </sect1>
21
22 <sect1>
23 <title>Reactive Clients API</title>
24 <para>The specification defines a new type of invoker named RxInvoker, and a default
25 implementation of this type named CompletionStageRxInvoker.
26 CompletionStageRxInvoker implements Java 8's interface CompletionStage.
27 This interface declares a large number of methods dedicated to managing
28 asynchronous computations.
29 </para>
30 <para>There is also a new rx method which is used in a similar manner to async.
31 </para>
32 </sect1>
33
34 <sect1 id="SSE-Server">
35 <title>Server-Sent Events (SSE)</title>
36 <para>
37 SSE is part of HTML standard, currently supported by many browsers.
38 It is a server push technology, which provides a way to establish
39 a one-way channel to continuously send data to clients. SSE events are pushed
40 to the client via a long-running HTTP connection.
41 In case of lost connection, clients can retrieve missed events by setting a
42 "Last-Event-ID" HTTP header in a new request.
43 </para>
44 <para>
45 SSE stream has text/event-stream media type and contains multiple SSE events.
46 SSE event is a data structure encoded with UTF-8 and contains fields and comment.
47 The field can be event, data, id, retry and other kinds of field will be ignored.
48 </para>
49 <para>
50 From JAX-RS 2.1, Server-sent Events APIs are introduced to support sending, receiving and broadcasting SSE events.
51 </para>
52 <sect2>
53 <title>SSE Server</title>
54 <para>
55 As shown in the following example, a SSE resource method has the text/event-stream produce
56 media type and an injected context parameter SseEventSink. The injected SseEventSink is
57 the connected SSE stream where events can be sent. Another injected context Sse is an
58 entry point for creating and broadcasting SSE events. Here is an example to
59 demonstrate how to send SSE events every 200ms and close the stream after a "done" event.
60 </para>
61 <para>
62 <example>
63 <programlisting><![CDATA[
64 @GET
65 @Path("domains/{id}")
66 @Produces(MediaType.SERVER_SENT_EVENTS)
67 public void startDomain(@PathParam("id") final String id, @Context SseEventSink sink @Context Sse sse)
68 {
69 ExecutorService service = (ExecutorService) servletContext
70 .getAttribute(ExecutorServletContextListener.TEST_EXECUTOR);
71 service.execute(new Thread()
72 {
73 public void run()
74 {
75 try
76 {
77 sink.send(sse.newEventBuilder().name("domain-progress")
78 .data(String.class, "starting domain " + id + " ...").build());
79 Thread.sleep(200);
80 sink.send(sse.newEvent("domain-progress", "50%"));
81 Thread.sleep(200);
82 sink.send(sse.newEvent("domain-progress", "60%"));
83 Thread.sleep(200);
84 sink.send(sse.newEvent("domain-progress", "70%"));
85 Thread.sleep(200);
86 sink.send(sse.newEvent("domain-progress", "99%"));
87 Thread.sleep(200);
88 sink.send(sse.newEvent("domain-progress", "Done.")).thenAccept((Object obj) -> {
89 sink.close();
90 });
91 }
92 catch (final InterruptedException e)
93 {
94 logger.error(e.getMessage(), e);
95 }
96 }
97 });
98 }
99 ]]>
100 </programlisting>
101 </example>
102 </para>
103 <note>
104 <para>
105 RESTEasy <link linkend="Reactive">supports sending SSE events via reactive types</link>.
106 </para>
107 </note>
108 </sect2>
109 <sect2>
110 <title>SSE Broadcasting</title>
111 <para>
112 With SseBroadcaster, SSE events can be broadcasted to multiple clients simultaneously.
113 It will iterate over all registered SseEventSinks and send events to all requested SSE Stream.
114 An application can create a SseBroadcaster from an injected context Sse. The broadcast
115 method on a SseBroadcaster is used to send SSE events to all registered clients.
116 The following code snippet is an example on how to create SseBroadcaster, subscribe
117 and broadcast events to all subscribed consumers.
118 </para>
119 <para>
120 <example>
121 <programlisting><![CDATA[
122 @GET
123 @Path("/subscribe")
124 @Produces(MediaType.SERVER_SENT_EVENTS)
125 public void subscribe(@Context SseEventSink sink) throws IOException
126 {
127 if (sink == null)
128 {
129 throw new IllegalStateException("No client connected.");
130 }
131 if (sseBroadcaster == null)
132 {
133 sseBroadcaster = sse.newBroadcaster();
134 }
135 sseBroadcaster.register(sink);
136 }
137
138 @POST
139 @Path("/broadcast")
140 public void broadcast(String message) throws IOException
141 {
142 if (sseBroadcaster == null)
143 {
144 sseBroadcaster = sse.newBroadcaster();
145 }
146 sseBroadcaster.broadcast(sse.newEvent(message));
147
148 }
149 ]]>
150 </programlisting>
151 </example>
152 </para>
153 </sect2>
154 <sect2>
155 <title>SSE Client</title>
156 <para>
157 SseEventSource is the entry point to read and process incoming SSE events.
158 A SseEventSource instance can be initialized with a WebTarget. Once SseEventSource
159 is created and connected to a server, registered event consumer will be invoked when
160 an inbound event arrives. In case of errors, an exception will be passed
161 to a registered consumer so that it can be processed. SseEventSource can automatically reconnect the server
162 and continuously receive pushed events after the connection has been lost. SseEventSource
163 can send lastEventId to the server by default when it is reconnected, and server may use
164 this id to replay all missed events. But reply event is really upon on SSE resource
165 method implementation. If the server responds HTTP 503 with a RETRY_AFTER header,
166 SseEventSource will automatically schedule a reconnect task with this RETRY_AFTER
167 value. The following code snippet is to create a SseEventSource and print the
168 inbound event data value and error if it happens.
169 </para>
170 <para>
171 <example>
172 <programlisting><![CDATA[
173 public void printEvent() throws Exception
174 {
175 WebTarget target = client.target("http://localhost:8080/service/server-sent-events"));
176 SseEventSource msgEventSource = SseEventSource.target(target).build();
177 try (SseEventSource eventSource = msgEventSource)
178 {
179 eventSource.register(event -> {
180 System.out.println(event.readData(String.class));
181 }, ex -> {
182 ex.printStackTrace();
183 });
184 eventSource.open();
185 }
186 }
187 ]]>
188 </programlisting>
189 </example>
190 </para>
191 </sect2>
192 </sect1>
193 <sect1>
194 <title>Java API for JSON Binding</title>
195 <para>
196 RESTEasy supports both JSON-B and JSON-P. In accordance with the specification,
197 entity providers for JSON-B take precedence over those for JSON-P for all types
198 except JsonValue and its sub-types.
199 </para>
200 </sect1>
201 </chapter>
103103 @Consumes and @Produces can list multiple media types that they support. The client's Accept header can also send
104104 multiple types it might like to receive. More specific media types are chosen first. The client Accept header or
105105 @Produces @Consumes can also specify weighted preferences that are used to match up requests with resource
106 methods. This is best explained by RFC 2616 section 14.1 . Resteasy supports this complex way of doing content
106 methods. This is best explained by RFC 2616 section 14.1 . RESTEasy supports this complex way of doing content
107107 negotiation.
108108 </para>
109109 <para>
152152 @Produces("application/xml")
153153 public SomeJAXBObject get() {...}
154154 </programlisting>
155 <para>If you are confused, check the Resteasy source code for the implementation of @XmlHeader</para>
155 <para>If you are confused, check the RESTEasy source code for the implementation of @XmlHeader</para>
156156 </sect1>
157157 <sect1 id="Pluggable_JAXBContext_s_with_ContextResolvers">
158158 <title>Pluggable JAXBContext's with ContextResolvers</title>
228228 <sect1 id="JAXB_+_XML_provider">
229229 <title>JAXB + XML provider</title>
230230 <para>
231 Resteasy is required to provide JAXB provider support for XML. It has a few extra annotations
231 RESTEasy is required to provide JAXB provider support for XML. It has a few extra annotations
232232 that can help code your app.
233233 </para>
234234 <sect2 id="XmlHeader">
235235 <title>@XmlHeader and @Stylesheet</title>
236 <para>Sometimes when outputting XML documents you may want to set an XML header. Resteasy provides
236 <para>Sometimes when outputting XML documents you may want to set an XML header. RESTEasy provides
237237 the @org.jboss.resteasy.annotations.providers.jaxb.XmlHeader annotation for this. For example:</para>
238238 <programlisting><![CDATA[
239239 @XmlRootElement
273273 details on how you can use substitution values provided by resteasy.
274274 </para>
275275 <para>
276 Resteasy also has a convenience annotation for stylesheet headers. For example:
276 RESTEasy also has a convenience annotation for stylesheet headers. For example:
277277 </para>
278278 <programlisting><![CDATA[
279279 @XmlRootElement
316316 <para>
317317
318318 RESTEasy allows you to marshall JAXB annotated POJOs to and from JSON. This provider wraps the Jettison JSON
319 library to accomplish this. You can obtain more information about Jettison and how it works from:
320 </para>
321 <para>
322 http://jettison.codehaus.org/
323 </para>
324 <para>
319 library to accomplish this. You can obtain more information about Jettison and how it works from
320 <ulink url="https://github.com/jettison-json/jettison">https://github.com/jettison-json/jettison</ulink>.
321 </para>
322 <para>
325323 To use this integration with Jettision you need to import the resteasy-jettison-provider Maven module. Older versions
326324 of RESTEasy used to include this within the resteasy-jaxb-provider but we decided to modularize it more.
327325 </para>
773771
774772 <sect2 id="json_list">
775773 <title>JSON and JAXB Collections/arrays</title>
776 <para>Resteasy supports using collections with JSON. It encloses lists, sets, or arrays of returned JAXB objects within a simple
774 <para>RESTEasy supports using collections with JSON. It encloses lists, sets, or arrays of returned JAXB objects within a simple
777775 JSON array. For example:</para>
778776 <programlisting>
779777 @XmlRootElement
948946 For more information about <classname>GenericType</classname>, please see its javadoc.
949947 </para>
950948 </sect2>
951
949
952950 <sect2 id="json_map">
953951 <title>JSON and JAXB maps</title>
954 <para>Resteasy supports using maps with JSON. It encloses maps returned JAXB objects within a simple
952 <para>RESTEasy supports using maps with JSON. It encloses maps returned JAXB objects within a simple
955953 JSON map. For example:</para>
956954 <programlisting>
957955 @XmlRootElement
00 <chapter id="json-p">
11 <title>JSON Support via Java EE 7 JSON-P API</title>
22 <para>No, this is not the JSONP you are thinking of! JSON-P is a new Java EE 7 JSON parsing API. Horrible name for
3 a new JSON parsing API! What were they thinking? Anyways, Resteasy has
3 a new JSON parsing API! What were they thinking? Anyways, RESTEasy has
44 a provider for it. If you are using WildFly, it is required by Java EE 7 so you will have it automatically bundled.
55 Otherwise, use this maven dependency.
66 </para>
88 <dependency>
99 <groupId>org.jboss.resteasy</groupId>
1010 <artifactId>resteasy-json-p-provider</artifactId>
11 <version>3.1.4.Final</version>
11 <version>3.5.0.Final</version>
1212 </dependency>
1313 ]]></programlisting>
1414 <para>
00 <chapter id="json">
11 <title>JSON Support via Jackson</title>
2 <para>Besides the Jettision JAXB adapter for JSON, Resteasy also supports integration with the Jackson project.
2 <para>Besides the Jettision JAXB adapter for JSON, RESTEasy also supports integration with the Jackson project.
33 Many users find the output from Jackson much nicer than the Badger format or Mapped format provided by Jettison.
44 For more on Jackson 2, see <ulink url="http://wiki.fasterxml.com/JacksonHome">http://wiki.fasterxml.com/JacksonHome</ulink>.
55 Besides JAXB like APIs, it has a JavaBean based model, described at
66 <ulink url="http://wiki.fasterxml.com/JacksonDataBinding">http://wiki.fasterxml.com/JacksonDataBinding</ulink>,
77 which allows you to easily marshal Java objects to and from JSON.
8 Resteasy integrates with the JavaBean model.
9 While Jackson does come with its own JAX-RS integration, Resteasy expanded it a little, as decribed below.
8 RESTEasy integrates with the JavaBean model.
9 While Jackson does come with its own JAX-RS integration, RESTEasy expanded it a little, as decribed below.
1010 </para>
1111 <para>
1212 <emphasis role="bold">NOTE.</emphasis> The resteasy-jackson-provider module, which is based on the outdated Jackson 1.9.x, is
1616
1717 <sect1>
1818 <title>Using Jackson 1.9.x Outside of WildFly</title>
19 <para>If you're deploying Resteasy outside of WildFly,
20 add the Resteasy Jackson provder to your WAR pom.xml build:</para>
19 <para>If you're deploying RESTEasy outside of WildFly,
20 add the RESTEasy Jackson provder to your WAR pom.xml build:</para>
2121 <programlisting><![CDATA[
2222 <dependency>
2323 <groupId>org.jboss.resteasy</groupId>
2828 </sect1>
2929 <sect1>
3030 <title>Using Jackson 1.9.x Inside WildFly 8</title>
31 <para>If you're deploying Resteasy with WildFly 8,
31 <para>If you're deploying RESTEasy with WildFly 8,
3232 there's nothing you need to do except to make sure
33 you've updated your installation with the latest and greatest Resteasy. See the
33 you've updated your installation with the latest and greatest RESTEasy. See the
3434 <link linkend='Installation_Configuration'>Installation/Configuration</link> section
3535 of this documentation for more details.</para>
3636 </sect1>
3737 <sect1>
3838 <title>Using Jackson 2 Outside of WildFly</title>
39 <para>If you're deploying Resteasy outside of WildFly,
40 add the Resteasy Jackson provder to your WAR pom.xml build:</para>
39 <para>If you're deploying RESTEasy outside of WildFly,
40 add the RESTEasy Jackson provder to your WAR pom.xml build:</para>
4141 <programlisting><![CDATA[
4242 <dependency>
4343 <groupId>org.jboss.resteasy</groupId>
4848 </sect1>
4949 <sect1>
5050 <title>Using Jackson 2 Inside WildFly 9 and above</title>
51 <para>If you're deploying Resteasy with WildFly 9 or above,
51 <para>If you're deploying RESTEasy with WildFly 9 or above,
5252 there's nothing you need to do except to make sure
53 you've updated your installation with the latest and greatest Resteasy. See the
53 you've updated your installation with the latest and greatest RESTEasy. See the
5454 <link linkend='Installation_Configuration'>Installation/Configuration</link> section
5555 of this documentation for more details.</para>
5656 </sect1>
5757 <sect1>
58 <title>Additional Resteasy Specifics</title>
59
60 <para>The first extra piece that Resteasy added to the integration was
58 <title>Additional RESTEasy Specifics</title>
59
60 <para>The first extra piece that RESTEasy added to the integration was
6161 to support "application/*+json". Jackson would only accept "application/json" and "text/json" as valid
6262 media types. This allows you to create json-based media types and still
6363 let Jackson marshal things for you. For example:
7171 public Customer[] getCustomers() {}
7272 }
7373 ]]></programlisting>
74 <para>Another problem that occurs is when you are using the Resteasy JAXB providers alongside Jackson.
74 <para>Another problem that occurs is when you are using the RESTEasy JAXB providers alongside Jackson.
7575 You may want to use Jettison and JAXB to output your JSON instead of Jackson. In this case, you must
7676 either not install the Jackson provider, or use the annotation
7777 @org.jboss.resteasy.annotations.providers.NoJackson
124124 <sect1 id="JSONP_Support">
125125 <title>JSONP Support</title>
126126 <para>
127 If you're using Jackson, Resteasy has <ulink url="http://en.wikipedia.org/wiki/JSONP">JSONP</ulink> that you can turn on by adding
127 If you're using Jackson, RESTEasy has <ulink url="http://en.wikipedia.org/wiki/JSONP">JSONP</ulink> that you can turn on by adding
128128 the provider <literal>org.jboss.resteasy.plugins.providers.jackson.JacksonJsonpInterceptor</literal> (Jackson2JsonpInterceptor if you're using the Jackson2 provider)
129129 to your deployments.
130130 If the media type of the response is json and a callback query parameter is given, the response will be a javascript snippet with
181181 <sect1 id="Jackson_JSON_Decorator">
182182 <title>Jackson JSON Decorator</title>
183183 <para>
184 If you are using the Jackson 2 provider, Resteasy has provided a pretty-printing annotation simliar with the one in JAXB provider:
184 If you are using the Jackson 2 provider, RESTEasy has provided a pretty-printing annotation simliar with the one in JAXB provider:
185185 <programlisting>
186186 org.jboss.resteasy.annotations.providers.jackson.Formatted
187187 </programlisting>
250250 }
251251 ]]>
252252 </programlisting>
253 Here the method <methodname>modify()</methodname> will take care of filtering all properties except "name" property before write. To make this work, we need let Resteasy know this mapping info. This can be easily set either in a WriterInterceptor:
253 Here the method <methodname>modify()</methodname> will take care of filtering all properties except "name" property before write. To make this work, we need let RESTEasy know this mapping info. This can be easily set either in a WriterInterceptor:
254254 <programlisting>
255255 <![CDATA[
256256 @Provider
292292 }
293293 ]]>
294294 </programlisting>
295 Resteasy get this modfiler from ThreadLocal variable and configure to modify ObjectWriter before write to response.
295 RESTEasy get this modfiler from ThreadLocal variable and configure to modify ObjectWriter before write to response.
296296 </para>
297297 </sect1>
298298 </chapter>
5151 <tr>
5252 <td>org.jboss.resteasy</td>
5353 <td>resteasy-links</td>
54 <td>3.1.4.Final</td>
54 <td>3.5.0.Final</td>
5555 </tr>
5656 </tbody>
5757 </table>
55 </para>
66 <para>
77
8 RESTEasy is modularized into 20 plus components. Each component is accessible as a Maven
9 artifact. As a convenience RESTEasy provides a BOM containing the complete set of components
10 with the appropriate versions for the "stack".
8 Here's the pom.xml fragment to use. RESTEasy is modularized into various components. Mix and max as you see fit. Please replace 3.5.0.Final with the current RESTEasy version you want to use.
119 </para>
12 <para>
13 It is recommended to declare the BOM in your POM file, that way you will always
14 be sure to get the correct version of the artifacts. In addition, you will not need
15 to declare the version of each RESTEasy artifact called out in the dependencies section.
16 </para>
17 <para>
18 Declare the BOM file in the dependencyManagement section of the POM file like this.
19 Note that Maven version 2.0.9 or higher is required to process BOM files.
20 </para>
21 <programlisting>
22 <![CDATA[
10 <programlisting>
11 <![CDATA[
12 <repositories>
13 <repository>
14 <id>jboss</id>
15 <url>http://repository.jboss.org/nexus/content/groups/public/</url>
16 </repository>
17 </repositories>
18 <dependencies>
19 <!-- core library -->
20 <dependency>
21 <groupId>org.jboss.resteasy</groupId>
22 <artifactId>resteasy-jaxrs</artifactId>
23 <version>3.5.0.Final</version>
24 </dependency>
25 <dependency>
26 <groupId>org.jboss.resteasy</groupId>
27 <artifactId>resteasy-client</artifactId>
28 <version>3.5.0.Final</version>
29 </dependency>
30
31 <!-- optional modules -->
32
33 <!-- JAXB support -->
34 <dependency>
35 <groupId>org.jboss.resteasy</groupId>
36 <artifactId>resteasy-jaxb-provider</artifactId>
37 <version>3.5.0.Final</version>
38 </dependency>
39 <!-- multipart/form-data and multipart/mixed support -->
40 <dependency>
41 <groupId>org.jboss.resteasy</groupId>
42 <artifactId>resteasy-multipart-provider</artifactId>
43 <version>3.5.0.Final</version>
44 </dependency>
45 <!-- RESTEasy Server Cache -->
46 <dependency>
47 <groupId>org.jboss.resteasy</groupId>
48 <artifactId>resteasy-cache-core</artifactId>
49 <version>3.5.0.Final</version>
50 </dependency>
51 <!-- Ruby YAML support -->
52 <dependency>
53 <groupId>org.jboss.resteasy</groupId>
54 <artifactId>resteasy-yaml-provider</artifactId>
55 <version>3.5.0.Final</version>
56 </dependency>
57 <!-- JAXB + Atom support -->
58 <dependency>
59 <groupId>org.jboss.resteasy</groupId>
60 <artifactId>resteasy-atom-provider</artifactId>
61 <version>3.5.0.Final</version>
62 </dependency>
63 <!-- Spring integration -->
64 <dependency>
65 <groupId>org.jboss.resteasy</groupId>
66 <artifactId>resteasy-spring</artifactId>
67 <version>3.5.0.Final</version>
68 </dependency>
69 <!-- Guice integration -->
70 <dependency>
71 <groupId>org.jboss.resteasy</groupId>
72 <artifactId>resteasy-guice</artifactId>
73 <version>3.5.0.Final</version>
74 </dependency>
75
76 <!-- Asynchronous HTTP support with Servlet 3.0 -->
77 <dependency>
78 <groupId>org.jboss.resteasy</groupId>
79 <artifactId>async-http-servlet-3.0</artifactId>
80 <version>3.5.0.Final</version>
81 </dependency>
82
83 </dependencies>
84 ]]>
85 </programlisting>
86 <para>
87 There is also a pom that can be imported so the versions of the individual modules do not have to be specified. Note that maven 2.0.9 is required for this.
88 </para>
89 <programlisting>
90 <![CDATA[
2391 <dependencyManagement>
24 <dependencies>
25 <dependency>
26 <groupId>org.jboss.resteasy</groupId>
27 <artifactId>resteasy-bom</artifactId>
28 <version>${version.resteasy}</version>
29 <type>pom</type>
30 <scope>import</scope>
31 </dependency>
32 </dependencies>
92 <dependencies>
93 <dependency>
94 <groupId>org.jboss.resteasy</groupId>
95 <artifactId>resteasy-bom</artifactId>
96 <version>3.5.0.Final</version>
97 <type>pom</type>
98 <scope>import</scope>
99 </dependency>
100 </dependencies>
33101 </dependencyManagement>
34 ]]>
35 </programlisting>
36 <para>
37 Declare the specific RESTEasy artifacts you require in the dependencies section of the
38 POM file like this.
39 </para>
40 <programlisting>
41 <![CDATA[
42 <dependencies>
43 <dependency>
44 <groupId>org.jboss.resteasy</groupId>
45 <artifactId>resteasy-client</artifactId>
46 </dependency>
47 ....
48 </dependencies>
49 ]]>
50 </programlisting>
51 <para>
52 It is possible to reference a RESTEasy artifact version not in the current BOM
53 by specifying a version in the dependency itself.
54 </para>
55 <programlisting>
56 <![CDATA[
57 <dependencies>
58 <dependency>
59 <groupId>org.jboss.resteasy</groupId>
60 <artifactId>resteasy-client</artifactId>
61 <version>${version.some.other}<version>
62 </dependency>
63 ....
64 </dependencies>
65 ]]>
66 </programlisting>
67
102 ]]>
103 </programlisting>
68104 </chapter>
00 <chapter id="Migration_from_older_versions">
11 <title>Migration from older versions</title>
22 <sect1>
3 <title>Migrating from Resteasy 2 to Resteasy 3</title>
3 <title>Migrating from RESTEasy 2 to RESTEasy 3</title>
44
55 <para>
6 Many facilities from Resteasy 2 appear in a different form in Resteasy 3. For example, much
7 of the client framework in Resteasy 2 is formalized, in modified form, in JAX-RS 2.0. Resteasy
6 Many facilities from RESTEasy 2 appear in a different form in RESTEasy 3. For example, much
7 of the client framework in RESTEasy 2 is formalized, in modified form, in JAX-RS 2.0. RESTEasy
88 versions 3.0.x implement both the older deprecated form and the newer conformant form. The
9 deprecated form is finally removed in Resteasy 3.1.0.Final. For more information on upgrading
10 from various deprecated facilities in Resteasy 2, see
9 deprecated form is moved to legacy module in RESTEasy 3.1 and finally removed in RESTEasy 4.
10 For more information on upgrading from various deprecated facilities in RESTEasy 2, see
1111 <ulink url="http://docs.jboss.org/resteasy/docs/resteasy-upgrade-guide-en-US.pdf">http://docs.jboss.org/resteasy/docs/resteasy-upgrade-guide-en-US.pdf</ulink>
1212 </para>
1313 </sect1>
1414 <sect1>
15 <title>Migrating to 3.0.17</title>
15 <title>Migrating from 3.0.x to 4.0.0</title>
1616 <itemizedlist>
1717 <listitem>
18 Module resteasy-spring is now included in the Resteasy distribution zip file. For more information see
19 <ulink url="https://issues.jboss.org/browse/RESTEASY-1354">https://issues.jboss.org/browse/RESTEASY-1354</ulink>.
20 </listitem>
21 <listitem>
22 Resteasy client proxies now support an <methodname>as()</methodname> method for casting to subinterfaces.
23 For more information see
24 <ulink url="https://issues.jboss.org/browse/RESTEASY-1332">https://issues.jboss.org/browse/RESTEASY-1332</ulink>.
25 </listitem>
26 <listitem>
27 <classname>org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer</classname> in module resteasy-netty4
28 can now be configured to close idle connections. For more information see
29 <ulink url="https://issues.jboss.org/browse/RESTEASY-1325">https://issues.jboss.org/browse/RESTEASY-1325</ulink>.
30 </listitem>
31 <listitem>
32 Resteasy Spring integration now includes a Spring Boot Starter. For more information see
33 <ulink url="https://issues.jboss.org/browse/RESTEASY-1305">https://issues.jboss.org/browse/RESTEASY-1305</ulink>.
34 </listitem>
35 <listitem>
36 resteasy-wadl now supports subresource locators. For more information see
37 <ulink url="https://issues.jboss.org/browse/RESTEASY-1297">https://issues.jboss.org/browse/RESTEASY-1297</ulink>.
38 </listitem>
39 <listitem>
40 Resteasy has a new builtin producer that implements <classname>MessageBodyWriter&lt;Number&gt;</classname>. For more information see
41 <ulink url="https://issues.jboss.org/browse/RESTEASY-1282">https://issues.jboss.org/browse/RESTEASY-1282</ulink>.
42 </listitem>
43 <listitem>
44 Links can be added manually to <classname>org.jboss.resteasy.Links.RESTServiceDiscovery</classname> in resteasy-links module.
45 See <ulink url="https://issues.jboss.org/browse/RESTEASY-833">https://issues.jboss.org/browse/RESTEASY-833</ulink> for more information.
18 In releases 3.0.x, when bean validation (<xref linkend="Validation"/>) threw instances of exceptions
19 <itemizedlist>
20 <listitem><classname>javax.validation.ConstraintDefinitionException</classname>,</listitem>
21 <listitem><classname>javax.validation.ConstraintDeclarationException</classname>, or</listitem>
22 <listitem><classname>javax.validation.GroupDefinitionException</classname>,</listitem>
23 </itemizedlist>
24 <para>
25 they were wrapped in a
26 <classname>org.jboss.resteasy.api.validation.Resteasy.ResteasyViolationException</classname>,
27 which <classname>org.jboss.resteasy.api.validation.ResteasyViolationExceptionMapper</classname>,
28 the built-in implementation of
29 <classname>javax.ws.rs.ext.ExceptionMapper&lt;javax.validation.ValidationException&gt;</classname>,
30 then turned into descriptive text.
31 As of release 4.0.0, instances of <classname>ConstraintDefinitionException</classname>, etc., are thrown as is.
32 They are still caught by <classname>ResteasyViolationExceptionMapper</classname>, so, in general, there is
33 no detectable change. It should be noted, however, that an implementation of
34 <classname>ExceptionMapper&lt;ResteasyViolationException&gt;</classname>, which, prior to release
35 4.0.0, would have caught wrapped instances of <classname>ConstraintDefinitionException</classname>,
36 will not catch unwrapped instances.
37 </para>
4638 </listitem>
4739 </itemizedlist>
4840 </sect1>
49 <sect1>
50 <title>Migrating from 3.0.13 to 3.0.14</title>
51 <itemizedlist>
52 <listitem>
53 Resteasy introduces a <classname>@QueryParam</classname> annotation which allows capturing the name of
54 a query parameter. See <ulink url="https://issues.jboss.org/browse/RESTEASY-715">https://issues.jboss.org/browse/RESTEASY-715</ulink>
55 for more information.
56 </listitem>
57 <listitem>Resteasy now supports WADL. See <xref linkend="WADL"/> for more information. Also see
58 <ulink url="https://issues.jboss.org/browse/RESTEASY-166">https://issues.jboss.org/browse/RESTEASY-166</ulink>.
59 </listitem>
60 </itemizedlist>
61 </sect1>
62 <sect1>
63 <title>Migrating from 3.0.12 to 3.0.13</title>
64 <itemizedlist>
65 <listitem>Resteasy 3 log messages and exceptions are now internationalized. See
66 <xref linkend="I18N"/> for more information. Also see
67 <ulink url="https://issues.jboss.org/browse/RESTEASY-1224">https://issues.jboss.org/browse/RESTEASY-1224</ulink>.
68 </listitem>
69 <listitem><literallayout><classname>org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder</classname> has a new method,
70 <methodname>asyncExecutor(ExecutorService asyncExecutor, boolean cleanupExecutor)</methodname>, with a new
71 second parameter which tells the <classname>Client</classname> to shut down the Executor upon closing. See
72 <ulink url="https://issues.jboss.org/browse/RESTEASY-1181">https://issues.jboss.org/browse/RESTEASY-1181</ulink> for more information.
73 </literallayout>
74 </listitem>
75 </itemizedlist>
76 </sect1>
77 <sect1>
78 <title>Migrating to 3.0.12</title>
79 <itemizedlist>
80 <listitem>
81 <methodname>org.jboss.resteasy.client.jaxrs.ResteasyClient.property()</methodname> will now
82 remove a property when the value is set to null. See
83 <ulink url="https://issues.jboss.org/browse/RESTEASY-1184">https://issues.jboss.org/browse/RESTEASY-1184</ulink> for more information.
84 </listitem>
85 <listitem>
86 <literallayout><classname>org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer</classname> in module resteasy-netty4
87 has a new method, <methodname>setHttpChannelHandlers()</methodname>, that allows adding channel handlers that are
88 processed after the HTTP handlers. See
89 <ulink url="https://issues.jboss.org/browse/RESTEASY-1171">https://issues.jboss.org/browse/RESTEASY-1171</ulink> for more information.
90 </literallayout>
91 </listitem>
92 <listitem><literallayout><classname>org.jboss.resteasy.api.validation.ResteasyViolationException</classname> is now a subclass of
93 <classname>javax.validation.ConstraintViolationException</classname> instead of
94 <classname>javax.validation.ValidationException</classname>. Now, an <classname>ExceptionMapper</classname> for
95 <classname>ConstraintViolationException</classname> will catch <classname>ResteasyViolationException</classname>s.
96 See <ulink url="https://issues.jboss.org/browse/RESTEASY-1137">https://issues.jboss.org/browse/RESTEASY-1137</ulink> for more information.</literallayout>
97 </listitem>
98 <listitem><literallayout>There is a new context parameter, "resteasy.buffer.exception.entity". See
99 <xref linkend="configuration_switches"/> for more information. Also, see
100 <ulink url="https://issues.jboss.org/browse/RESTEASY-981">https://issues.jboss.org/browse/RESTEASY-981</ulink>.
101 </literallayout>
102 </listitem>
103 </itemizedlist>
104 </sect1>
105 <sect1>
106 <title>Migrating from 3.0.7 to 3.0.9</title>
107 <itemizedlist>
108 <listitem>
109 You may need to upgrade your JDK to the latest 1.7.x or 1.8 releases if you are using JAXB. There's some
110 entity expansion security vulnerabilities that we had to patch and it seems the fix doesn't work on earlier
111 versions of JDK 1.7.
112 </listitem>
113 <listitem>
114 ContainerRequestContext.setRequestUri() method behavior has been changed to match the behavior of the JAXRS RI.
115 The relative URI must be equal to are an extension of the base URI or it will not work. i.e.
116 <programlisting>
117 context.setRequestUri(URI.create("https://foo.com/base"),
118 URI.create("https://foo.com/base/path")); // legal
119 context.setRequestUri(URI.create("https://foo.com/base"),
120 URI.create("/path")); // "path" is ignored
121 // if base uri is "http://foo.com/base"
122 context.setRequestUri(URI.create("http://foo.com/base/path")); // legal
123 context.setRequestUri(URI.create("/path")); // ignored
124 </programlisting>
125 </listitem>
126 </itemizedlist>
127 </sect1>
128
129 <sect1>
130 <title>Migrating from 3.0.6 to 3.0.7</title>
131 <itemizedlist>
132 <listitem>
133 Scannotation has been removed. If you are not running within an application server you must use the
134 ResteasyServletInitializer. See docs for more detail.
135 </listitem>
136 </itemizedlist>
137 </sect1>
138 <sect1>
139 <title>Migrating from 3.0 to 3.0.4</title>
140 <itemizedlist>
141 <listitem>
142 Servlet 3.0 deployments within standalone Tomcat or Jetty can now use the Resteasy <literal>ServletContainerInitializer</literal>.
143 This allows tighter integration with Resteasy much like you have within JBoss/WildFly. Check out
144 <xref linkend="Installation_Configuration"/> for more information.
145 </listitem>
146 </itemizedlist>
147 </sect1>
148 <sect1>
149 <title>Migrating from 3.0-beta-6 and 3.0-rc-1</title>
150 <itemizedlist>
151 <listitem>
152 Form parameters are now read via a provider where earlier they were read from HttpServletRequest.getParameterMap().
153 This may break deployments that depend on that behavior, i.e. if you have a servlet filter that calls that very method.
154 For those situations I added the switch resteasy.use.container.form.params
155 </listitem>
156 <listitem>
157 The JAX-RS TCK has become very strict with a ton more tests. I can't remember them all, but there are a number
158 of edge cases which earlier Resteasy releases misinterpreted.
159 </listitem>
160 <listitem>
161 Any Failure exceptions in the SPI now have a corresponding JAX-RS 2.0 exception, so they have been deprecated
162 Resteasy no longer uses these old SPI exceptions internally. It now uses the JAX-RS 2.0 ones.
163 </listitem>
164 <listitem>
165 A number of SPIs have changed. Shouldn't be an issue for those of you who use Restasy as-is. Specifically
166 InjectorFactory and Registry have changed.
167 </listitem>
168 </itemizedlist>
169 </sect1>
170 <sect1>
171 <title>Migrating from 3.0-beta-5 and 3.0-beta-6</title>
172 <itemizedlist>
173 <listitem>
174 The JAX-RS 2.0 TCK has become very very strict in terms of the matching algorithm. Unfortunately, the matching
175 algorithm is quite poor so there are a number of resource schemes that will no longer match.
176 For example, resource classes are scanned for a best match, other are ignored in the match.
177 Resource locators are not visited unless they are a best match over resource methods. There is one config switch
178 I added so that Resteasy will ignore the Spec defined class expression filtering step and instead match
179 base on the full expressions of each JAX-RS method. resteasy.wider.request.matching. Set that to true
180 and you will at least be able to avoid that.
181 </listitem>
182 <listitem>
183 The JAX-RS TCK has become very strict with a ton more tests. I can't remember them all, but there are a number
184 of edge cases which earlier Resteasy releases misinterpreted.
185 </listitem>
186 <listitem>
187 Any Failure exceptions in the SPI now have a corresponding JAX-RS 2.0 exception, so they have been deprecated
188 Resteasy no longer uses these old SPI exceptions internally. It now uses the JAX-RS 2.0 ones.
189 </listitem>
190 <listitem>
191 A number of SPIs have changed. Shouldn't be an issue for those of you who use Restasy as-is. Specifically
192 InjectorFactory and Registry have changed.
193 </listitem>
194 </itemizedlist>
195 </sect1>
196 <sect1>
197 <title>Migrating from 3.0-beta-4 and 3.0-beta-5</title>
198 <itemizedlist>
199 <listitem>
200 JSONP support is no longer on by default. A few users have complained that it is a security hole for their applications.
201 </listitem>
202 <listitem>
203 A number of SPIs have changed. Shouldn't be an issue for those of you who use Restasy as-is. Specifically
204 InjectorFactory and Registry have changed.
205 </listitem>
206 </itemizedlist>
207 </sect1>
208 <sect1>
209 <title>Migrating from 3.0-beta-2 and 3.0-beta-4</title>
210 <itemizedlist>
211 <listitem>
212 The JAX-RS 2.0 class ClientFactory no longer exists. It has been replaced with ClientBuilder. You can
213 still call newClient(), but there is now an additional builder interface. Likewise, there is no
214 ResteasyClientFactory. We also have an extension to ClientBuilder called ResteasyClientBuilder. So docs
215 for more details.
216 </listitem>
217 <listitem>
218 Filter execution and exception handling now matches the JAX-RS 2.0 spec. Exceptions thrown from filters/interceptors
219 can now be mapped if possible. Responses returned from ExceptionMappers are now filtered.
220 </listitem>
221 </itemizedlist>
222 </sect1>
223 <sect1>
224 <title>Migrating from 3.0-beta-1 and 3.0-beta-2</title>
225 <itemizedlist>
226 <listitem>
227 The constructors for ResteasyClient class are no longer public. You need to use the new ResteasyClientBuilder
228 class. One thing to note is that when a ResteasyClient is created by a builder, it no longer
229 uses ResteasyProviderFactory.getInstance(), but instead instantiates a new one. This will probably
230 not effect most uses.
231 </listitem>
232 </itemizedlist>
233 </sect1>
234 <sect1>
235 <title>Migrating from 2.x to 3.0-beta-1</title>
236 <itemizedlist>
237 <listitem>
238 Resteasy manual client API, interceptors, StringConverters, StringParamterConverters, and Async HTTP APIs have all been
239 deprecated and will be removed possibly in a later release. There is now a JAX-RS 2.0 equivalent for each
240 of these things.
241 </listitem>
242 <listitem>
243 resteasy-crypto: SignedInput and SignedOutput must have a multipart/signed content type set either through
244 the request or response object, or by annotation @Consumes/@Produces
245 </listitem>
246 <listitem>
247 Server-side cache setup has been changed. Please see documentation for more details.
248 </listitem>
249 <listitem>
250 The security filters for @RolesAllowed, etc. now return 403, Forbidden instead of 401.
251 </listitem>
252 <listitem>
253 Most add() methods have been removed or made protected in ResteasyProviderFactory. Use registerProvider() and registerProviderInstance() methods.
254 </listitem>
255 <listitem>
256 The new JAX-RS 2.0 client-side filters will not be bound and run when you are using Resteasy's old client api.
257 </listitem>
258 <listitem>
259 On server-side, all old Resteasy interceptors can run in parallel with the new JAX-RS 2.0 filter and interceptor
260 interfaces.
261 </listitem>
262 <listitem>
263 Some SPIs have changed. This should not effect applications unless you are doing something you aren't supposed
264 to do.
265 </listitem>
266 <listitem>
267 The async tomcat and async jboss web modules have been removed. If you are not running under Servlet 3.0,
268 async HTTP server-side, will be faked and run synchronously in same request thread.
269 </listitem>
270 </itemizedlist>
271 </sect1>
272 <sect1>
273 <title>Migrating from 2.3.2 to 2.3.3</title>
274 <itemizedlist>
275 <listitem>
276 MultipartInput has a new close() method. If you have a read body that is MultipartInput or one of
277 its subinterfaces, then you must call this method to clean up any temporary files created. Otherwise,
278 these possible temporary files are deleted on GC or JDK shutdown. Other multipart providers clean up
279 automatically.
280 </listitem>
281 </itemizedlist>
282 </sect1>
283 <sect1>
284 <title>Migrating from 2.3.0 to 2.3.1</title>
285 <itemizedlist>
286 <listitem>
287 sjsxp has been removed as a dependency for the Resteasy JAXB provider
288 </listitem>
289 </itemizedlist>
290 </sect1>
291 <sect1>
292 <title>Migrating from 2.2.x to 2.3</title>
293 <itemizedlist>
294 <listitem>
295 The Apache Abdera integration has been removed as a project. If you want the integration back, please
296 ping our dev lists or open a JIRA.
297 </listitem>
298 <listitem>
299 Apache Http Client 4.x is now the default underlying client HTTP mechanism. If there are problems, you
300 can change the default mechanism by calling ClientRequest.setDefaultExecutorClass.
301 </listitem>
302 <listitem>
303 ClientRequest no longer supports a shared default executor. The
304 <code>createPerRequestInstance</code> parameter has been removed from
305 <methodname>ClientRequest.setDefaultExecutorClass()</methodname>.
306 </listitem>
307 <listitem>
308 resteasy-doseta module no longer exists. It is now renamed to the resteasy-crypto module and also includes other things beyond doseta.
309 </listitem>
310 <listitem>
311 Doseta work has be refactored a bit and may have broken backward compatibility.
312 </listitem>
313 <listitem>
314 Jackson has been upgraded from 1.6.3 to 1.8.5. Let me know if there are any issues.
315 </listitem>
316 <listitem>
317 Form parameter processing behavior was modified because of RESTEASY-574. If you are having problems with form paramater processing on Tomcat after
318 this fix, please log a JIRA or contact the resteasy-developers email list.
319 </listitem>
320 <listitem>
321 Some subtle changes were made to ExceptionMapper handling so that you can write ExceptionMappers for any exception thrown internally or within
322 your application. See JIRA Issue RESTEASY-595 for more details. This may have an effect on existing applications that have an ExceptionMapper
323 for RuntimeException in that you will start to see Resteasy internal exceptions being caught by this kind of ExceptionMapper.
324 </listitem>
325 <listitem>
326 The resteasy-cache (Server-side cache) will now invalidate the cache when a PUT, POST, or DELETE is done on a particular URI.
327 </listitem>
328 </itemizedlist>
329 </sect1>
330 <sect1 id="22_221">
331 <title>Migrating from 2.2.0 to 2.2.1</title>
332 <itemizedlist>
333 <listitem>
334 Had to upgrade JAXB libs from 2.1.x to 2.2.4 as there was a concurrency bug in JAXB impl.
335 </listitem>
336 </itemizedlist>
337 </sect1>
338 <sect1 id="21_22">
339 <title>Migrating from 2.1.x to 2.2</title>
340 <itemizedlist>
341 <listitem>
342 ClientRequest.getHeaders() always returns a copy. It also converts the values within
343 ClientRequest.getHeadersAsObjects() to string. If you
344 add values to the map returned by getHeaders() nothing happen. Instead add values to the
345 getHeadersAsObjects() map. This allows non-string header objects
346 to propagate through the MessageBodyWriter interceptor and ClientExecutor interceptor chains.
347 </listitem>
348 </itemizedlist>
349 </sect1>
350 <sect1 id="20_21">
351 <title>Migrating from 2.0.x to 2.1</title>
352 <itemizedlist>
353 <listitem>
354 Slf4j is no longer the default logging mechanism for resteasy. Resteasy also no longer ships with SLF4J
355 libraries. Please read the logging
356 section in the Installation and Configuration chapter for more details.
357 </listitem>
358 <listitem>
359 The constructor used to instantiate resource and provider classes is now picked based on the requirements of
360 the JAX-RS specification.
361 Specifically, the public constructor with the most arguments is picked. This behavior varies from previous
362 versions where a no-arg
363 constructor is preferred.
364 </listitem>
365 </itemizedlist>
366 </sect1>
367 <sect1 id="Migrating_to_Resteasy_12_20">
368 <title>Migrating from 1.2.x to 2.0</title>
369
370 <para>
371
372 <itemizedlist>
373 <listitem>
374 TJWS has been forked to fix some bugs. The new groupId is org.jboss.resteasy, the artifactId is
375 tjws. It will match the resteasy distribution version
376 </listitem>
377 <listitem>
378 Please check out the JBoss 6 integration. It makes things a lot easier if you are deploying in that
379 environment
380 </listitem>
381 <listitem>
382 There is a new Filter implementation that is the preferred deployment mechanism. Servlet-based
383 deployments are still supported, but it is suggested you use to using a FilterDispatcher. See
384 documentation for more details.
385 </listitem>
386 <listitem>
387 As per required by the spec List or array injection of empty values will return an empty collection
388 or array, not null. I.e.
389 (@QueryParam("name") List&lt;String&gt; param) param will be an empty List. Resteasy 1.2.x and
390 earlier would return null.
391 </listitem>
392 <listitem>
393 We have forked TJWS, the servlet container used for embedded testing into the group
394 org.jboss.resteasy, with the artifact id of tjws. You will need
395 to remove these dependencies from your maven builds if you are using any part of the resteasy
396 embeddable server. TJWS has a number of startup/shutdown
397 race conditions we had to fix in order to make unit testing viable.
398 </listitem>
399 <listitem>
400 Spring integration compiled against Spring 3.0.3. It may or may not still work with 2.5.6 and lower
401 </listitem>
402 </itemizedlist>
403 </para>
404 </sect1>
405 <sect1 id="migrating_1.2_1.2.1">
406 <title>Migrating from 1.2.GA to 1.2.1.GA</title>
407 <para>
408 Methods @Deprecated within 1.2.GA have been removed. This is in the Client Framework and has to do with all
409 references to Apache HTTP Client. You must now create an ClientExecutor if you want to manage your Apache
410 HTTP Client
411 sessions.
412 </para>
413 </sect1>
414 <sect1 id="Migrating_to_Resteasy_1_1_1_2">
415 <title>Migrating from 1.1 to 1.2</title>
416
417 <para>
418
419 <itemizedlist>
420 <listitem>
421 The resteasy-maven-import artifact has been renamed to resteasy-bom
422 </listitem>
423 <listitem>
424 Jettison and Fastinfoset have been broken out of the resteasy-jaxb-provider maven module. You will
425 now need to include resteasy-jettison-provider or resteasy-fastinfoset-provider if you use either
426 of these libraries.
427 </listitem>
428 <listitem>
429 The constructors for ClientRequest that have a HttpClient parameter (Apache Http Client 3.1 API) are
430 now deprecated. They will be removed in the final release of 1.2. You must create a Apache hTTP
431 Client Executor and pass it in as a parameter if you want to re-use existing Apache HttpClient
432 sessions or do any special configuration. The same is true for the ProxyFactoyr methods.
433 </listitem>
434 <!--
435 <listitem>
436 Apache HttpClient 4.0 is now the default client used for our ClientRequest and ProxyFactory APIs. Version 3.1 of this library is still support. Just allocate an executor for that instead. Or you can set the default one used by modifying the static field ClientRequest.defaultExecutorClass.
437 </listitem>
438 -->
439 <listitem>
440 Apache HttpClient 4.0 support is available if you want to use it. I've had some trouble with it so
441 it is not the default implementation yet for the client framework.
442 </listitem>
443 <listitem>
444 It is no longer required to call RegisterBuiltin.register() to initialize the set of providers. Too
445 many users forgot to do this (include myself!). You can turn this off by calling the static method
446 ResteasyProviderFactory.setRegisterBuiltinByDefault(false)
447 </listitem>
448 <listitem>
449 The Embedded Container's API has changed to use org.jboss.resteasy.spi.ResteasyDeployment. Please
450 see embedded documentation for more details.
451 </listitem>
452 </itemizedlist>
453 </para>
454 </sect1>
45541 </chapter>
55 </para>
66 </chapter>
77
8 <chapter id="Migration_to_3_5">
9 <title>Migration to RESTEasy 3.5 series</title>
10 <para>
11 RESTEasy 3.5 series is a spin-off of the old RESTEasy 3.0 series, featuring JAX-RS 2.1 implementation.
12 </para>
13 <para>
14 The reason why 3.5 comes from 3.0 instead of the 3.1 / 4.0 development streams is basically providing
15 users with a selection of RESTEasy 4 critical / strategic new features, while ensuring full backward
16 compatiblity. As a consequence, no major issues are expected when upgrading RESTEasy from 3.0.x to 3.5.x.
17 </para>
18 <para>
19 The natural upgrade path for users already on RESTEasy 3.1 series is straight to RESTEasy 4 instead.
20 </para>
21 </chapter>
22
823 <chapter id="Migration_to_3_1">
9 <title>Migration to Resteasy 3.1</title>
10
11 <para>
12 In a minor release like 3.1.0.Final, as opposed to a point release like 3.0.19.Final, the scope of
13 permissible changes is broadened. User discernible changes in Resteasy 3.1.0.Final include
24 <title>Migration to RESTEasy 3.1 series</title>
25
26 <para>
27 RESTEasy 3.1.0.Final release comes with many changes compared to previous 3.0 point releases.
28 User discernible changes in RESTEasy 3.1.0.Final include
1429 </para>
1530
1631 <itemizedlist>
2439 <para>
2540 In this chapter we focus on changes that might cause existing code to fail or behave in new ways.
2641 The audience for this discussion may be partitioned into three subsets, depending on the version
27 of Resteasy currently in use, the API currently in use, and the API to be used after an upgrade
28 to Resteasy 3.1. The following APIs are available:
42 of RESTEasy currently in use, the API currently in use, and the API to be used after an upgrade
43 to RESTEasy 3.1. The following APIs are available:
2944 </para>
3045
3146 <orderedlist>
3247 <listitem>
33 <para><emphasis role="bold">Resteasy 2</emphasis>: Resteasy 2 conforms to the JAX-RS 1 specification, and adds a
48 <para><emphasis role="bold">RESTEasy 2</emphasis>: RESTEasy 2 conforms to the JAX-RS 1 specification, and adds a
3449 variety of additional facilities, such as a client API, a caching system, an interceptor framework, etc.
35 All of these user facing classes and interfaces comprise the Resteasy 2 API.</para>
36 </listitem>
37 <listitem>
38 <para><emphasis role="bold">Resteasy 3</emphasis>: Resteasy 3 conforms to the JAX-RS 2 specification, and adds some additional
39 facilities. Many of the non-spec facilities from the Resteasy 2 API are formalized, in altered form,
50 All of these user facing classes and interfaces comprise the RESTEasy 2 API.</para>
51 </listitem>
52 <listitem>
53 <para><emphasis role="bold">RESTEasy 3</emphasis>: RESTEasy 3 conforms to the JAX-RS 2 specification, and adds some additional
54 facilities. Many of the non-spec facilities from the RESTEasy 2 API are formalized, in altered form,
4055 in JAX-RS 2, in which case the older facilites are deprecated. The non-deprecated user facing classes and interfaces in
41 Resteasy 3 comprise the Resteasy 3 API.</para>
56 RESTEasy 3 comprise the RESTEasy 3 API.</para>
4257 </listitem>
4358 </orderedlist>
4459
4560 <para>
4661 These definitions are rather informal and imprecise, since the user facing classes / interfaces in Resteasy
47 3.0.19.Final, for example, are a proper superset of the user facing classes / interfaces in Resteasy 3.0.1.Final.
62 3.0.19.Final, for example, are a proper superset of the user facing classes / interfaces in RESTEasy 3.0.1.Final.
4863 For this discussion, we identify the API with the version currently in use in a given project.
4964 </para>
5065
5166 <para>
52 Now, there are three potential target audiences of users planning to upgrade to Resteasy 3.1.0.Final:
67 Now, there are three potential target audiences of users planning to upgrade to RESTEasy 3.1.0.Final:
5368 </para>
5469
5570 <orderedlist>
5671 <listitem>
57 <para>Those currently using Resteasy API 3 with some Resteasy 3.0.x release</para>
58 </listitem>
59 <listitem>
60 <para>Those currently using Resteasy API 2 with some Resteasy 2.x or 3.0.x release and planning
61 to upgrade to Resteasy API 3</para>
62 </listitem>
63 <listitem>
64 <para>Those currently using Resteasy API 2 with some Resteasy 2.x or 3.0.x release and planning
65 to continue to use Resteasy API 2</para>
72 <para>Those currently using RESTEasy API 3 with some RESTEasy 3.0.x release</para>
73 </listitem>
74 <listitem>
75 <para>Those currently using RESTEasy API 2 with some RESTEasy 2.x or 3.0.x release and planning
76 to upgrade to RESTEasy API 3</para>
77 </listitem>
78 <listitem>
79 <para>Those currently using RESTEasy API 2 with some RESTEasy 2.x or 3.0.x release and planning
80 to continue to use RESTEasy API 2</para>
6681 </listitem>
6782 </orderedlist>
6883
6984 <para>
70 Of these, users in Group 2 have the most work to do in upgrading from Resteasy API 2 to Resteasy API 3.
85 Of these, users in Group 2 have the most work to do in upgrading from RESTEasy API 2 to RESTEasy API 3.
7186 They should consult the separate guide
72 <ulink url="http://docs.jboss.org/resteasy/docs/resteasy-upgrade-guide-en-US.pdf">Upgrading from Resteasy 2 to Resteasy 3</ulink>.
87 <ulink url="http://docs.jboss.org/resteasy/docs/resteasy-upgrade-guide-en-US.pdf">Upgrading from RESTEasy 2 to RESTEasy 3</ulink>.
7388 </para>
7489
7590 <para>
7893 are a few changes that they should be aware of.
7994 </para>
8095
81 <sect1>
82 <title>Upgrading with Resteasy 3 API</title>
83
84 <para>
85 All Resteasy changes are documented in JIRA issues. Issues that describe detectable changes in
96 <sect1>
97 <title>Upgrading with RESTEasy 3 API</title>
98
99 <para>
100 All RESTEasy changes are documented in JIRA issues. Issues that describe detectable changes in
86101 release 3.1.0.Final that might impact existing applications include
87102 </para>
88103
112127 <listitem>
113128 <ulink url="https://issues.jboss.org/browse/RESTEASY-1433">RESTEASY-1433: Compile with JDK 1.8 source/target version</ulink>
114129 <para>
115 As it says. Depending on the application, it might be necessary to recompile with a target of JDK 1.8 so that calls to Resteasy code
130 As it says. Depending on the application, it might be necessary to recompile with a target of JDK 1.8 so that calls to RESTEasy code
116131 can work.
117132 </para>
118133 </listitem>
120135 <listitem>
121136 <ulink url="https://issues.jboss.org/browse/RESTEASY-1484">RESTEASY-1484: CVE-2016-6346: Abuse of GZIPInterceptor in can lead to denial of service attack</ulink>
122137 <para>
123 Prior to release 3.1.0.Final, the default behavior of Resteasy was to use GZIP to compress and decompress messages
138 Prior to release 3.1.0.Final, the default behavior of RESTEasy was to use GZIP to compress and decompress messages
124139 whenever "gzip" appeared in the Content-Encoding header.
125140 However, decompressing messages can lead to security issues, so, as of release 3.1.0.Final, GZIP compression has to
126141 be enabled explicitly. For details, see Chapter <link linkend='gzip'>GZIP Compression/Decompression</link>.
131146 </listitem>
132147
133148 <listitem>
134 <ulink url="https://issues.jboss.org/browse/RESTEASY-1531">RESTEASY-1531: Restore removed Resteasy internal classes into a deprecated/disabled module</ulink>
135 <para>
136 This issue is related to refactoring deprecated elements of the Resteasy 2 API into a separate module, and, ideally,
137 would have no bearing at all on Resteasy 3. However, a reorganization of packages has led to moving some
149 <ulink url="https://issues.jboss.org/browse/RESTEASY-1531">RESTEASY-1531: Restore removed RESTEasy internal classes into a deprecated/disabled module</ulink>
150 <para>
151 This issue is related to refactoring deprecated elements of the RESTEasy 2 API into a separate module, and, ideally,
152 would have no bearing at all on RESTEasy 3. However, a reorganization of packages has led to moving some
138153 non-deprecated API elements in the resteasy-jaxrs module:
139154 </para>
140155
162177 </sect1>
163178
164179 <sect1>
165 <title>Upgrading with Resteasy 2 API</title>
180 <title>Upgrading with RESTEasy 2 API</title>
166181
167182 <para>
168183 Most of the deprecated classes and interfaces
169 from Resteasy 2 have been segregated in a separate module, resteasy-legacy, as of release 3.1.0.Final.
184 from RESTEasy 2 have been segregated in a separate module, resteasy-legacy, as of release 3.1.0.Final.
170185 A few remain in module resteasy-jaxrs for technical reasons. Eventually, all such classes and interfaces will be
171 removed from Resteasy. Most of the relocated elements are internal, so ensuring that resteasy-legacy is on the
186 removed from RESTEasy. Most of the relocated elements are internal, so ensuring that resteasy-legacy is on the
172187 classpath will make most changes undetectable. One way to do that, of course, is to include it in an application's
173188 WAR. In the context of WildFly, it is also possible to use a jboss-deployment-structure.xml file in the
174189 WEB-INF directory of your WAR file. For example:
00 <chapter id="Multipart">
11 <title>Multipart Providers</title>
2 <para>Resteasy has rich support for the "multipart/*" and "multipart/form-data" mime types. The multipart mime
2 <para>RESTEasy has rich support for the "multipart/*" and "multipart/form-data" mime types. The multipart mime
33 format is used to pass lists of content bodies. Multiple content bodies are embedded in one message.
44 "multipart/form-data" is often found in web application HTML Form documents and is generally used to
55 upload files. The form-data format is the same as other multipart formats, except that each inlined piece
4545 <para>MultipartInput is a simple interface that allows you to get access to each part of the multipart message.
4646 Each part is represented by an InputPart interface. Each part has a set of headers associated with it
4747 You can unmarshall the part by calling one of the getBody() methods. The Type genericType parameter can be null,
48 but the Class type parameter must be set. Resteasy will find a MessageBodyReader based on the media type
48 but the Class type parameter must be set. RESTEasy will find a MessageBodyReader based on the media type
4949 of the part as well as the type information you pass in. The following piece of code is unmarshalling
5050 parts which are XML into a JAXB annotated class called Customer.
5151 </para>
218218 }
219219 ]]></programlisting>
220220 <para>When you want to output multipart data it is as simple as creating a MultipartOutput object
221 and calling addPart() methods. Resteasy will automatically find a MessageBodyWriter
221 and calling addPart() methods. RESTEasy will automatically find a MessageBodyWriter
222222 to marshall your entity objects. Like MultipartInput, sometimes you may have marshalling
223223 which is sensitive to generic type metadata. In that case, use GenericType. Most of the time though
224224 passing in an Object and its MediaType is enough. In the example below, we are sending
277277 public OutputPart addFormData(String key, Object entity, Class type, Type genericType, MediaType mediaType)
278278
279279 public Map<String, OutputPart> getFormData()
280
281 public Map<String, List<OutputPart>> getFormDataMap()
280282 }
281283 ]]></programlisting>
282284 <para>When you want to output multipart/form-data it is as simple as creating a MultipartFormDataOutput object
283 and calling addFormData() methods. Resteasy will automatically find a MessageBodyWriter
285 and calling addFormData() methods. RESTEasy will automatically find a MessageBodyWriter
284286 to marshall your entity objects. Like MultipartInput, sometimes you may have marshalling
285287 which is sensitive to generic type metadata. In that case, use GenericType. Most of the time though
286288 passing in an Object and its MediaType is enough. In the example below, we are sending
301303 }
302304 }
303305 </programlisting>
306 <para>When using form-data format the named content can be a list of OutputPart objects
307 as long as each object in the named list contains a uniform object and media type.
308 In the example below, we are sending back a "multipart/form-data" format which consists
309 of two named list of objects, bill and monica.
310 </para>
311 <programlisting>
312 @Path("/form")
313 public class MyService
314 {
315 @GET
316 @Produces("multipart/form-data")
317 public MultipartFormDataOutput get()
318 {
319 MultipartFormDataOutput output = new MultipartFormDataOutput();
320 output.addPart("smith", new Customer("Joe Smith"), MediaType.APPLICATION_XML_TYPE);
321 output.addPart("monica", new Employee("monica"), MediaType.APPLICATION_JSON_TYPE);
322 output.addPart("smith", new Customer("Deb Smith"), MediaType.APPLICATION_XML_TYPE);
323 output.addPart("smith", new Customer("Buba Smith"), MediaType.APPLICATION_XML_TYPE);
324 return output;
325 }
326 }
327 </programlisting>
304328 </sect1>
305329 <sect1 id="multipart_map_output">
306330 <title>Multipart FormData Output with java.util.Map</title>
345369 <para>When you want to output multipart/related it is as simple as creating a MultipartRelatedOutput object
346370 and calling addPart() methods. The first added part will be used as the root part of the multipart/related
347371 message.
348 Resteasy will automatically find a MessageBodyWriter to marshall your entity objects. Like MultipartInput,
372 RESTEasy will automatically find a MessageBodyWriter to marshall your entity objects. Like MultipartInput,
349373 sometimes you may have marshalling which is sensitive to generic type metadata. In that case, use
350374 GenericType. Most of the time though passing in an Object and its MediaType is enough. In the example
351375 below, we are sending back a "multipart/related" format back to the calling client. We are sending a
524548 <title>Note about multipart parsing and working with other frameworks</title>
525549 <para>There are a lot of frameworks doing multipart parsing automatically with the help of filters and interceptors.
526550 Like org.jboss.seam.web.MultipartFilter in Seam or org.springframework.web.multipart.MultipartResolver in Spring.
527 However the incoming multipart request stream can be parsed only once. Resteasy users working with multipart should
528 make sure that nothing parses the stream before Resteasy gets it.</para>
551 However the incoming multipart request stream can be parsed only once. RESTEasy users working with multipart should
552 make sure that nothing parses the stream before RESTEasy gets it.</para>
529553 </sect1>
530554 <sect1 id="multipart_overwrite_default_content_type">
531555 <title>Overwriting the default fallback content type for multipart messages</title>
22
33 <para>
44
5 JAX-RS 2.0, JSR-339, is a new JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.
6 Resteasy is an portable implementation of this specification which can run in any Servlet container. Tighter
5 JAX-RS 2.0 (JSR-339) and JAX-RS 2.1 (JSR-370), are JCP specifications that provide a Java API for RESTful Web Services over the HTTP protocol.
6 RESTEasy is a portable implementation of these specifications which can run in any Servlet container. Tighter
77 integration with WildFly application server is also available to make the user experience nicer in that environment.
8 Resteasy also comes with additional features on top of plain JAX-RS functionalities.
8 RESTEasy also comes with additional features on top of plain JAX-RS functionalities.
99 </para>
1010 </chapter>
00 <chapter id="RESTEasy_Client_Framework">
1 <title>Resteasy Client API</title>
2
3 <sect1>
1 <title>RESTEasy Client API</title>
2
3 <section>
44 <title>JAX-RS 2.0 Client API</title>
55 <para>JAX-RS 2.0 introduces a new client API so that you can make http requests to your remote RESTful web services.
66 It is a 'fluent' request building API with really 3 main classes: Client, WebTarget, and Response. The Client
2323 ResteasyWebTarget target = client.target("http://foo.com/resource");
2424 </programlisting>
2525 <para>
26 Resteasy will automatically load a set of default providers. (Basically all classes listed in all
26 RESTEasy will automatically load a set of default providers. (Basically all classes listed in all
2727 META-INF/services/javax.ws.rs.ext.Providers files). Additionally, you can manually register other providers,
2828 filters, and interceptors through the Configuration object provided by the method call Client.configuration().
2929 Configuration also lets you set various configuration properties that may be needed.
3535 </para>
3636
3737 <para>
38 One Resteasy extension to the client API is the ability to specify that requests should be sent in "chunked" transfer mode.
38 One RESTEasy extension to the client API is the ability to specify that requests should be sent in "chunked" transfer mode.
3939 There are two ways of doing that. One is to configure an <classname>org.jboss.resteasy.client.jaxrs.ResteasyWebTarget</classname>
4040 so that all requests to that target are sent in chunked mode:
4141 </para>
6060
6161 <para>
6262 Note that <classname>org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder</classname>,
63 unlike <classname>javax.ws.rs.client.Invocation.Builder</classname>, is a Resteasy class.
63 unlike <classname>javax.ws.rs.client.Invocation.Builder</classname>, is a RESTEasy class.
6464 </para>
6565
6666 <para>
7373 support chunked mode. See Section <link linkend='transport_layer'>Apache HTTP Client 4.x and other backends</link>
7474 for more information.
7575 </para>
76 </sect1>
76 </section>
7777 <para>
7878
7979 </para>
8080
81 <sect1>
82 <title>Resteasy Proxy Framework</title>
81 <section>
82 <title>RESTEasy Proxy Framework</title>
8383 <para>
8484
85 The Resteasy Proxy Framework is the mirror opposite of the JAX-RS server-side specification. Instead of using
85 The RESTEasy Proxy Framework is the mirror opposite of the JAX-RS server-side specification. Instead of using
8686 JAX-RS annotations to map an incoming request to your RESTFul Web Service method, the client framework builds an
8787 HTTP request that it uses to invoke on a remote RESTful Web Service. This remote service does not have to be a
8888 JAX-RS service and can be any web resource that accepts HTTP requests.
8989 </para>
9090 <para>
9191
92 Resteasy has a client proxy framework that allows you to use JAX-RS annotations to invoke on a remote HTTP
92 RESTEasy has a client proxy framework that allows you to use JAX-RS annotations to invoke on a remote HTTP
9393 resource.
9494 The way it works is that you write a Java interface and use JAX-RS annotations on methods and the interface. For
9595 example:
127127 </para>
128128 <para>
129129
130 Resteasy has a simple API based on Apache HttpClient. You generate a proxy then you can invoke methods on the
130 RESTEasy has a simple API based on Apache HttpClient. You generate a proxy then you can invoke methods on the
131131 proxy. The invoked method gets translated to an HTTP request based on how you annotated the method and posted to
132132 the server. Here's how you would set this up:
133133 </para>
141141 SimpleClient simple = rtarget.proxy(SimpleClient.class);
142142 client.putBasic("hello world");
143143 </programlisting>
144 Alternatively you can use the Resteasy client extension interfaces directly:
144 Alternatively you can use the RESTEasy client extension interfaces directly:
145145 <programlisting>
146146 ResteasyClient client = new ResteasyClientBuilder().build();
147147 ResteasyWebTarget target = client.target("http://example.com/base/uri");
164164 The framework also supports the JAX-RS locator pattern, but on the client side. So, if you have a method annotated only with @Path, that proxy method
165165 will return a new proxy of the interface returned by that method.
166166 </para>
167 <sect1 id="Custom_client-side_responses">
167 <section id="Custom_client-side_responses">
168168 <title>Abstract Responses</title>
169169
170170 <para>
215215 Response getAllBooks();
216216 }</programlisting>
217217 </para>
218 </sect1>
219 <sect1 id="Sharing_interfaces">
218 </section>
219
220 <section id="Response_proxies">
221 <title>Response proxies</title>
222 <para>
223 A further extension implemented by the RESTEasy client proxy framework is the "response proxy facility",
224 where a client proxy method returns an interface that represents the information
225 contained in a <classname>javax.ws.rs.core.Response</classname>. Such an interface must be annotated with
226 <classname>@ResponseObject</classname> from package <classname>org.jboss.resteasy.annotations</classname>,
227 and its methods may be further annotated with <classname>@Body</classname>, <classname>@LinkHeaderParam</classname>,
228 and <classname>@Status</classname> from the same package, as well as <classname>javax.ws.rs.HeaderParam</classname>.
229 Consider the following example.
230 </para>
231
232 <programlisting>
233 @ResponseObject
234 public interface TestResponseObject {
235
236 @Status
237 int status();
238
239 @Body
240 String body();
241
242 @HeaderParam("Content-Type")
243 String contentType();
244
245 ClientResponse response();
246 }
247
248 @Path("test")
249 public interface TestClient {
250
251 @GET
252 TestResponseObject get();
253 }
254
255 @Path("test")
256 public static class TestResource {
257
258 @GET
259 @Produces("text/plain")
260 public String get() {
261 return "ABC";
262 }
263 }
264 </programlisting>
265
266 <para>
267 Here, <classname>TestClient</classname> will define the client side proxy for <classname>TestResource</classname>.
268 Note that <methodname>TestResource.get()</methodname> returns a <classname>String</classname> but the proxy
269 based on <classname>TestClient</classname> will return a <classname>TestResponseObject</classname> on a
270 call to <methodname>get()</methodname>:
271 </para>
272
273 <programlisting>
274 Client client = ClientBuilder.newClient();
275 TestClient ClientInterface = ProxyBuilder.builder(TestClient.class, client.target("http://localhost:8081")).build();
276 TestResponseObject tro = ClientInterface.get();
277 </programlisting>
278
279 <para>
280 The methods of <classname>TestResponseObject</classname> provide access to various pieces of information about the
281 response received from <methodname>TestResponse.get()</methodname>. This is where the annotations on those methods
282 come into play. <methodname>status()</methodname> is annotated with <classname>@Status</classname>, and a call to
283 <methodname>status()</methodname> returns the HTTP status. Similarly, <methodname>body()</methodname> returns the
284 returned entity, and <methodname>contentType()</methodname> returns the value of the response header Content-Type:
285 </para>
286
287 <programlisting>
288 System.out.println("status: " + tro.status());
289 System.out.println("entity: " + tro.body());
290 System.out.println("Content-Type: " + tro.contentType());
291 </programlisting>
292
293 <para>
294 will yield
295 </para>
296
297 <programlisting>
298 status: 200
299 entity: ABC
300 Content-Type: text/plain;charset=UTF-8
301 </programlisting>
302
303 <para>
304 Note that there is one other method in <classname>TestResponseObject</classname>, <methodname>response()</methodname>,
305 that has no annotation. When RESTEasy sees a method in an interface annotated with <classname>@ResponseObject</classname>
306 that returns a <classname>javax.ws.rs.core.Response</classname> (or a subclass thereof), it will return a
307 <classname>org.jboss.resteasy.client.jaxrs.internal.ClientResponse</classname>. For example,
308 </para>
309
310 <programlisting>
311 ClientResponse clientResponse = tro.response();
312 System.out.println("Content-Length: " + clientResponse.getLength());
313 </programlisting>
314
315 <para>
316 Perhaps the most interesting piece of the response proxy facility is the treatment of methods
317 annotated with <classname>@LinkHeaderParam</classname>. Its simplest use is to assist in
318 accessing a <classname>javax.ws.rs.core.Link</classname> returned by a resource method. For
319 example, let's add
320 </para>
321
322 <programlisting>
323 @GET
324 @Path("/link-header")
325 public Response getWithHeader(@Context UriInfo uri) {
326 URI subUri = uri.getAbsolutePathBuilder().path("next-link").build();
327 Link link = new LinkBuilderImpl().uri(subUri).rel("nextLink").build();
328 return Response.noContent().header("Link", link.toString()).build();
329 }
330 </programlisting>
331
332 <para>
333 to <classname>TestResource</classname>, add
334 </para>
335
336 <programlisting>
337 @GET
338 @Path("link-header")
339 ResponseObjectInterface performGetBasedOnHeader();
340 </programlisting>
341
342 <para>
343 to <classname>ClientInterface</classname>, and add
344 </para>
345
346 <programlisting>
347 @LinkHeaderParam(rel = "nextLink")
348 URI nextLink();
349 </programlisting>
350
351 <para>
352 to <classname>ResponseObjectInterface</classname>. Then calling
353 </para>
354
355 <programlisting>
356 ResponseObjectInterface obj = ClientInterface.performGetBasedOnHeader();
357 System.out.println("nextLink(): " + obj.nextLink());
358 </programlisting>
359
360 <para>
361 will access the <classname>LinkHeader</classname> returned by <methodname>TestResource.getWithHeader()</methodname>:
362 </para>
363
364 <programlisting>
365 nextlink: http://localhost:8081/test/link-header/next-link
366 </programlisting>
367
368 <para>
369 Last but not least, let's add
370 </para>
371
372 <programlisting>
373 @GET
374 @Produces("text/plain")
375 @Path("/link-header/next-link")
376 public String getHeaderForward() {
377 return "forwarded";
378 }
379 </programlisting>
380
381 <para>
382 to <classname>TestResource</classname> and
383 </para>
384
385 <programlisting>
386 @GET
387 @LinkHeaderParam(rel = "nextLink")
388 String followNextLink();
389 </programlisting>
390
391 <para>
392 to <classname>ResponseObjectInterface</classname>. Note that, unlike
393 <methodname>ResponseObjectInterface.nextLink()</methodname>, <methodname>followNextLink()</methodname>
394 is annotated with <classname>@GET</classname>; that is, it qualifies as (the client proxy to) a resource
395 method. When executing <methodname>followNextLink()</methodname>, RESTEasy will retrieve the value
396 of the <classname>Link</classname> returned by <methodname>TestResource.getWithHeader()</methodname>
397 and then will make a GET invocation on the <classname>URL</classname> in that <classname>Link</classname>.
398 Calling
399 </para>
400
401 <programlisting>
402 System.out.println("followNextLink(): " + obj.followNextLink());
403 </programlisting>
404
405 <para>
406 causes RESTEasy to retrieve the <classname>URL</classname> http://localhost:8081/test/link-header/next-link
407 from the call to <methodname>TestResource.getWithHeader()</methodname> and then perform a GET on it,
408 invoking <methodname>TestResource.getHeaderForward()</methodname>:
409 </para>
410
411 <programlisting>
412 followNextLink(): forwarded
413 </programlisting>
414
415 <para><emphasis role="bold">Note.</emphasis> This facility for extracting a <classname>URL</classname>
416 and following it is a step toward supporting the Representation State Transfer principle of HATEOAS.
417 For more information, see
418 <ulink url="http://shop.oreilly.com/product/0636920028925.do">RESTful Java with JAX-RS 2.0, 2nd Edition</ulink>
419 by Bill Burke.
420 </para>
421 </section>
422
423 <section id="ClientURI">
424 <title>Giving client proxy an ad hoc URI</title>
425
426 <para>
427 Client proxies figure out appropriate URIs for targeting resource methods by looking at <classname>@Path</classname>
428 annotations in the client side interface, but it is also possible to pass URIs explicitly to the proxy through the
429 use of the <classname>org.jboss.resteasy.annotations.ClientURI</classname> annotation. For example, let
430 <classname>TestResource</classname> be a client side interface and <classname>TestResourceImpl</classname> a server resource:
431 </para>
432
433 <programlisting>
434 @Path("")
435 public interface TestResource {
436
437 @GET
438 @Path("dispatch")
439 public String dispatch(@ClientURI String uri);
440 }
441
442 @Path("")
443 public static class TestResourceImpl {
444
445 @GET
446 @Path("a")
447 public String a() {
448 return "a";
449 }
450
451 @GET
452 @Path("b")
453 public String b() {
454 return "b";
455 }
456 }
457 </programlisting>
458
459 <para>
460 Calling <methodname>TestResource.dispatch()</methodname> allows specifying a specific URI for accessing a resource method. In the
461 following, let BASE_URL be the address of the <classname>TestResourceImpl</classname> resource.
462 </para>
463
464 <programlisting>
465 private static String BASE_URL = "http://localhost:8081/";
466 ...
467 public void test() throws Exception
468 {
469 ResteasyClient client = new ResteasyClientBuilder().build();
470 TestResource proxy = client.target(BASE_URL).proxy(TestResource.class);
471 String name = proxy.dispatch(BASE_URL + "a");
472 System.out.println("name: " + name);
473 name = proxy.dispatch(BASE_URL + "b");
474 System.out.println("name: " + name);
475 client.close();
476 }
477 </programlisting>
478
479 <para>
480 Then passing "http://localhost:8081/a" and "http://localhost/b" to <methodname>dispatch()</methodname> invokes
481 <methodname>TestResourceImp.a()</methodname> and <methodname>TestResourceImpl.b()</methodname> respectively, yielding
482 the output
483 </para>
484
485 <programlisting>
486 name: a
487 name: b
488 </programlisting>
489 </section>
490
491 <section id="Sharing_interfaces">
220492 <title>Sharing an interface between client and server</title>
221493 <para>
222494 It is generally possible to share an interface between the client and server. In this scenario, you just
224496 and then reuse that same interface to create client proxies to invoke on the client-side.
225497 </para>
226498
227 </sect1>
228 </sect1>
499 </section>
500 </section>
229501
230502
231503
232504
233505
234 <sect1 id="transport_layer">
506 <section id="transport_layer">
235507 <title>Apache HTTP Client 4.x and other backends</title>
236
237 <para>
238 Network communication between the client and server is handled in Resteasy,
239 by default, by HttpClient (4.x) from the Apache HttpComponents project. In general,
240 the interface between the Resteasy Client Framework and the network is
241 found in an implementation of
242 <classname>org.jboss.resteasy.client.jaxrs.ClientHttpEngine</classname>.
243 <classname>org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine</classname>,
244 which uses HttpClient (4.3+), is the default implementation. Resteasy
245 also ships with the older <classname>ApacheHttpClient4Engine</classname>, which uses
246 HttpClient 4.2, and <classname>URLConnectionEngine</classname>,
247 which uses <classname>java.net.HttpURLConnection</classname>. It is also possible to pass
248 an alternative implementation of <classname>ClientHttpEngine</classname> to a
249 <classname>ResteasyClient</classname>:
250 </para>
251
252 <programlisting>
253 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
508
509 <para>
510 Network communication between the client and server is handled by default in RESTEasy.
511 The interface between the RESTEasy Client Framework and the network
512 is defined by RESTEasy's <code class="classname">ClientHttpEngine</code> interface.
513 RESTEasy ships with multiple implementations of this interface.
514 </para>
515 <para>
516 The default
517 implementation is <code class="classname">ApacheHttpClient43Engine</code>, which uses
518 version 4.3 of the <code class="classname">HttpClient</code> from the Apache
519 <code class="classname">HttpComponents</code> project.
520 <code class="classname">ApacheHttpClient4Engine</code> is an implementation that
521 uses the pre-Apache 4.3 version, to provide backward compatibility.
522 RESTEasy automatically selects one of these two
523 <code class="classname">ClientHttpEngine</code> implementations based upon the
524 detection of the Apache version.
525 </para>
526 <para>
527 <code class="classname">ApacheHttpAsyncClient4Engine</code>, instead, is built on top
528 of <emphasis>HttpAsyncClient</emphasis> (still from the Apache
529 <emphasis>HttpComponents</emphasis> project) with internally dispatches requests
530 using a non-blocking IO model.
531 </para>
532 <para>
533 Finally,
534 <code class="classname">InMemoryClientEngine</code> is
535 an implementation that dispatches requests to a server in the same JVM and
536 <code class="classname">URLConnectionEngine</code> is an implementation that uses
537 <code class="classname">java.net.HttpURLConnection</code>.
538 </para>
539
540 <table frame="topbot">
541 <tgroup cols="2" rowsep="1" colsep="1">
542 <thead>
543 <row>
544 <entry>RESTEasy ClientHttpEngine implementations</entry>
545 <entry></entry>
546 </row>
547 </thead>
548 <tbody>
549 <row>
550 <entry>ApacheHttpClient43Engine</entry>
551 <entry>Uses HttpComponents HttpClient 4.3 api</entry>
552 </row>
553 <row>
554 <entry>ApacheHttpClient4Engine</entry>
555 <entry>Uses HttpComponents HttpClient pre-4.3 api</entry>
556 </row>
557 <row>
558 <entry>ApacheHttpAsyncClient4Engine</entry>
559 <entry>Uses HttpComponents HttpAsyncClient</entry>
560 </row>
561 <row>
562 <entry>InMemoryClientEngine</entry>
563 <entry>Dispatches requests to a server in the same JVM</entry>
564 </row>
565 <row>
566 <entry>URLConnectionEngine</entry>
567 <entry>Uses java.net.HttpURLConnection</entry>
568 </row>
569 </tbody>
570 </tgroup>
571 </table>
572
573 <para>
574 The RESTEasy Client Framework can also be customized. The user can provide
575 their own implementations of
576 <code class="classname">ClientHttpEngine</code> to the
577 <code class="classname">ResteasyClient</code>.
578 </para>
579
580 <programlisting>
581 ClientHttpEngine myEngine = new ClientHttpEngine() {
582 protected SSLContext sslContext;
583 protected HostnameVerifier hostnameVerifier;
584
585
586 @Override
587 public ClientResponse invoke(ClientInvocation request) {
588 // implement your processing code and return a
589 // org.jboss.resteasy.client.jaxrs.internal.ClientResponse
590 // object.
591 }
592
593 @Override
594 public SSLContext getSslContext() {
595 return sslContext;
596 }
597
598 @Override
599 public HostnameVerifier getHostnameVerifier() {
600 return hostnameVerifier;
601 }
602
603 @Override
604 public void close() {
605 // do nothing
606 }
607 };
608
609 ResteasyClient client = new RESTEasyClientBuilder().httpEngine(myEngine).build();
610 </programlisting>
611
612 <para>
613 RESTEasy and <classname>HttpClient</classname> make reasonable default decisions so
614 that it is possible to use the client framework without ever referencing
615 <classname>HttpClient</classname>. For some applications it may be necessary to drill
616 down into the <classname>HttpClient</classname> details.
617 <classname>ApacheHttpClient43Engine</classname> and
618 <classname>ApacheHttpClient4Engine</classname> can
619 be supplied with an instance of
620 <classname>org.apache.http.client.HttpClient</classname> and an instance of
621 <classname>org.apache.http.protocol.HttpContext</classname>, which can carry
622 additional configuration details into the <classname>HttpClient</classname> layer.
623
624 </para>
625 <classname>HttpContextProvider</classname>
626 is a RESTEasy provided interface through which a custom
627 <classname>HttpContext</classname> is supplied to
628 <classname>ApacheHttpClient43Engine</classname> and
629 <classname>ApacheHttpClient4Engine</classname>.
630 <para>
631
632 <programlisting>
633 package org.jboss.resteasy.client.jaxrs.engines;
634
635 import org.apache.http.protocol.HttpContext;
636
637 public interface HttpContextProvider {
638 HttpContext getContext();
639 }
640 </programlisting>
641
642 </para>
643
644 <para>
645 Here is an example of providing a custom HttpContext
646 </para>
647
648 <programlisting>
649 DefaultHttpClient httpClient = new DefaultHttpClient();
650 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient,
651 new HttpContextProvider() {
652 @Override
653 public HttpContext getContext() {
654 // Configure HttpClient to authenticate preemptively
655 // by prepopulating the authentication data cache.
656 // 1. Create AuthCache instance
657 AuthCache authCache = new BasicAuthCache();
658 // 2. Generate BASIC scheme object and add it to the local auth cache
659 BasicScheme basicAuth = new BasicScheme();
660 authCache.put(getHttpHost(url), basicAuth);
661 // 3. Add AuthCache to the execution context
662 BasicHttpContext localContext = new BasicHttpContext();
663 localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
664 return localContext;
665 }
666 });
667 </programlisting>
668
669 <section id="http_redirect">
670 <title>HTTP redirect</title>
671 <para>
672 The <classname>ClientHttpEngine</classname> implementations based on Apache
673 <classname>HttpClient</classname> support HTTP redirection.
674 The feaure is disabled by default and has to be enabled by users explicitly:
675 <programlisting>
676 ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine();
677 engine.setFollowRedirects(true);
678 Client client = new ResteasyClientBuilder().httpEngine(engine).build();
254679 </programlisting>
255
256 <para>
257 Resteasy and HttpClient make reasonable default decisions so that it is possible to use the client
258 framework without ever referencing HttpClient, but for some applications it may be necessary to drill
259 down into the HttpClient details. <classname>ApacheHttpClient4Engine</classname> can
260 be supplied with an instance of <classname>org.apache.http.client.HttpClient</classname> and
261 an instance of <classname>org.apache.http.protocol.HttpContext</classname>, which can carry
262 additional configuration details into the HttpClient layer. For example, authentication
263 may be configured as follows:
264 </para>
265
266 <programlisting>
267 // Configure HttpClient to authenticate preemptively
268 // by prepopulating the authentication data cache.
269
270 // 1. Create AuthCache instance
271 AuthCache authCache = new BasicAuthCache();
272
273 // 2. Generate BASIC scheme object and add it to the local auth cache
274 AuthScheme basicAuth = new BasicScheme();
275 authCache.put(new HttpHost("sippycups.bluemonkeydiamond.com"), basicAuth);
276
277 // 3. Add AuthCache to the execution context
278 BasicHttpContext localContext = new BasicHttpContext();
279 localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
280
281 // 4. Create client executor and proxy
282 DefaultHttpClient httpClient = new DefaultHttpClient();
283 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, localContext);
284 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
285 </programlisting>
286
287 <para>
288 One default decision made by HttpClient and adopted by Resteasy is the use of
289 <classname>org.apache.http.impl.conn.SingleClientConnManager</classname>,
290 which manages a single socket at any given time and which
680 </para>
681 </section>
682
683 <section id="apache_pre_4_3">
684 <title>Apache HTTP Client pre-4.3 APIs</title>
685 <para>
686 The Apache pre-4.3 <classname>HttpClient</classname> implementation uses
687 <classname>org.apache.http.impl.conn.SingleClientConnManager</classname>
688 to manage a single socket and allows
689 <classname>org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager</classname>
690 to replace <classname>SingleClientConnManager</classname> for multithreaded applications.
691 <classname>SingleClientConnManager</classname> manages a single socket at any given time and
291692 supports the use case in which one or more invocations are made serially
292 from a single thread. For multithreaded applications,
293 <classname>SingleClientConnManager</classname> may be replaced by
294 <classname>org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager</classname>:
295 </para>
296
693 from a single thread.
694 </para>
695
696 <para>
697 Here is an example of replacing the <classname>SingleClientConnManager</classname>
698 with <classname>ThreadSafeClientConnManager</classname> in
699 <classname>ApacheHttpClient4Engine</classname>.
700 </para>
297701 <programlisting>
298702 ClientConnectionManager cm = new ThreadSafeClientConnManager();
299703 HttpClient httpClient = new DefaultHttpClient(cm);
320724 released from its current use, which can occur in one of two ways. If
321725 an execution of a request or a call on
322726 a proxy returns a class other than <classname>Response</classname>,
323 then Resteasy will take care of releasing the connection. For example,
727 then RESTEasy will take care of releasing the connection. For example,
324728 in the fragments
325729 </para>
326730
340744 </programlisting>
341745
342746 <para>
343 Resteasy will release the connection under the covers. The only counterexample is the case
747 RESTEasy will release the connection under the covers. The only counterexample is the case
344748 in which the response is an instance of <classname>InputStream</classname>, which must
345749 be closed explicitly.
346750 </para>
390794 Finally, if your javax.ws.rs.client.Client class has created the engine automatically for you, you should
391795 call Client.close() and this will clean up any socket connections.
392796 </para>
393
394 </sect1>
797 </section>
798
799 <section id="apache_4_3">
800 <title>Apache HTTP Client 4.3 APIs</title>
801 <para>
802 The Apache 4.3 <classname>HttpClient</classname> implementation uses
803 <classname>org.apache.http.impl.conn.BasicHttpClientConnectionManager</classname>
804 to manage a single socket and
805 <classname>org.apache.http.impl.conn.PoolingHttpClientConnectionManager</classname>
806 to service connection requests from multiple execution threads.
807 RESTEasy's <classname>ClientHttpclientBuilder43</classname> and
808 <classname>ApacheHttpClient43Engine</classname>
809 uses them as well.
810 </para>
811 </section>
812
813 <section id="apache_asynch">
814 <title>Asynchronous HTTP Request Processing</title>
815 <para>
816 RESTEasy's default async engine implementation class is
817 <emphasis>ApacheHttpAsyncClient4Engine</emphasis>. It can be set as the active
818 engine by calling method <emphasis>useAsyncHttpEngine</emphasis> in
819 <emphasis>ResteasyClientBuilder</emphasis>.
820 </para>
821 <programlisting>
822 Client asyncClient = new ResteasyClientBuilder().useAsyncHttpEngine()
823 .build();
824 Future&lt;Response&gt; future = asyncClient
825 .target("http://locahost:8080/test").request()
826 .async().get();
827 Response res = future.get();
828 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
829 String entity = res.readEntity(String.class);
830 </programlisting>
831 <sect2>
832 <title>InvocationCallbacks</title>
833 <para>
834 InvocationCallbacks are called from within the io-threads and thus must not block or else
835 the application may slow down to a halt. Reading the response is safe because the response
836 is buffered in memory, as are other async and in-memory client-invocations that submit-calls
837 returning a future not containing Response, InputStream or Reader.
838 </para>
839 <programlisting>
840 final CountDownLatch latch = new CountDownLatch(1);
841 Future&lt;String&gt; future = nioClient.target(generateURL("/test")).request()
842 .async().get(new InvocationCallback&lt;String&gt;()
843 {
844 @Override
845 public void completed(String s)
846 {
847 Assert.assertEquals("get", s);
848 latch.countDown();
849 throw new RuntimeException("for the test of it");
850 }
851
852 @Override
853 public void failed(Throwable error)
854 {
855 }
856 });
857 String entity = future.get();
858 Assert.assertEquals("get", entity);
859 </programlisting>
860 <para>
861 InvocationCallbacks may be called seemingly "after" the future-object returns. Thus, responses
862 should be handled solely in the InvocationCallback.
863 </para>
864 <para>
865 InvocationCallbacks will see the same result as the future-object and vice versa. Thus, if the
866 invocationcallback throws an exception, the future-object will not see it. This is the
867 reason to handle responses only in the InvocationCallback.
868 </para>
869
870 </sect2>
871
872 <sect2>
873 <title>Async Engine Usage Considerations</title>
874 <para>
875 Asynchronous IO means non-blocking IO utilizing few threads, typically at most as many
876 threads as number of cores. As such, performance may profit from fewer thread switches
877 and less memory usage due to fewer thread-stacks. But doing synchronous, blocking IO (the
878 invoke-methods not returning a future) may suffer, because the data has to be transferred
879 piecewise to/from the io-threads.
880 </para>
881 <para>
882 Request-Entities are fully buffered in memory, thus <emphasis>HttpAsyncClient</emphasis>
883 is unsuitable for very large uploads. Response-Entities are buffered in memory, except
884 if requesting a Response, InputStream or Reader as Result. Thus for large downloads or
885 COMET, one of these three return types must be requested, but there may be a performance
886 penalty because the response-body is transferred piecewise from the io-threads. When
887 using InvocationCallbacks, the response is always fully buffered in memory.
888 </para>
889 </sect2>
890 </section>
891
892 </section>
395893
396894
397895 </chapter>
22
33 <para>
44
5 To integrate with EJB you must first modify your EJB's published interfaces. Resteasy currently only has simple portable integration with EJBs so you must also manually configure your Resteasy WAR.
5 To integrate with EJB you must first modify your EJB's published interfaces. RESTEasy currently only has simple portable integration with EJBs so you must also manually configure your RESTEasy WAR.
66 </para>
77 <para>
88
1010 </para>
1111 <para>
1212
13 Resteasy currently only has simple integration with EJBs. To make an EJB a JAX-RS resource, you must annotate an SLSB's @Remote or @Local interface with JAX-RS annotations:
13 RESTEasy currently only has simple integration with EJBs. To make an EJB a JAX-RS resource, you must annotate an SLSB's @Remote or @Local interface with JAX-RS annotations:
1414 </para>
1515 <para>
1616
7272 </para>
7373 <para>
7474
75 If you're using Resteasy with an EAR and EJB, a good structure to have is:
75 If you're using RESTEasy with an EAR and EJB, a good structure to have is:
7676 </para>
7777 <para>
7878
8585 ----WEB-INF/lib (nothing)
8686 |------lib/
8787 |
88 ----All Resteasy jar files
88 ----All RESTEasy jar files
8989 </programlisting>
9090 </para>
9191 <para>
9292
93 From the distribution, remove all libraries from WEB-INF/lib and place them in a common EAR lib. OR. Just place the Resteasy jar dependencies in your application server's system classpath. (i.e. In JBoss put them in server/default/lib)
93 From the distribution, remove all libraries from WEB-INF/lib and place them in a common EAR lib. OR. Just place the RESTEasy jar dependencies in your application server's system classpath. (i.e. In JBoss put them in server/default/lib)
9494 </para>
9595 <para>
9696
00 <chapter id="RESTEasy_Embedded_Container">
11 <title>Embedded Containers</title>
22
3 <para>Resteasy has a few different plugins for different embedabble HTTP and/or Servlet containers if use Resteasy in
3 <para>RESTEasy has a few different plugins for different embedabble HTTP and/or Servlet containers if use RESTEasy in
44 a test environment, or within an environment where you do not want a Servlet engine dependency.</para>
55 <section>
66 <title>Undertow</title>
113113 <title>Sun JDK HTTP Server</title>
114114 <para>
115115 The Sun JDK comes with a simple HTTP server implementation (com.sun.net.httpserver.HttpServer) which you
116 can run Resteasy on top of.
116 can run RESTEasy on top of.
117117 </para>
118118 <programlisting> <![CDATA[
119119 HttpServer httpServer = HttpServer.create(new InetSocketAddress(port), 10);
137137 <dependency>
138138 <groupId>org.jboss.resteasy</groupId>
139139 <artifactId>resteasy-jdk-http</artifactId>
140 <version>3.1.4.Final</version>
140 <version>3.5.0.Final</version>
141141 </dependency>
142142 ]]></programlisting>
143143
156156 <dependency>
157157 <groupId>org.jboss.resteasy</groupId>
158158 <artifactId>tjws</artifactId>
159 <version>3.1.4.Final</version>
159 <version>3.5.0.Final</version>
160160 </dependency>
161161
162162 <dependency>
226226 <section>
227227 <title>Netty</title>
228228 <para>
229 Resteasy has integration with the popular Netty project as well..
229 RESTEasy has integration with the popular Netty project as well..
230230 </para>
231231 <programlisting> <![CDATA[
232232 public static void start(ResteasyDeployment deployment) throws Exception
245245 <dependency>
246246 <groupId>org.jboss.resteasy</groupId>
247247 <artifactId>resteasy-netty</artifactId>
248 <version>3.1.4.Final</version>
248 <version>3.5.0.Final</version>
249249 </dependency>
250250 ]]></programlisting>
251251
253253 <section>
254254 <title>Vert.x</title>
255255 <para>
256 Resteasy has integration with the popular Vert.x project as well..
256 RESTEasy has integration with the popular Vert.x project as well..
257257 </para>
258258 <programlisting> <![CDATA[
259259 public static void start(VertxResteasyDeployment deployment) throws Exception
272272 <dependency>
273273 <groupId>org.jboss.resteasy</groupId>
274274 <artifactId>resteasy-vertx</artifactId>
275 <version>3.1.4.Final</version>
275 <version>3.5.0.Final</version>
276276 </dependency>
277277 ]]></programlisting>
278278
281281 <para>When a resource is called, it is done with the Vert.x Event Loop thread, keep in mind to
282282 not block this thread and respect the Vert.x programming model, see the related Vert.x <ulink url="http://vertx.io/docs/vertx-core/java/#_don_t_block_me">manual page</ulink>.</para>
283283
284 <para>Vert.x extends the Resteasy registry to provide a new binding scope that creates resources per Event Loop:</para>
284 <para>Vert.x extends the RESTEasy registry to provide a new binding scope that creates resources per Event Loop:</para>
285285 <programlisting> <![CDATA[
286286 VertxResteasyDeployment deployment = new VertxResteasyDeployment();
287287 // Create an instance of resource per Event Loop
291291 <para>The per instance binding scope caches the same resource instance for each event loop providing the same
292292 concurrency model than a verticle deployed multiple times.</para>
293293
294 <para>Vert.x can also embed a Resteasy deployment, making easy to use Jax-RS annotated controller in Vert.x applications: </para>
294 <para>Vert.x can also embed a RESTEasy deployment, making easy to use Jax-RS annotated controller in Vert.x applications: </para>
295295 <programlisting> <![CDATA[
296296 Vertx vertx = Vertx.vertx();
297297 HttpServer server = vertx.createHttpServer();
5656 <sect2 id="SpringMVC">
5757 <title>Spring MVC Integration</title>
5858 <para>
59 RESTEasy can also integrate with the Spring DispatcherServlet. The advantages of using this are that you have a simpler web.xml file, you can dispatch to either Spring controllers or Resteasy from under the same base URL, and finally, the most important, you can use Spring ModelAndView objects as return arguments from @GET resource methods. Setup requires you using the Spring DispatcherServlet in your web.xml file, as well as importing the springmvc-resteasy.xml file into your base Spring beans xml file. Here's an example web.xml file:
59 RESTEasy can also integrate with the Spring DispatcherServlet. The advantages of using this are that you have a simpler web.xml file, you can dispatch to either Spring controllers or RESTEasy from under the same base URL, and finally, the most important, you can use Spring ModelAndView objects as return arguments from @GET resource methods. Setup requires you using the Spring DispatcherServlet in your web.xml file, as well as importing the springmvc-resteasy.xml file into your base Spring beans xml file. Here's an example web.xml file:
6060 </para>
6161 <programlisting>
6262 &lt;web-app&gt;
8686 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
8787 ">
8888
89 <!-- Import basic SpringMVC Resteasy integration -->
89 <!-- Import basic SpringMVC RESTEasy integration -->
9090 <import resource="classpath:springmvc-resteasy.xml"/>
9191 ....
9292 ]]>
9494 <para>
9595 You can specify resteasy configuration options by overriding the resteasy.deployment bean which is an instance
9696 of org.jboss.resteasy.spi.ResteasyDeployment. Here's an example of adding media type suffix mappings as well
97 as enabling the Resteasy asynchronous job service.
97 as enabling the RESTEasy asynchronous job service.
9898 </para>
9999 <programlisting>
100100 <![CDATA[
107107 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
108108 ">
109109
110 <!-- Import basic SpringMVC Resteasy integration -->
110 <!-- Import basic SpringMVC RESTEasy integration -->
111111 <import resource="classpath:springmvc-resteasy.xml" />
112112
113113 <!-- override the bean definition for deployment -->
163163 <url-pattern>/*</url-pattern>
164164 </servlet-mapping>
165165
166 <!-- required Resteasy Configuration Switch directs auto scanning
166 <!-- required RESTEasy Configuration Switch directs auto scanning
167167 of the archive for JAX-RS resource files
168168 -->
169169 <context-param>
0 <chapter id="Reactive">
1 <title>Reactive programming support</title>
2 <para>
3 JAX-RS 2.1 adds support for returning the <link linkend="CompletionStage">asynchronous
4 reactive type <code>CompletableFuture</code></link>, but
5 RESTEasy supports much more than this, when it comes to asynchronous programming.
6 </para>
7 <sect1>
8 <title>Plugable reactive types</title>
9 <para>
10 Out of the box, RESTEasy supports <code>CompletableFuture</code> for single events, and
11 <code>org.reactivestreams.Publisher</code> (from <link linkend="http://www.reactive-streams.org">Reactive Streams</link>)
12 for multiple events.
13 </para>
14 <para>
15 The optional modules <code>resteasy-rxjava</code> and
16 <code>resteasy-rxjava2</code> add support for the <link linkend="https://github.com/ReactiveX/RxJava">RxJava 1 and 2</link>
17 reactive types, such as <code>Single</code> and <code>Observable</code>, which means if you import
18 this dependency you can just start returning reactive types from those frameworks from your resource methods.
19 </para>
20 <para>
21 Adding support for other reactive types can be done by declaring a <code>@Provider</code> for the interfaces
22 <code>AsyncStreamProvider</code> (for streams) and <code>AsyncResponseProvider</code> (for single values), which
23 both have a single method to convert the new reactive type into (respectively) a <code>Publisher</code> (for streams)
24 or a <code>CompletionStage</code> (for single values).
25 </para>
26 </sect1>
27 <sect1>
28 <title>Behavior of reactive types</title>
29 <para>
30 Single-value reactive types behave like the specification of JAX-RS 2.1 wrt. <code>CompletionStage</code>,
31 which is that the reactive value will be subscribed to, the request will be turned asynchronous, and only
32 resumed when the reactive value is resolved to either a value (normal completion), or an exception.
33 </para>
34 <para>
35 Multiple-value reactive types (streams) behave in three possible ways, depending on how the resource method
36 is annotated:
37 </para>
38 <variablelist>
39 <varlistentry>
40 <term>Default case (no special annotation)</term>
41 <listitem>
42 Collect every value until the stream is complete, then wrap into a <code>java.util.List</code> entity
43 and send to the client.
44 </listitem>
45 </varlistentry>
46 <varlistentry>
47 <term><code>@Produces(MediaType.SERVER_SENT_EVENTS)</code></term>
48 <listitem>
49 Send each value as a Server-Sent Event. This is an alternative to the more verbose <link linkend="SSE-Server">SSE
50 server support in JAX-RS 2.1</link>.
51 </listitem>
52 </varlistentry>
53 <varlistentry>
54 <term><code>@Stream</code></term>
55 <listitem>
56 Write each value to the response as they become available. This is most useful for values you can cut in pieces,
57 such as strings, bytes, buffers, etc.
58 </listitem>
59 </varlistentry>
60 </variablelist>
61 </sect1>
62 </chapter>
22
33 <para>
44
5 Because Resteasy is deployed as a servlet, you must use standard web.xml constraints to enable authentication and authorization.
5 Because RESTEasy is deployed as a servlet, you must use standard web.xml constraints to enable authentication and authorization.
66 </para>
77 <para>
88
3030 </para>
3131 <para>
3232
33 Resteasy JAX-RS supports the @RolesAllowed, @PermitAll and @DenyAll annotations on JAX-RS methods. By default though, Resteasy does not recognize these annotations. You have to
34 configure Resteasy to turn on role-based security by setting a context parameter. NOTE!!! Do not turn on this switch if you are using EJBs. The EJB container will provide this
35 functionality instead of Resteasy.
33 RESTEasy JAX-RS supports the @RolesAllowed, @PermitAll and @DenyAll annotations on JAX-RS methods. By default though, RESTEasy does not recognize these annotations. You have to
34 configure RESTEasy to turn on role-based security by setting a context parameter. NOTE!!! Do not turn on this switch if you are using EJBs. The EJB container will provide this
35 functionality instead of RESTEasy.
3636
3737 </para>
3838 <programlisting>
4646 </web-app>]]>
4747 </programlisting>
4848
49 <para>There is a bit of quirkiness with this approach. You will have to declare all roles used within the Resteasy JAX-RS war file that you are using in your JAX-RS classes and set up a security constraint that permits all of these roles access to every URL handled by the JAX-RS runtime. You'll just have to trust that Resteasy JAX-RS authorizes properly.
49 <para>There is a bit of quirkiness with this approach. You will have to declare all roles used within the RESTEasy JAX-RS war file that you are using in your JAX-RS classes and set up a security constraint that permits all of these roles access to every URL handled by the JAX-RS runtime. You'll just have to trust that RESTEasy JAX-RS authorizes properly.
5050 </para>
5151 <para>
5252
53 How does Resteasy do authorization? Well, its really simple. It just sees if a method is annotated with @RolesAllowed and then just does HttpServletRequest.isUserInRole. If one of the @RolesAllowed passes, then allow the request, otherwise, a response is sent back with a 401 (Unauthorized) response code.
53 How does RESTEasy do authorization? Well, its really simple. It just sees if a method is annotated with @RolesAllowed and then just does HttpServletRequest.isUserInRole. If one of the @RolesAllowed passes, then allow the request, otherwise, a response is sent back with a 401 (Unauthorized) response code.
5454 </para>
5555 <para>
5656
57 So, here's an example of a modified RESTEasy WAR file. You'll notice that every role declared is allowed access to every URL controlled by the Resteasy servlet.
57 So, here's an example of a modified RESTEasy WAR file. You'll notice that every role declared is allowed access to every URL controlled by the RESTEasy servlet.
5858 </para>
5959 <para>
6060
00 <chapter id="StringConverter">
11 <title>String marshalling for String based @*Param</title>
2 <para>@PathParam, @QueryParam, @MatrixParam, @FormParam, and @HeaderParam are represented as strings in a raw
3 HTTP request. The specification says that these types of injected parameters can be converted to objects
4 if these objects have a valueOf(String) static method or a constructor that takes one String parameter.
5 What if you have a class where valueOf() or this string constructor doesn't exist or is inappropriate for
6 an HTTP request? JAX-RS 2.0 has the javax.ws.rs.ext.ParamConverterProvider to help in this situation.
7 See javadoc for more details.
8 </para>
2
3 <sect1>
4 <title>Simple conversion</title>
5
6 <para>
7 Parameters and properties annotated with <classname>@CookieParam</classname>,
8 <classname>@HeaderParam</classname>, <classname>@MatrixParam</classname>, <classname>@PathParam</classname>, or
9 <classname>@QueryParam</classname> are represented as strings in a raw HTTP request. The specification
10 says that any of these injected parameters can be converted to an object if the object's class has
11 a <methodname>valueOf(String)</methodname> static method or a constructor that takes one <classname>String</classname>parameter.
12 In the following, for example,
13 </para>
14 <programlisting>
15 public static class Customer {
16 private String name;
17
18 public Customer(String name) {
19 this.name = name;
20 }
21
22 public String getName() {
23 return name;
24 }
25 }
26
27 @Path("test")
28 public static class TestResource {
29
30 @GET
31 @Path("")
32 public Response test(@QueryParam("cust") Customer cust) {
33 return Response.ok(cust.getName()).build();
34 }
35 }
36
37 @Test
38 public void testQuery() throws Exception {
39 Invocation.Builder request = ClientBuilder.newClient().target("http://localhost:8081/test?cust=Bill").request();
40 Response response = request.get();
41 ...
42 }
43 </programlisting>
44 <para>
45 the query "?cust=Bill" will be transformed automatically to an instance of <classname>Customer</classname> with name
46 == "Bill".
47 </para>
48 </sect1>
49
50 <sect1>
51 <title>ParamConverter</title>
52
53 <para>
54 What if you have a class where <methodname>valueOf()</methodname>or this string constructor don't exist or are inappropriate
55 for an HTTP request? JAX-RS 2.0 has the <classname>javax.ws.rs.ext.ParamConverterProvider</classname> to help
56 in this situation.
57 </para>
58
59 <para>
60 A <classname>ParamConverterProvider</classname> is a provider defined as follows:
61 </para>
62
63 <programlisting>
64 public interface ParamConverterProvider {
65
66 public &lt;T&gt; ParamConverter&lt;T&gt; getConverter(Class&lt;T&gt; rawType, Type genericType, Annotation annotations[]);
67 }
68 </programlisting>
69
70 <para>
71 where a <classname>ParamConverter</classname> is defined:
72 </para>
73
74 <programlisting>
75 public interface ParamConverter&lt;T&gt; {
76 ...
77 public T fromString(String value);
78 public String toString(T value);
79 }
80 </programlisting>
81
82 <para>
83 For example, consider <classname>DateParamConverterProvider</classname> and <classname>DateParamConverter</classname>:
84 </para>
85
86 <programlisting>
87 @Provider
88 public class DateParamConverterProvider implements ParamConverterProvider {
89
90 @SuppressWarnings("unchecked")
91 @Override
92 public &lt;T&gt; ParamConverter&lt;T&gt; getConverter(Class&lt;T&gt; rawType, Type genericType, Annotation[] annotations) {
93 if (rawType.isAssignableFrom(Date.class)) {
94 return (ParamConverter&lt;T&gt;) new DateParamConverter();
95 }
96 return null;
97 }
98 }
99
100 public class DateParamConverter implements ParamConverter&lt;Date&gt; {
101
102 public static final String DATE_PATTERN = "yyyyMMdd";
103
104 @Override
105 public Date fromString(String param) {
106 try {
107 return new SimpleDateFormat(DATE_PATTERN).parse(param.trim());
108 } catch (ParseException e) {
109 throw new BadRequestException(e);
110 }
111 }
112
113 @Override
114 public String toString(Date date) {
115 return new SimpleDateFormat(DATE_PATTERN).format(date);
116 }
117 }
118 </programlisting>
119
120 <para>
121 Sending a <classname>Date</classname> in the form of a query, e.g., "?date=20161217" will cause the string "20161217"
122 to be converted to a <classname>Date</classname> on the server.
123 </para>
124 </sect1>
125
126 <sect1>
127 <title>StringParameterUnmarshaller</title>
128
129 <para>
130 In addition to the JAX-RS <classname>javax.ws.rs.ext.ParamConverterProvider</classname>,
131 RESTEasy also has its own <classname>org.jboss.resteasy.StringParameterUnmarshaller</classname>, defined
132 </para>
133
134 <programlisting>
135 public interface StringParameterUnmarshaller&lt;T&gt;
136 {
137 void setAnnotations(Annotation[] annotations);
138
139 T fromString(String str);
140 }
141 </programlisting>
142 <para>
143 It is similar to <classname>javax.ws.rs.ext.ParamConverter</classname> except that
144 </para>
145 <itemizedlist>
146 <listitem>it converts only from <classname>String</classname>s;</listitem>
147 <listitem>it is configured with the annotations on the injected parameter, which
148 allows for fine-grained control over the injection; and</listitem>
149 <listitem>it is bound to a given parameter by an annotation that is annotated with the meta-annotation
150 <classname>org.jboss.resteasy.annotations.StringParameterUnmarshallerBinder:</classname></listitem>
151 </itemizedlist>
152
153 <programlisting>
154 @Target({ElementType.ANNOTATION_TYPE})
155 @Retention(RetentionPolicy.RUNTIME)
156 public @interface StringParameterUnmarshallerBinder
157 {
158 Class&lt;? extends StringParameterUnmarshaller&gt; value();
159 }
160 </programlisting>
161 <para>
162 For example,
163 </para>
164
165 <programlisting>
166 @Retention(RetentionPolicy.RUNTIME)
167 @StringParameterUnmarshallerBinder(TestDateFormatter.class)
168 public @interface TestDateFormat {
169 String value();
170 }
171
172 public static class TestDateFormatter implements StringParameterUnmarshaller&lt;Date&gt; {
173 private SimpleDateFormat formatter;
174
175 public void setAnnotations(Annotation[] annotations) {
176 TestDateFormat format = FindAnnotation.findAnnotation(annotations, TestDateFormat.class);
177 formatter = new SimpleDateFormat(format.value());
178 }
179
180 public Date fromString(String str) {
181 try {
182 return formatter.parse(str);
183 } catch (ParseException e) {
184 throw new RuntimeException(e);
185 }
186 }
187 }
188
189 @Path("/")
190 public static class TestResource {
191
192 @GET
193 @Produces("text/plain")
194 @Path("/datetest/{date}")
195 public String get(@PathParam("date") @TestDateFormat("MM-dd-yyyy") Date date) {
196 Calendar c = Calendar.getInstance();
197 c.setTime(date);
198 return date.toString();
199 }
200 }
201 </programlisting>
202
203 <para>
204 Note that the annotation <classname>@StringParameterUnmarshallerBinder</classname> on the
205 annotation <classname>@TestDateFormat</classname> binds the formatter
206 <classname>TestDateFormatter</classname> to a parameter annotated with <classname>@TestDateFormat</classname>.
207 In this example, <classname>TestDateFormatter</classname> is used to format the <classname>Date</classname> parameter.
208 Note also that the parameter "MM-dd-yyyy" to <classname>@TestDateFormat</classname> is accessible from
209 <methodname>TestDateFormatter.setAnnotations()</methodname>.
210 </para>
211 </sect1>
212
213 <sect1>
214 <title>Collections</title>
215
216 <para>
217 For parameters and properties annotated with <classname>@CookieParam</classname>, <classname>@HeaderParam</classname>,
218 <classname>@MatrixParam</classname>, <classname>@PathParam,</classname> or <classname>@QueryParam</classname>, the JAX-RS specification
219 [<ulink url="https://jcp.org/aboutJava/communityprocess/final/jsr339/index.html">https://jcp.org/aboutJava/communityprocess/final/jsr339/index.html</ulink>]
220 allows conversion as defined in the Javadoc of the
221 corresponding annotation. In general, the following types are supported:
222 </para>
223
224 <orderedlist>
225 <listitem>
226 Types for which a <classname>ParamConverter</classname> is available via a registered <classname>ParamConverterProvider</classname>. See
227 Javadoc for these classes for more information.
228 </listitem>
229 <listitem>
230 Primitive types.
231 </listitem>
232 <listitem>
233 Types that have a constructor that accepts a single <classname>String</classname> argument.
234 </listitem>
235 <listitem>
236 Types that have a static method named <methodname>valueOf</methodname> or <methodname>fromString</methodname>
237 with a single <classname>String</classname> argument
238 that return an instance of the type. If both methods are present then <methodname>valueOf</methodname> MUST be used
239 unless the type is an enum in which case <methodname>fromString</methodname> MUST be used.
240 </listitem>
241 <listitem>
242 List&lt;T&gt;, Set&lt;T&gt;, or SortedSet&lt;T&gt;, where T satisfies 3 or 4 above.
243 </listitem>
244 </orderedlist>
245
246 <para>
247 Items 1, 3, and 4 have been discussed above, and item 2 is obvious. Note that item 5 allows for
248 collections of parameters. How these collections are expressed in HTTP messages depends, by
249 default, on the particular kind of parameter. In most cases, the notation for collections is based
250 on convention rather than a specification.
251 </para>
252
253 <sect2>
254 <title>@QueryParam</title>
255
256 <para>
257 For example, a multivalued query parameter is conventionally expressed like this:
258 </para>
259
260 <programlisting>
261 http://bluemonkeydiamond.com?q=1&amp;q=2&amp;q=3
262 </programlisting>
263
264 <para>
265 In this case, there is a query with name "q" and value {1, 2, 3}. This notation is further supported
266 in JAX-RS by the method
267 </para>
268
269 <programlisting>
270 public MultivaluedMap&lt;String, String&gt; getQueryParameters();
271 </programlisting>
272
273 <para>
274 in <classname>javax.ws.rs.core.UriInfo</classname>.
275 </para>
276 </sect2>
277
278 <sect2>
279 <title>@MatrixParam</title>
280
281 <para>
282 There is no specified syntax for collections derived from matrix parameters, but
283 </para>
284
285 <orderedlist>
286 <listitem>
287 matrix parameters in a URL segment are conventionally separated by ";", and
288 </listitem>
289 <listitem>
290 the method
291 <programlisting>
292 MultivaluedMap&lt;String, String&gt; getMatrixParameters();
293 </programlisting>
294 <para>
295 in <classname>javax.ws.rs.core.PathSegment</classname> supports extraction of collections from matrix parameters.
296 </para>
297 </listitem>
298 </orderedlist>
299
300 <para>
301 RESTEasy adopts the convention that multiple instances of a matrix parameter with the same name
302 are treated as a collection. For example,
303 </para>
304 <programlisting>
305 http://bluemonkeydiamond.com/sippycup;m=1;m=2;m=3
306 </programlisting>
307
308 <para>
309 is interpreted as a matrix parameter on path segment "sippycup" with name "m" and value {1, 2, 3}.
310 </para>
311 </sect2>
312
313 <sect2>
314 <title>@HeaderParam</title>
315
316 <para>
317 The HTTP 1.1 specification doesn't exactly specify that multiple components of a header value
318 should be separated by commas, but commas are used in those headers that naturally use lists,
319 e.g. Accept and Allow. Also, note that the method
320 </para>
321
322 <programlisting>
323 public MultivaluedMap&lt;String, String&gt; getRequestHeaders();
324 </programlisting>
325
326 <para>
327 in <classname>javax.ws.rs.core.HttpHeaders</classname> returns a <classname>MultivaluedMap</classname>.
328 It is natural, then, for RESTEasy to treat
329 </para>
330
331 <programlisting>
332 x-header: a, b, c
333 </programlisting>
334
335 <para>
336 as mapping name "x-header" to set {a, b, c}.
337 </para>
338 </sect2>
339
340 <sect2>
341 <title>@CookieParam</title>
342
343 <para>
344 The syntax for cookies is specified, but, unfortunately, it is specified in multiple competing
345 specifications. Typically, multiple name=value cookie pairs are separated by ";". However, unlike
346 the case with query and matrix parameters, there is no specified JAX-RS method that returns a
347 collection of cookie values. Consequently, if two cookies with the same name are received on
348 the server and directed to a collection typed parameter, RESTEasy will inject only the second one.
349 Note, in fact, that the method
350 </para>
351
352 <programlisting>
353 public Map&lt;String, Cookie&gt; getCookies();
354 </programlisting>
355
356 <para>
357 in <classname>javax.ws.rs.core.HttpHeaders</classname> returns a <classname>Map</classname> rather than a
358 <classname>MultivaluedMap</classname>.
359 </para>
360
361 </sect2>
362
363 <sect2>
364 <title>@PathParam</title>
365
366 <para>
367 Deriving a collection from path segments is somewhat less natural than it is for other parameters,
368 but JAX-RS supports the injection of multiple <classname>javax.ws.rs.core.PathSegment</classname>s. There are a
369 couple of ways of obtaining multiple <classname>PathSegment</classname>s. One is through the use of multiple path
370 variables with the same name. For example, the result of calling <methodname>testTwoSegmentsArray()</methodname> and
371 <methodname>testTwoSegmentsList()</methodname> in
372 </para>
373
374 <programlisting>
375 @Path("")
376 public static class TestResource {
377
378 @GET
379 @Path("{segment}/{other}/{segment}/array")
380 public Response getTwoSegmentsArray(@PathParam("segment") PathSegment[] segments) {
381 System.out.println("array segments: " + segments.length);
382 return Response.ok().build();
383 }
384
385 @GET
386 @Path("{segment}/{other}/{segment}/list")
387 public Response getTwoSegmentsList(@PathParam("segment") List&lt;PathSegment&gt; segments) {
388 System.out.println("list segments: " + segments.size());
389 return Response.ok().build();
390 }
391 }
392
393 ...
394
395 @Test
396 public void testTwoSegmentsArray() throws Exception {
397 Invocation.Builder request = client.target("http://localhost:8081/a/b/c/array").request();
398 Response response = request.get();
399 Assert.assertEquals(200, response.getStatus());
400 response.close();
401 }
402
403 @Test
404 public void testTwoSegmentsList() throws Exception {
405 Invocation.Builder request = client.target("http://localhost:8081/a/b/c/list").request();
406 Response response = request.get();
407 Assert.assertEquals(200, response.getStatus());
408 response.close();
409 }
410 </programlisting>
411
412 <para>is</para>
413
414 <programlisting>
415 array segments: 2
416 list segments: 2
417 </programlisting>
418
419 <para>
420 An alternative is to use a wildcard template parameter. For example, the output of calling
421 <methodname>testWildcardArray()</methodname> and <methodname>testWildcardList() </methodname>in
422 </para>
423
424 <programlisting>
425 @Path("")
426 public static class TestResource {
427
428 @GET
429 @Path("{segments:.*}/array")
430 public Response getWildcardArray(@PathParam("segments") PathSegment[] segments) {
431 System.out.println("array segments: " + segments.length);
432 return Response.ok().build();
433 }
434
435 @GET
436 @Path("{segments:.*}/list")
437 public Response getWildcardList(@PathParam("segments") List&lt;PathSegment&gt; segments) {
438 System.out.println("list segments: " + segments.size());
439 return Response.ok().build();
440 }
441
442 ...
443
444 @Test
445 public void testWildcardArray() throws Exception {
446 Invocation.Builder request = client.target("http://localhost:8081/a/b/c/array").request();
447 Response response = request.get();
448 response.close();
449 }
450
451 @Test
452 public void testWildcardList() throws Exception {
453 Invocation.Builder request = client.target("http://localhost:8081/a/b/c/list").request();
454 Response response = request.get();
455 response.close();
456 }
457 </programlisting>
458
459 <para>is</para>
460
461 <programlisting>
462 array segments: 3
463 list segments: 3
464 </programlisting>
465
466 </sect2>
467 </sect1>
468
469 <sect1>
470 <title>Extension to <classname>ParamConverter</classname> semantics</title>
471
472 <para>
473 In the JAX-RS semantics, a <classname>ParamConverter</classname> is supposed to convert a single <classname>String</classname> that
474 represents an individual object. RESTEasy extends the semantics to allow a <classname>ParamConverter</classname>
475 to parse the <classname>String</classname> representation of multiple objects and generate a <classname>List&lt;T&gt;</classname>,
476 <classname>Set&lt;T&gt;</classname>, <classname>SortedSet&lt;T&gt;</classname>, array, or, indeed, any multivalued data structure
477 whatever. First, consider the resource
478 </para>
479
480 <programlisting>
481 @Path("queryParam")
482 public static class TestResource {
483
484 @GET
485 @Path("")
486 public Response conversion(@QueryParam("q") List&lt;String&gt; list) {
487 return Response.ok(stringify(list)).build();
488 }
489 }
490
491 private static &lt;T&gt; String stringify(List&lt;T&gt; list) {
492 StringBuffer sb = new StringBuffer();
493 for (T s : list) {
494 sb.append(s).append(',');
495 }
496 return sb.toString();
497 }
498 </programlisting>
499
500 <para>
501 Calling <classname>TestResource</classname> as follows, using the standard notation,
502 </para>
503
504 <programlisting>
505 @Test
506 public void testQueryParamStandard() throws Exception {
507 ResteasyClient client = new ResteasyClientBuilder().build();
508 Invocation.Builder request = client.target("http://localhost:8081/queryParam?q=20161217&amp;q=20161218&amp;q=20161219").request();
509 Response response = request.get();
510 System.out.println("response: " + response.readEntity(String.class));
511 }
512 </programlisting>
513
514 <para>results in</para>
515
516 <programlisting>
517 response: 20161217,20161218,20161219,
518 </programlisting>
519
520 <para>
521 Suppose, instead, that we want to use a comma separated notation. We can add
522 </para>
523
524 <programlisting>
525 public static class MultiValuedParamConverterProvider implements ParamConverterProvider
526
527 @SuppressWarnings("unchecked")
528 @Override
529 public &lt;T&gt; ParamConverter&lt;T&gt; getConverter(Class&lt;T&gt; rawType, genericType, Annotation[] annotations) {
530 if (List.class.isAssignableFrom(rawType)) {
531 return (ParamConverter&lt;T&gt;) new MultiValuedParamConverter();
532 }
533 return null;
534 }
535 }
536
537 public static class MultiValuedParamConverter implements ParamConverter&lt;List&lt;?&gt;&gt; {
538
539 @Override
540 public List&lt;?&gt; fromString(String param) {
541 if (param == null || param.trim().isEmpty()) {
542 return null;
543 }
544 return parse(param.split(","));
545 }
546
547 @Override
548 public String toString(List&lt;?&gt; list) {
549 if (list == null || list.isEmpty()) {
550 return null;
551 }
552 return stringify(list);
553 }
554
555 private static List&lt;String&gt; parse(String[] params) {
556 List&lt;String&gt; list = new ArrayList&lt;String&gt;();
557 for (String param : params) {
558 list.add(param);
559 }
560 return list;
561 }
562 }
563 </programlisting>
564
565 <para>Now we can call</para>
566
567 <programlisting>
568 @Test
569 public void testQueryParamCustom() throws Exception {
570 ResteasyClient client = new ResteasyClientBuilder().build();
571 Invocation.Builder request = client.target("http://localhost:8081/queryParam?q=20161217,20161218,20161219").request();
572 Response response = request.get();
573 System.out.println("response: " + response.readEntity(String.class));
574 }
575 </programlisting>
576
577 <para>and get</para>
578
579 <programlisting>
580 response: 20161217,20161218,20161219,
581 </programlisting>
582
583 <para>
584 Note that in this case, <methodname>MultiValuedParamConverter.fromString()</methodname> creates and returns an
585 <classname>ArrayList</classname>, so <methodname>TestResource.conversion()</methodname> could be rewritten
586 </para>
587
588 <programlisting>
589 @Path("queryParam")
590 public static class TestResource {
591
592 @GET
593 @Path("")
594 public Response conversion(@QueryParam("q") ArrayList&lt;String&gt; list) {
595 return Response.ok(stringify(list)).build();
596 }
597 }
598 </programlisting>
599
600 <para>
601 On the other hand, <classname>MultiValuedParamConverter</classname> could be rewritten to return a
602 <classname>LinkList</classname> and the parameter list in <methodname>TestResource.conversion()</methodname>
603 could be either a <classname>List</classname> or a <classname>LinkedList</classname>.
604 </para>
605
606 <para>
607 Finally, note that this extension works for arrays as well. For example,
608 </para>
609
610 <programlisting>
611 public static class Foo {
612 private String foo;
613 public Foo(String foo) {this.foo = foo;}
614 public String getFoo() {return foo;}
615 }
616
617 public static class FooArrayParamConverter implements ParamConverter&lt;Foo[]&gt; {
618
619 @Override
620 public Foo[] fromString(String value)
621 {
622 String[] ss = value.split(",");
623 Foo[] fs = new Foo[ss.length];
624 int i = 0;
625 for (String s : ss) {
626 fs[i++] = new Foo(s);
627 }
628 return fs;
629 }
630
631 @Override
632 public String toString(Foo[] values)
633 {
634 StringBuffer sb = new StringBuffer();
635 for (int i = 0; i &lt; values.length; i++) {
636 sb.append(values[i].getFoo()).append(",");
637 }
638 if (sb.length() &gt; 0) {
639 sb.deleteCharAt(sb.length() - 1);
640 }
641 return sb.toString();
642 }
643 }
644
645 @Provider
646 public static class FooArrayParamConverterProvider implements ParamConverterProvider {
647
648 @SuppressWarnings("unchecked")
649 @Override
650 public &lt;T&gt; ParamConverter&lt;T&gt; getConverter(Class&lt;T&gt; rawType, Type genericType, Annotation[] annotations) {
651 if (rawType.equals(Foo[].class));
652 return (ParamConverter&lt;T&gt;) new FooArrayParamConverter();
653 }
654 }
655
656 @Path("")
657 public static class ParamConverterResource {
658
659 @GET
660 @Path("test")
661 public Response test(@QueryParam("foos") Foo[] foos) {
662 return Response.ok(new FooArrayParamConverter().toString(foos)).build();
663 }
664 }
665 </programlisting>
666 </sect1>
667
9668 </chapter>
2929 </para>
3030 <para>
3131
32 Let's say you have the Resteasy servlet configured and reachable at a root path of http://myhost.com/services. The requests would be handled by the Library class:
32 Let's say you have the RESTEasy servlet configured and reachable at a root path of http://myhost.com/services. The requests would be handled by the Library class:
3333 </para>
3434 <para>
3535
107107
108108 <para>
109109 If a validation problem occurs, either a problem with the validation definitions or a constraint violation,
110 Resteasy will set the return header <classname>org.jboss.resteasy.api.validation.Validation.VALIDATION_HEADER</classname>
110 RESTEasy will set the return header <classname>org.jboss.resteasy.api.validation.Validation.VALIDATION_HEADER</classname>
111111 ("validation-exception") to "true".
112112 </para>
113113
114114 <para>
115 If Resteasy detects a structural validation problem, such as a validation annotation with a
115 If RESTEasy detects a structural validation problem, such as a validation annotation with a
116116 missing validator class, it will return a String representation of a
117117 <classname>javax.validation.ValidationException</classname>. For example
118118 </para>
122122 ]]></programlisting>
123123
124124 <para>
125 If any constraint violations are detected, Resteasy will return a report in one of a variety
125 If any constraint violations are detected, RESTEasy will return a report in one of a variety
126126 of formats. If one of "application/xml" or "application/json" occur in the "Accept" request header,
127 Resteasy will return an appropriately marshalled instance of
127 RESTEasy will return an appropriately marshalled instance of
128128 <classname>org.jboss.resteasy.api.validation.ViolationReport</classname>:
129129 </para>
130130
243243 </para>
244244
245245 <para>If neither "application/xml" or "application/json" occur in the "Accept" request header,
246 Resteasy returns a report with a String representation of each
246 RESTEasy returns a report with a String representation of each
247247 <classname>ResteasyConstraintViolation</classname>, where
248248 each field is delimited by '[' and ']', followed by a '\r', with a final '\r' at the end.
249249 For example,
44
55 RESTEasy comes with built in support for YAML using the SnakeYAML library. To enable YAML support,
66 you need to drop in the SnakeYaml 1.8 jar and the resteasy-yaml-provider.jar (whatever the current version is) in RestEASY's classpath.
7 Then you need to manually register the org.jboss.resteasy.plugins.providers.YamlProvider provider. Note this feature is currently
8 deprecated due to security vulnerabilities and will likely be removed in the future.
79 </para>
810 <para>
911
176176 </para>
177177 <para>
178178
179 You can have Resteasy inject a PathSegment instead of a value with your @PathParam.
179 You can have RESTEasy inject a PathSegment instead of a value with your @PathParam.
180180 </para>
181181 <para>
182182
1919 </para>
2020 <para>
2121
22 Currently since Resteasy is built on top of a Servlet, it does not distinguish between URI query strings or url form encoded parameters. Like PathParam, your parameter type can be an String, primitive, or class that has a String constructor or static valueOf() method.
22 Currently since RESTEasy is built on top of a Servlet, it does not distinguish between URI query strings or url form encoded parameters. Like PathParam, your parameter type can be an String, primitive, or class that has a String constructor or static valueOf() method.
2323 </para>
2424 <para>
2525
00 <chapter id="ContentRange">
11 <title>Content-Range Support</title>
22 <para>
3 Resteasy supports <literal>Range</literal> requests for <literal>java.io.File</literal> response entities.
3 RESTEasy supports <literal>Range</literal> requests for <literal>java.io.File</literal> response entities.
44 </para>
55 <programlisting><![CDATA[
66 @Path("/")
00 <chapter>
11 <title>CORS</title>
22 <para>
3 Resteasy has a <literal>ContainerRequestFilter</literal> that can be used to handle CORS preflight and actual requests.
3 RESTEasy has a <literal>ContainerRequestFilter</literal> that can be used to handle CORS preflight and actual requests.
44 <literal>org.jboss.resteasy.plugins.interceptors.CorsFilter</literal>. You must allocate this and register it
55 as a singleton provider from your Application class. See the javadoc or its various settings.
66 </para>
00 <chapter id="gzip">
1 <title>Content encoding</title>
2
3 <sect1>
14 <title>GZIP Compression/Decompression</title>
25 <para>
3 Resteasy supports (though not by default - see below)
6 RESTEasy supports (though not by default - see below)
47 GZIP decompression. If properly configured,
58 the client framework or a JAX-RS service, upon receiving
69 a message body with a Content-Encoding of "gzip",
912 set the Accept-Encoding header to be "gzip, deflate" so you do not
1013 have to set this header yourself.
1114 </para>
12 <para>Resteasy also supports (though not by default - see below) automatic
15 <para>RESTEasy also supports (though not by default - see below) automatic
1316 compression. If the client framework is sending a request
1417 or the server is sending a response with the Content-Encoding header
15 set to "gzip", Resteasy will (if properly configured)
18 set to "gzip", RESTEasy will (if properly configured)
1619 do the compression. So that you do not
1720 have to set the Content-Encoding header directly, you can use the
1821 @org.jboss.resteasy.annotation.GZIP annotation.
4043 }
4144 </programlisting>
4245
43 <sect1 id="configuring">
46 <sect2 id="configuring">
4447 <title>Configuring GZIP compression / decompression</title>
4548
4649 <para><emphasis role="bold">Note.</emphasis> Decompression carries a risk of attack
4750 from a bad actor that can package an entity that will expand greatly. Consequently,
48 Resteasy disables GZIP compression / decompression by default.
51 RESTEasy disables GZIP compression / decompression by default.
4952 </para>
5053
5154 <para>
5356 </para>
5457
5558 <orderedlist>
56 <listitem>org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor:
59 <listitem>org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor:
5760 If the Content-Encoding header is present and has the value "gzip",
5861 <classname>GZIPDecodingInterceptor</classname> will install an <classname>InputStream</classname>
5962 that decompresses the message body.
6063 </listitem>
6164
62 <listitem>org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor:
65 <listitem>org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor:
6366 If the Content-Encoding header is present and has the value "gzip",
6467 <classname>GZIPEncodingInterceptor</classname> will install an <classname>OutputStream</classname>
6568 that compresses the message body.
6669 </listitem>
6770
68 <listitem>org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter:
71 <listitem>org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter:
6972 If the Accept-Encoding header does not exist, <classname>AcceptEncodingGZIPFilter</classname>
7073 will add Accept-Encoding with the value "gzip, deflate". If the Accept-Encoding header exists but
7174 does not contain "gzip", <classname>AcceptEncodingGZIPFilter</classname> will append ", gzip".
8083 The default limit is 10,000,000, but a different value can be configured. See below.
8184 </para>
8285
83 <sect2>
86 <sect3>
8487 <title>Server side configuration</title>
8588
8689 <para>
8790 The interceptors may be enabled by including their classnames in a
88 javax.ws.rs.ext.Providers file on the classpath. The upper limit on deflated files may
91 META-INF/services/javax.ws.rs.ext.Providers file on the classpath. The upper limit on deflated files may
8992 be configured by setting the web application context parameter "resteasy.gzip.max.input".
9093 If the limit is exceeded on the server side, GZIPDecodingInterceptor will return a
9194 <classname>Response</classname> with status 413 ("Request Entity Too Large") and
100103 named accordingly in javax.ws.rs.ext.Providers. However, they continue to exist in
101104 <classname>org.jboss.resteasy.plugins.interceptors.encoding</classname> in module
102105 resteasy-legacy, so, if resteasy-legacy is available, the original names can be used.
103 See Chapter <link linkend='Migration_to_3_1'>Migration to Resteasy 3.1</link> for more
106 See Chapter <link linkend='Migration_to_3_1'>Migration to RESTEasy 3.1</link> for more
104107 information.
105108 </para>
106109
107 </sect2>
108
109 <sect2>
110 </sect3>
111
112 <sect3>
110113 <title>Client side configuration</title>
111114
112115 <para>
139142 <classname>ProcessingException</classname> with a message specifying the upper limit.
140143 </para>
141144
142 </sect2>
145 </sect3>
146 </sect2>
143147 </sect1>
144
145 </chapter>
148
149 <sect1>
150 <title>General content encoding</title>
151
152 <para>
153 The designation of a compressible entity by the use of the <classname>@GZIP</classname> annotation is a
154 built in, specific instance of a more general facility supported by RESTEasy. There are three components
155 to this facility.
156 </para>
157
158 <orderedlist>
159 <listitem>
160 The annotation <classname>org.jboss.resteasy.annotations.ContentEncoding</classname> is a "meta-annotation"
161 used on other annotations to indicate that they represent a Content-Encoding. For example, <classname>@GZIP</classname>
162 is defined
163
164 <programlisting>
165 @Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
166 @Retention(RetentionPolicy.RUNTIME)
167 @ContentEncoding("gzip")
168 public @interface GZIP
169 {
170 }
171 </programlisting>
172 The value of <classname>@ContentEncoding</classname> indicates the represented Content-Encoding. For <classname>@GZIP</classname>
173 it is "gzip".
174 </listitem>
175 <listitem>
176 <classname>ClientContentEncodingAnnotationFeature</classname> and
177 <classname>ServerContentEncodingAnnotationFeature</classname>,
178 two <classname>DynamicFeature</classname>s
179 in package <classname>org.jboss.resteasy.plugins.interceptors</classname>,
180 examine resource methods for annotations decorated with <classname>@ContentEncoding</classname>.
181 </listitem>
182 <listitem>
183 For each value found in a <classname>@ContentEncoding</classname> decorated annotation on a resource method, an instance of
184 <classname>ClientContentEncodingAnnotationFilter</classname> or
185 <classname>ServerContentEncodingAnnotationFilter</classname>,
186 <classname>javax.ws.rs.ext.WriterInterceptor</classname>s in package
187 <classname>org.jboss.resteasy.plugins.interceptors</classname>, is registered.
188 They are responsible for adding an appropriate Content-Encoding header. For example,
189 <classname>ClientContentEncodingAnnotationFilter</classname> is defined
190 <programlisting>
191 @ConstrainedTo(RuntimeType.CLIENT)
192 @Priority(Priorities.HEADER_DECORATOR)
193 public class ClientContentEncodingAnnotationFilter implements WriterInterceptor
194 {
195 protected String encoding;
196
197 public ClientContentEncodingAnnotationFilter(String encoding)
198 {
199 this.encoding = encoding;
200 }
201
202 @Override
203 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
204 {
205 context.getHeaders().putSingle(HttpHeaders.CONTENT_ENCODING, encoding);
206 context.proceed();
207 }
208 }
209 </programlisting>
210 When it is created, <classname>ClientContentEncodingAnnotationFeature</classname> passes in the value
211 to be used for Content-Encoding headers.
212 </listitem>
213 </orderedlist>
214
215 <para>
216 The annotation <classname>@GZIP</classname> is built into RESTEasy, but
217 <classname>ClientContentEncodingAnnotationFeature</classname> and <classname>ServerContentEncodingAnnotationFeature</classname>
218 will also recognize application defined annotations. For example,
219 </para>
220
221 <programlisting>
222 @Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
223 @Retention(RetentionPolicy.RUNTIME)
224 @ContentEncoding("compress")
225 public @interface Compress
226 {
227 }
228
229 @Path("")
230 public static class TestResource {
231
232 @GET
233 @Path("a")
234 @Compress
235 public String a() {
236 return "a";
237 }
238 }
239 </programlisting>
240
241 <para>
242 If <methodname>TestResource.a()</methodname> is invoked as follows
243 </para>
244
245 <programlisting>
246 @Test
247 public void testCompress() throws Exception
248 {
249 ResteasyClient client = new ResteasyClientBuilder().build();
250 Invocation.Builder request = client.target("http://localhost:8081/a").request();
251 request.acceptEncoding("gzip,compress");
252 Response response = request.get();
253 System.out.println("content-encoding: "+ response.getHeaderString("Content-Encoding"));
254 client.close();
255 }
256 </programlisting>
257
258 <para>
259 the output will be
260 </para>
261
262 <programlisting>
263 content-encoding: compress
264 </programlisting>
265 </sect1>
266
267 </chapter>
6262 <listitem>
6363 <para>Algorithm used to hash and sign the message. RSA signing and
6464 SHA256 hashing is the only supported algorithm at the moment by
65 Resteasy.</para>
65 RESTEasy.</para>
6666 </listitem>
6767 </varlistentry>
6868
152152 keys. For one, it becomes very easy for verifiers to find public keys.
153153 There's no real central store that is needed. DNS is a infrastructure IT
154154 knows how to deploy. Verifiers can choose which domains they allow requests
155 from. Resteasy supports discovering public keys via DNS. It also instead
155 from. RESTEasy supports discovering public keys via DNS. It also instead
156156 allows you to discover public keys within a local Java KeyStore if you do
157157 not want to use DNS. It also allows you to plug in your own mechanism to
158158 discover keys.</para>
171171 <para><programlisting> &lt;dependency&gt;
172172 &lt;groupId&gt;org.jboss.resteasy&lt;/groupId&gt;
173173 &lt;artifactId&gt;resteasy-crypto&lt;/artifactId&gt;
174 &lt;version&gt;3.1.4.Final&lt;/version&gt;
174 &lt;version&gt;3.5.0.Final&lt;/version&gt;
175175 &lt;/dependency&gt;
176176
177177 </programlisting></para>
180180 <section>
181181 <title>Signing API</title>
182182
183 <para>To sign a request or response using the Resteasy client or server
183 <para>To sign a request or response using the RESTEasy client or server
184184 framework you need to create an instance of
185185 org.jboss.resteasy.security.doseta.DKIMSignature. This class represents
186186 the DKIM-Signature header. You instantiate the DKIMSignature object and
226226 ClientResponse response = request.put();
227227 </programlisting>To sign a message you need a PrivateKey. This can be
228228 generated by KeyTool or manually using regular, standard JDK Signature
229 APIs. Resteasy currently only supports RSA key pairs. The DKIMSignature
229 APIs. RESTEasy currently only supports RSA key pairs. The DKIMSignature
230230 class also allows you to add and control how various pieces of metadata
231231 are added to the DKIM-Signature header and the signature calculation. See
232232 the javadoc for more details.</para>
238238 <section>
239239 <title>@Signed annotation</title>
240240
241 <para>Instead of using the API, Resteasy also provides you an
241 <para>Instead of using the API, RESTEasy also provides you an
242242 annotation alternative to the manual way of signing using a
243243 DKIMSignature instances is to use the
244244 @org.jboss.resteasy.annotations.security.doseta.Signed annotation. It is
372372 <section>
373373 <title>Managing Keys via a KeyRepository</title>
374374
375 <para>Resteasy manages keys for you through a
375 <para>RESTEasy manages keys for you through a
376376 org.jboss.resteasy.security.doseta.KeyRepository. By default, the
377377 KeyRepository is backed by a Java KeyStore. Private keys are always
378378 discovered by looking into this KeyStore. Public keys may also be
399399 <title>Configure Restreasy to use the KeyRepository</title>
400400
401401 <para>Next you need to configure the KeyRepository in your web.xml file
402 so that it is created and made available to Resteasy to discover private
402 so that it is created and made available to RESTEasy to discover private
403403 and public keys.You can reference a Java key store you want the Resteasy
404404 signature framework to use within web.xml using either
405405 <literal>resteasy.keystore.classpath</literal> or
2020 <para><programlisting> &lt;dependency&gt;
2121 &lt;groupId&gt;org.jboss.resteasy&lt;/groupId&gt;
2222 &lt;artifactId&gt;resteasy-crypto&lt;/artifactId&gt;
23 &lt;version&gt;3.1.4.Final&lt;/version&gt;
23 &lt;version&gt;3.5.0.Final&lt;/version&gt;
2424 &lt;/dependency&gt;
2525
2626 </programlisting></para>
135135 know how to parse a multipart message and Doseta doesn't. Its up to you
136136 what you want to use.</para>
137137
138 <para>Resteasy has two different interfaces for creating a
138 <para>RESTEasy has two different interfaces for creating a
139139 multipart/signed message. One for input, one for output. If your client or
140140 server wants to send an HTTP request or response with an multipart/signed
141141 body, it uses the
44 <parent>
55 <artifactId>resteasy-jaxrs-all</artifactId>
66 <groupId>org.jboss.resteasy</groupId>
7 <version>3.1.4.Final</version>
7 <version>3.5.0.Final</version>
88 </parent>
99
1010 <artifactId>eagledns-fork</artifactId>
00 package se.unlogic.standardutils.crypto;
1
2 import org.apache.log4j.Logger;
13
24 /**
35 * <p>
165167 private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
166168 private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
167169
170 private final static Logger logger = Logger.getLogger(Base64.class);
171
168172 /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
169173
170174 /** The 64 valid Base64 values. */
11611165
11621166 } // end try
11631167 catch (java.io.IOException e) {
1164 e.printStackTrace();
1168 logger.error(e.getMessage(), e);
11651169 // Just return originally-decoded bytes
11661170 } // end catch
11671171 finally {
66 ******************************************************************************/
77 package se.unlogic.standardutils.threads;
88
9 import org.apache.log4j.Logger;
10
911 import java.util.ArrayList;
1012 import java.util.List;
1113 import java.util.concurrent.CopyOnWriteArrayList;
3133 protected Status status = Status.RUNNING;
3234
3335 protected final ArrayList<Thread> threads = new ArrayList<Thread>();
34
36
37 private final static Logger logger = Logger.getLogger(ThreadPoolTaskGroupHandler.class);
3538
3639 public ThreadPoolTaskGroupHandler(int poolSize, boolean daemon){
3740
9598
9699 }catch(Throwable e){
97100
98 e.printStackTrace();
101 logger.error(e.getMessage(), e);
99102
100103 }finally{
101104
66 ******************************************************************************/
77 package se.unlogic.standardutils.xml;
88
9 import org.apache.log4j.Logger;
910 import org.w3c.dom.Document;
1011 import org.w3c.dom.Element;
1112 import org.w3c.dom.Node;
3839
3940 private static DocumentBuilder documentBuilder;
4041 private static DocumentBuilder namespaceAwareDocumentBuilder;
42 private final static Logger logger = Logger.getLogger(XMLUtils.class);
4143
4244 static {
4345 try {
4951
5052 namespaceAwareDocumentBuilder = documentBuilderFactory.newDocumentBuilder();
5153 } catch (ParserConfigurationException e) {
52 e.printStackTrace();
54 logger.error(e.getMessage(), e);
5355 }
5456 }
5557
7474 <maven-resource group="org.codehaus.jettison" artifact="jettison"/>
7575 </module-def>
7676
77 <module-def name="org.reactivestreams">
78 <maven-resource group="org.reactivestreams" artifact="reactive-streams"/>
79 </module-def>
80
81 <module-def name="org.eclipse.microprofile.restclient">
82 <maven-resource group="org.eclipse.microprofile.rest.client" artifact="microprofile-rest-client-api"/>
83 </module-def>
84
7785 <module-def name="com.fasterxml.jackson.core.jackson-core">
7886 <maven-resource group="com.fasterxml.jackson.core" artifact="jackson-core"/>
7987 </module-def>
8997 <module-def name="com.fasterxml.jackson.datatype.jackson-datatype-jdk8">
9098 <maven-resource group="com.fasterxml.jackson.datatype" artifact="jackson-datatype-jdk8"/>
9199 </module-def>
92
100
93101 <module-def name="com.fasterxml.jackson.datatype.jackson-datatype-jsr310">
94102 <maven-resource group="com.fasterxml.jackson.datatype" artifact="jackson-datatype-jsr310"/>
95103 </module-def>
96
104
97105 <module-def name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider">
98106 <maven-resource group="com.fasterxml.jackson.jaxrs" artifact="jackson-jaxrs-json-provider"/>
99107 <maven-resource group="com.fasterxml.jackson.jaxrs" artifact="jackson-jaxrs-base"/>
100108 <maven-resource group="com.fasterxml.jackson.module" artifact="jackson-module-jaxb-annotations" />
101109 </module-def>
102110
111 <module-def name="javax.json.bind.api">
112 <maven-resource group="javax.json.bind" artifact="javax.json.bind-api"/>
113 </module-def>
114
115 <!-- todo this is temporary and should be removed when wildfly makes the needed update
116 -->
117 <module-def name="org.eclipse.yasson">
118 <maven-resource group="org.eclipse" artifact="yasson"/>
119 </module-def>
120 <!-- todo this is temporary and should be removed when wildfly makes the needed update
121 -->
122 <module-def name="org.glassfish.javax.json">
123 <maven-resource group="org.glassfish" artifact="javax.json"/>
124 </module-def>
125
103126 <!-- already present in wildfly -->
104127 <module-def name="javax.ws.rs.api">
105 <maven-resource group="org.jboss.spec.javax.ws.rs" artifact="jboss-jaxrs-api_2.0_spec"/>
128 <maven-resource group="org.jboss.spec.javax.ws.rs" artifact="jboss-jaxrs-api_2.1_spec"/>
106129 </module-def>
107130
108131 <module-def name="org.jboss.resteasy.resteasy-atom-provider">
116139 <module-def name="org.jboss.resteasy.resteasy-crypto">
117140 <maven-resource group="org.jboss.resteasy" artifact="resteasy-crypto"/>
118141 </module-def>
119
142
120143 <module-def name="org.jboss.resteasy.resteasy-jackson-provider">
121144 <maven-resource group="org.jboss.resteasy" artifact="resteasy-jackson-provider"/>
122145 </module-def>
123146
124147 <module-def name="org.jboss.resteasy.resteasy-jackson2-provider">
125148 <maven-resource group="org.jboss.resteasy" artifact="resteasy-jackson2-provider"/>
149 </module-def>
150
151 <module-def name="com.github.fge.jackson-coreutils">
152 <maven-resource group="com.github.fge" artifact="jackson-coreutils"/>
153 </module-def>
154
155 <module-def name="com.github.fge.json-patch">
156 <maven-resource group="com.github.fge" artifact="json-patch"/>
126157 </module-def>
127158
128159 <module-def name="org.jboss.resteasy.resteasy-jaxb-provider">
138169 <maven-resource group="org.jboss.resteasy" artifact="resteasy-client"/>
139170 </module-def>
140171
141 <module-def name="org.jboss.resteasy.resteasy-jaxrs-api">
142 </module-def>
143
144 <module-def name="org.jboss.resteasy.resteasy-jaxrs-services">
145 <maven-resource group="org.jboss.resteasy" artifact="resteasy-jaxrs-services"/>
146 </module-def>
147
148172 <module-def name="org.jboss.resteasy.jose-jwt">
149173 <maven-resource group="org.jboss.resteasy" artifact="jose-jwt"/>
150174 </module-def>
156180 <module-def name="org.jboss.resteasy.resteasy-json-p-provider">
157181 <maven-resource group="org.jboss.resteasy" artifact="resteasy-json-p-provider"/>
158182 </module-def>
159
160 <module-def name="org.jboss.resteasy.resteasy-legacy">
161 <maven-resource group="org.jboss.resteasy" artifact="resteasy-legacy"/>
183
184 <module-def name="org.jboss.resteasy.resteasy-json-binding-provider">
185 <maven-resource group="org.jboss.resteasy" artifact="resteasy-json-binding-provider"/>
162186 </module-def>
163187
164188 <module-def name="org.jboss.resteasy.resteasy-multipart-provider">
168192 <module-def name="org.jboss.resteasy.resteasy-spring">
169193 <maven-resource-bundle group="org.jboss.resteasy" artifact="resteasy-spring" subdir="bundled/resteasy-spring-jar"/>
170194 </module-def>
171
195
172196 <module-def name="org.jboss.resteasy.resteasy-validator-provider-11">
173197 <maven-resource group="org.jboss.resteasy" artifact="resteasy-validator-provider-11"/>
174198 </module-def>
2929 <parent>
3030 <groupId>org.jboss.resteasy</groupId>
3131 <artifactId>resteasy-jaxrs-all</artifactId>
32 <version>3.1.4.Final</version>
32 <version>3.5.0.Final</version>
3333 </parent>
3434
3535 <artifactId>resteasy-jboss-modules</artifactId>
6262 <artifactId>jettison</artifactId>
6363 </dependency>
6464 <dependency>
65 <groupId>org.reactivestreams</groupId>
66 <artifactId>reactive-streams</artifactId>
67 </dependency>
68 <dependency>
6569 <groupId>com.fasterxml.jackson.core</groupId>
6670 <artifactId>jackson-core</artifactId>
6771 </dependency>
99103 </dependency>
100104 <dependency>
101105 <groupId>org.jboss.spec.javax.ws.rs</groupId>
102 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
106 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
103107 </dependency>
104108 <dependency>
105109 <groupId>org.jboss.resteasy</groupId>
108112 </dependency>
109113 <dependency>
110114 <groupId>org.jboss.resteasy</groupId>
111 <artifactId>resteasy-jaxrs-services</artifactId>
112 <version>${project.version}</version>
113 </dependency>
114 <dependency>
115 <groupId>org.jboss.resteasy</groupId>
116115 <artifactId>resteasy-client</artifactId>
117116 <version>${project.version}</version>
118117 </dependency>
119118 <dependency>
120119 <groupId>org.jboss.resteasy</groupId>
121 <artifactId>resteasy-legacy</artifactId>
122 <version>${project.version}</version>
123 </dependency>
124 <dependency>
125 <groupId>org.jboss.resteasy</groupId>
126120 <artifactId>resteasy-crypto</artifactId>
127121 <version>${project.version}</version>
128122 </dependency>
177171 <dependency>
178172 <groupId>org.jboss.resteasy</groupId>
179173 <artifactId>resteasy-json-p-provider</artifactId>
174 <version>${project.version}</version>
175 </dependency>
176
177 <dependency>
178 <groupId>org.jboss.resteasy</groupId>
179 <artifactId>resteasy-json-binding-provider</artifactId>
180180 <version>${project.version}</version>
181181 </dependency>
182182
219219 <dependency>
220220 <groupId>org.jboss.spec.javax.annotation</groupId>
221221 <artifactId>jboss-annotations-api_1.2_spec</artifactId>
222 </dependency>
223
224 <dependency>
225 <groupId>javax.json.bind</groupId>
226 <artifactId>javax.json.bind-api</artifactId>
227 </dependency>
228 <dependency>
229 <groupId>org.eclipse</groupId>
230 <artifactId>yasson</artifactId>
222231 </dependency>
223232
224233 </dependencies>
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2011, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23 <module xmlns="urn:jboss:module:1.3" name="com.github.fge.jackson-coreutils">
24 <properties>
25 <property name="jboss.api" value="private"/>
26 </properties>
27 <resources>
28 <!-- Insert resources here -->
29 </resources>
30
31 <dependencies>
32 <module name="com.fasterxml.jackson.core.jackson-annotations"/>
33 <module name="com.fasterxml.jackson.core.jackson-core"/>
34 <module name="com.fasterxml.jackson.core.jackson-databind"/>
35 <module name="com.google.guava"/>
36 </dependencies>
37 </module>
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2011, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23 <module xmlns="urn:jboss:module:1.3" name="com.github.fge.json-patch">
24 <properties>
25 <property name="jboss.api" value="private"/>
26 </properties>
27 <resources>
28 <!-- Insert resources here -->
29 </resources>
30
31 <dependencies>
32 <module name="com.github.fge.jackson-coreutils"/>
33 <module name="com.fasterxml.jackson.core.jackson-annotations"/>
34 <module name="com.fasterxml.jackson.core.jackson-core"/>
35 <module name="com.fasterxml.jackson.core.jackson-databind"/>
36 <module name="com.google.guava"/>
37 </dependencies>
38 </module>
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2010, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23
24 <module xmlns="urn:jboss:module:1.3" name="javax.json.bind.api">
25
26 <properties>
27 <property name="jboss.api" value="public"/>
28 </properties>
29
30 <resources>
31 <!-- Insert resources here -->
32 </resources>
33
34 <dependencies>
35 </dependencies>
36 </module>
3131 <module name="javax.xml.bind.api"/>
3232 <!-- needed because javax.ws.rs.core.Link uses JAXB annotations -->
3333 <module name="javax.api"/>
34 <module name="org.jboss.modules"/>
34 <module name="org.jboss.resteasy.resteasy-jaxrs" services="export"/>
3535 </dependencies>
3636 </module>
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2010, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23
24 <module xmlns="urn:jboss:module:1.3" name="org.eclipse.microprofile.restclient">
25
26 <resources>
27 <!-- Insert resources here -->
28 </resources>
29
30 <dependencies>
31 <module name="javax.api"/>
32 <module name="javax.annotation.api"/>
33 <module name="javax.enterprise.api"/>
34 <module name="javax.xml.bind.api"/>
35 <module name="javax.ws.rs.api"/>
36 </dependencies>
37 </module>
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2010, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23
24 <module xmlns="urn:jboss:module:1.3" name="org.eclipse.yasson">
25 <properties>
26 <property name="jboss.api" value="private"/>
27 </properties>
28
29 <resources>
30 <!-- Insert resources here -->
31 </resources>
32
33 <dependencies>
34 <module name="javax.json.bind.api"/>
35 <module name="javax.json.api"/>
36 <module name="javax.api"/>
37 <module name="javax.enterprise.api"/>
38 </dependencies>
39 </module>
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2013, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23
24 <module xmlns="urn:jboss:module:1.5" name="org.glassfish.javax.json">
25 <properties>
26 <property name="jboss.api" value="private"/>
27 </properties>
28
29 <dependencies>
30 </dependencies>
31 <resources>
32 <!-- Insert resources here -->
33 </resources>
34
35 </module>
4040 <module name="org.jboss.weld.core"/>
4141 <module name="org.jboss.weld.spi"/>
4242 <module name="org.jboss.logging"/>
43 <module name="org.eclipse.microprofile.restclient"/>
4344 </dependencies>
4445 </module>
3333 <module name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider"/>
3434 <module name="com.fasterxml.jackson.datatype.jackson-datatype-jdk8"/>
3535 <module name="com.fasterxml.jackson.datatype.jackson-datatype-jsr310"/>
36 <module name="com.github.fge.json-patch"/>
3637 <module name="javax.xml.bind.api"/>
3738 <module name="javax.api"/>
3839 <module name="javax.enterprise.api"/>
2727 </resources>
2828
2929 <dependencies>
30 <module name="org.jboss.resteasy.resteasy-jaxrs-services" services="import"/>
3130 <module name="javax.api"/>
3231 <module name="javax.annotation.api"/>
3332 <module name="javax.activation.api"/>
3534 <module name="javax.enterprise.api"/>
3635 <module name="javax.xml.bind.api"/>
3736 <module name="javax.ws.rs.api"/>
37 <module name="javax.json.bind.api"/>
3838 <module name="org.apache.commons.io"/>
3939 <module name="org.apache.commons.codec" />
4040 <module name="org.apache.httpcomponents"/>
4444 <module name="javax.servlet.api"/>
4545 <module name="org.jboss.resteasy.resteasy-validator-provider-11" optional="true" services="export" export="true"/>
4646 <module name="org.jboss.logging"/>
47 <module name="org.reactivestreams"/>
48 <module name="org.eclipse.microprofile.restclient"/>
4749 </dependencies>
4850 </module>
+0
-38
jboss-modules/src/main/resources/modules/org/jboss/resteasy/resteasy-jaxrs-api/main/module.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2010, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23
24 <module xmlns="urn:jboss:module:1.3" name="org.jboss.resteasy.resteasy-jaxrs-api">
25 <properties>
26 <property name="jboss.api" value="private"/>
27 </properties>
28
29 <resources>
30 <!-- Insert resources here -->
31 </resources>
32
33 <dependencies>
34 <module name="org.jboss.resteasy.resteasy-jaxrs-services" services="import"/>
35 <module name="org.jboss.resteasy.resteasy-jaxrs" services="import"/>
36 </dependencies>
37 </module>
+0
-36
jboss-modules/src/main/resources/modules/org/jboss/resteasy/resteasy-jaxrs-services/main/module.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2010, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23
24 <module xmlns="urn:jboss:module:1.3" name="org.jboss.resteasy.resteasy-jaxrs-services">
25 <properties>
26 <property name="jboss.api" value="private"/>
27 </properties>
28
29 <resources>
30 <!-- Insert resources here -->
31 </resources>
32
33 <dependencies>
34 </dependencies>
35 </module>
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2010, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23
24 <module xmlns="urn:jboss:module:1.3" name="org.jboss.resteasy.resteasy-json-binding-provider">
25
26 <properties>
27 <property name="jboss.api" value="private"/>
28 </properties>
29
30 <resources>
31 <!-- Insert resources here -->
32 </resources>
33
34 <dependencies>
35 <module name="org.glassfish.javax.json"/>
36 <module name="javax.json.bind.api" export="true"/>
37 <module name="org.eclipse.yasson"/>
38 <module name="javax.api"/>
39 <module name="javax.annotation.api"/>
40 <module name="javax.json.api"/>
41 <module name="javax.enterprise.api"/>
42 <module name="javax.ws.rs.api"/>
43 <module name="javax.xml.bind.api"/>
44 <module name="org.jboss.resteasy.resteasy-jaxrs"/>
45 <module name="org.jboss.logging"/>
46 </dependencies>
47 </module>
+0
-53
jboss-modules/src/main/resources/modules/org/jboss/resteasy/resteasy-legacy/main/module.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2010, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23
24 <module xmlns="urn:jboss:module:1.3" name="org.jboss.resteasy.resteasy-legacy">
25 <properties>
26 <property name="jboss.api" value="deprecated"/>
27 </properties>
28
29 <resources>
30 <!-- Insert resources here -->
31 </resources>
32
33 <dependencies>
34 <module name="javax.ws.rs.api"/>
35 <module name="org.jboss.resteasy.resteasy-jaxrs" services="import"/>
36 <module name="javax.api"/>
37 <module name="javax.annotation.api"/>
38 <module name="javax.activation.api"/>
39 <module name="javax.validation.api"/>
40 <module name="javax.enterprise.api"/>
41 <module name="javax.xml.bind.api"/>
42 <module name="org.apache.commons.io"/>
43 <module name="org.apache.commons.codec" />
44 <module name="org.apache.httpcomponents"/>
45 <module name="org.apache.log4j"/>
46 <module name="org.hibernate.validator" optional="true" services="import"/>
47 <module name="org.slf4j" />
48 <module name="javax.servlet.api"/>
49 <module name="org.jboss.resteasy.resteasy-validator-provider-11" optional="true" services="export" export="true"/>
50 <module name="org.jboss.logging"/>
51 </dependencies>
52 </module>
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--
3 ~ JBoss, Home of Professional Open Source.
4 ~ Copyright 2010, Red Hat, Inc., and individual contributors
5 ~ as indicated by the @author tags. See the copyright.txt file in the
6 ~ distribution for a full listing of individual contributors.
7 ~
8 ~ This is free software; you can redistribute it and/or modify it
9 ~ under the terms of the GNU Lesser General Public License as
10 ~ published by the Free Software Foundation; either version 2.1 of
11 ~ the License, or (at your option) any later version.
12 ~
13 ~ This software is distributed in the hope that it will be useful,
14 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ~ Lesser General Public License for more details.
17 ~
18 ~ You should have received a copy of the GNU Lesser General Public
19 ~ License along with this software; if not, write to the Free
20 ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
22 -->
23
24 <module xmlns="urn:jboss:module:1.3" name="org.reactivestreams">
25
26 <properties>
27 <property name="jboss.api" value="private"/>
28 </properties>
29
30 <resources>
31 <!-- Insert resources here -->
32 </resources>
33
34 <dependencies>
35 <!-- Insert dependencies here -->
36 </dependencies>
37 </module>
22 <parent>
33 <groupId>org.jboss</groupId>
44 <artifactId>jboss-parent</artifactId>
5 <version>22</version>
5 <version>25</version>
66 <relativePath/>
77 </parent>
88
1313
1414 <groupId>org.jboss.resteasy</groupId>
1515 <artifactId>resteasy-jaxrs-all</artifactId>
16 <version>3.1.4.Final</version>
16 <version>3.5.0.Final</version>
1717 <packaging>pom</packaging>
1818
1919 <properties>
2929 <!-- maven-javadoc-plugin -->
3030 <maven.javadoc.skip>true</maven.javadoc.skip>
3131 <!-- maven-surefire-plugin -->
32 <surefire.system.args>${modular.jdk.props}</surefire.system.args>
32 <surefire.system.args>${modular.jdk.args} ${modular.jdk.props}</surefire.system.args>
3333 <!-- Plugins versions -->
3434 <version.org.jacoco.plugin>0.7.9</version.org.jacoco.plugin>
3535 </properties>
9797 <modules>
9898 <module>tjws</module>
9999 <module>resteasy-jaxrs</module>
100 <module>resteasy-jaxrs-services</module>
100 <module>resteasy-jaxrs-testsuite</module>
101101 <module>resteasy-client</module>
102 <module>resteasy-legacy</module>
103102 <module>providers</module>
104103 <module>resteasy-bom</module>
105104 <module>resteasy-cache</module>
113112 <module>resteasy-jsapi</module>
114113 <module>resteasy-cdi</module>
115114 <module>resteasy-servlet-initializer</module>
115 <module>resteasy-rxjava</module>
116 <module>resteasy-rxjava2</module>
116117 <module>server-adapters</module>
117118 <module>jboss-modules</module>
118119 <module>resteasy-wadl</module>
149150 <modules>
150151 <module>tjws</module>
151152 <module>resteasy-jaxrs</module>
153 <module>resteasy-jaxrs-testsuite</module>
152154 <module>resteasy-client</module>
153155 <module>providers</module>
154156 <module>resteasy-bom</module>
163165 <module>resteasy-jsapi</module>
164166 <module>resteasy-cdi</module>
165167 <module>resteasy-servlet-initializer</module>
168 <module>resteasy-rxjava</module>
169 <module>resteasy-rxjava2</module>
166170 <module>server-adapters</module>
167171 <module>jboss-modules</module>
168172 <module>resteasy-wadl</module>
190194 </activation>
191195 <properties>
192196 <!--<maven.compiler.verbose>true</maven.compiler.verbose>-->
193 <modular.jdk.args>--add-modules java.se.ee</modular.jdk.args>
197 <modular.jdk.args>--add-modules=java.se</modular.jdk.args>
194198 <modular.jdk.props>-Dsun.util.logging.disableCallerCheck=true
195199 -Dsun.reflect.debugModuleAccessChecks=true
196 --add-opens=java.base/java.lang=ALL-UNNAMED
197 --add-opens=java.base/java.nio=ALL-UNNAMED
198 --add-opens=java.base/sun.nio.ch=ALL-UNNAMED
199 --add-opens=java.base/java.io=ALL-UNNAMED
200 --add-opens=java.base/java.util=ALL-UNNAMED
201 --add-opens=java.base/java.lang.reflect=ALL-UNNAMED
202 --add-opens=java.base/java.util.concurrent=ALL-UNNAMED
203 --add-opens=java.base/sun.util.calendar=ALL-UNNAMED
204 --add-opens=java.base/java.security=ALL-UNNAMED
205 --add-opens=java.base/sun.reflect.annotation=ALL-UNNAMED
206 --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED
207 --add-exports=java.xml/com.sun.org.apache.xerces.internal.jaxp=ALL-UNNAMED
208 --add-exports=java.xml/com.sun.org.apache.xalan.internal.xsltc.trax=ALL-UNNAMED
209 --add-exports=java.xml/com.sun.org.apache.xerces.internal.jaxp.datatype=ALL-UNNAMED
210 --add-exports=java.xml/com.sun.xml.internal.stream=ALL-UNNAMED
211200 </modular.jdk.props>
212201 </properties>
213202 <build>
214203 <plugins>
215204 <plugin>
216 <artifactId>maven-compiler-plugin</artifactId>
217 <configuration>
218 <!-- fork is needed so compiler args can be used -->
219 <fork>true</fork>
220 <compilerArgs>
221 <arg>-J--add-modules</arg>
222 <arg>-Jjava.xml.ws.annotation</arg>
223 </compilerArgs>
224 </configuration>
225 </plugin>
226 <plugin>
227205 <artifactId>maven-javadoc-plugin</artifactId>
228206 <configuration>
229 <additionalparam>--add-modules java.se.ee</additionalparam>
207 <additionalparam>--add-modules=ALL-SYSTEM</additionalparam>
230208 </configuration>
231209 </plugin>
232210 </plugins>
254232 <build>
255233 <pluginManagement>
256234 <plugins>
257 <plugin>
258 <groupId>org.apache.maven.plugins</groupId>
259 <artifactId>maven-compiler-plugin</artifactId>
260 <configuration>
261 <compilerArgument>
262 -AgeneratedTranslationFilesPath=${project.basedir}/target/generated-translation-files
263 </compilerArgument>
264 </configuration>
265 </plugin>
266235 <plugin>
267236 <groupId>org.apache.maven.plugins</groupId>
268237 <artifactId>maven-surefire-plugin</artifactId>
282251 <quiet>false</quiet>
283252 <aggregate>true</aggregate>
284253 <excludePackageNames>
285 com.restfully.*:org.jboss.resteasy.examples.*:se.unlogic.*:org.jboss.resteasy.tests.*
254 com.restfully.*:org.jboss.resteasy.examples.*:se.unlogic.*:org.jboss.resteasy.tests.*:Acme.*:*.tjws.*
286255 </excludePackageNames>
287256 </configuration>
288 <executions>
289 <execution>
290 <phase>package</phase>
291 <goals>
292 <goal>jar</goal>
293 </goals>
294 </execution>
295 </executions>
296257 </plugin>
297258 <plugin>
298259 <groupId>org.eclipse.jetty</groupId>
309270 <plugins>
310271 <plugin>
311272 <groupId>com.atlassian.maven.plugins</groupId>
312 <artifactId>maven-clover2-plugin</artifactId>
273 <artifactId>clover-maven-plugin</artifactId>
313274 </plugin>
314275 <plugin>
315276 <artifactId>maven-clean-plugin</artifactId>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-profiling-tests</artifactId>
00 package org.jboss.resteasy.test.profiling;
11
2 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.core.executors.InMemoryClientExecutor;
34 import org.junit.Test;
45
56 import javax.ws.rs.Consumes;
67 import javax.ws.rs.POST;
78 import javax.ws.rs.Path;
89 import javax.ws.rs.Produces;
9 import javax.ws.rs.client.Client;
10 import javax.ws.rs.client.Entity;
11 import javax.ws.rs.client.Invocation.Builder;
1210
1311 /**
1412 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7068 @Test
7169 public void testJson() throws Exception
7270 {
73 InMemoryClientEngine engine = new InMemoryClientEngine();
74 engine.getDispatcher().getRegistry().addPerRequestResource(JsonTest.class);
75 Client client = new ResteasyClientBuilder().httpEngine(engine).build();
71 InMemoryClientExecutor executor = new InMemoryClientExecutor();
72 executor.getDispatcher().getRegistry().addPerRequestResource(JsonTest.class);
73
7674 final int ITERATIONS = 1000;
7775
7876 long start = System.currentTimeMillis();
7977 for (int i = 0; i < ITERATIONS; i++)
8078 {
81 Builder request = client.target("/").request();
82 request.post(Entity.entity(new Customer("bill", "burke"), "application/json"), String.class);
79 ClientRequest request = new ClientRequest("/", executor);
80 request.body("application/json", new Customer("bill", "burke"));
81 String response = request.postTarget(String.class);
8382 }
8483 long end = System.currentTimeMillis() - start;
8584 System.out.println(ITERATIONS + " iterations took " + end + "ms");
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>abdera-atom-provider</artifactId>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-fastinfoset-provider</artifactId>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-jackson-provider</artifactId>
1616 <groupId>org.jboss.resteasy</groupId>
1717 <artifactId>resteasy-jaxrs</artifactId>
1818 <version>${project.version}</version>
19 <scope>provided</scope>
1920 </dependency>
2021 <dependency>
2122 <groupId>org.jboss.resteasy</groupId>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-jackson2-provider</artifactId>
5656 <artifactId>jboss-servlet-api_3.1_spec</artifactId>
5757 </dependency>
5858 <dependency>
59 <groupId>com.github.fge</groupId>
60 <artifactId>json-patch</artifactId>
61 </dependency>
62 <dependency>
5963 <groupId>org.jboss.resteasy</groupId>
6064 <artifactId>tjws</artifactId>
6165 <version>${project.version}</version>
0 package org.jboss.resteasy.plugins.providers.jackson;
1
2 import java.io.ByteArrayInputStream;
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5
6 import javax.annotation.Priority;
7 import javax.ws.rs.ProcessingException;
8 import javax.ws.rs.container.ContainerRequestContext;
9 import javax.ws.rs.container.ContainerRequestFilter;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.ext.MessageBodyWriter;
12 import javax.ws.rs.ext.Provider;
13
14 import org.jboss.resteasy.core.ResourceInvoker;
15 import org.jboss.resteasy.core.ResourceMethodInvoker;
16 import org.jboss.resteasy.specimpl.MultivaluedTreeMap;
17 import org.jboss.resteasy.spi.HttpRequest;
18 import org.jboss.resteasy.spi.HttpResponse;
19 import org.jboss.resteasy.spi.Registry;
20 import org.jboss.resteasy.spi.ResteasyProviderFactory;
21
22 import com.fasterxml.jackson.databind.JsonNode;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.github.fge.jsonpatch.JsonPatch;
25 import com.github.fge.jsonpatch.JsonPatchException;
26 /*
27 * @author <a href="mailto:ema@redhat.com">Jim Ma</a>
28 */
29 @Provider
30 @Priority(Integer.MAX_VALUE)
31 public class PatchMethodFilter implements ContainerRequestFilter
32 {
33 private static final MediaType APPLICATION_JSON_PATCH_JSON_TYPE = new MediaType("application", "json-patch+json");
34
35 @Override
36 public void filter(ContainerRequestContext requestContext) throws IOException
37 {
38 //Strict the filter is only executed for patch method and media type is APPLICATION_JSON_PATCH_JSON_TYPE
39 if (requestContext.getMethod().equals("PATCH")
40 && APPLICATION_JSON_PATCH_JSON_TYPE.equals(requestContext.getMediaType()))
41 {
42
43 HttpRequest request = ResteasyProviderFactory.getContextData(HttpRequest.class);
44 HttpResponse response = ResteasyProviderFactory.getContextData(HttpResponse.class);
45 request.setHttpMethod("GET");
46 Registry methodRegistry = ResteasyProviderFactory.getContextData(Registry.class);
47 ResourceInvoker resourceInovker = methodRegistry.getResourceInvoker(request);
48 if (resourceInovker == null)
49 {
50 throw new ProcessingException("Get method not found and patch method failed");
51 }
52 ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) resourceInovker;
53 Object object = methodInvoker.invokeDryRun(request, response);
54
55 ByteArrayOutputStream tmpOutputStream = new ByteArrayOutputStream();
56 MessageBodyWriter msgBodyWriter = ResteasyProviderFactory.getInstance().getMessageBodyWriter(
57 object.getClass(), object.getClass(), methodInvoker.getMethodAnnotations(),
58 MediaType.APPLICATION_JSON_TYPE);
59 msgBodyWriter.writeTo(object, object.getClass(), object.getClass(), methodInvoker.getMethodAnnotations(),
60 MediaType.APPLICATION_JSON_TYPE, new MultivaluedTreeMap<String, Object>(), tmpOutputStream);
61 ObjectMapper mapper = new ObjectMapper();
62 JsonNode targetJson = mapper.readValue(tmpOutputStream.toByteArray(), JsonNode.class);
63 JsonPatch patch = JsonPatch.fromJson(mapper.readValue(request.getInputStream(), JsonNode.class));
64
65 JsonNode result = null;
66 try
67 {
68 result = patch.apply(targetJson);
69 }
70 catch (JsonPatchException e)
71 {
72 throw new ProcessingException(e);
73 }
74 ByteArrayOutputStream targetOutputStream = new ByteArrayOutputStream();
75 mapper.writeValue(targetOutputStream, result);
76 request.setInputStream(new ByteArrayInputStream(targetOutputStream.toByteArray()));
77
78 request.setHttpMethod("PATCH");
79
80 }
81
82 }
83
84 }
00 org.jboss.resteasy.plugins.providers.jackson.ResteasyJackson2Provider
11 org.jboss.resteasy.plugins.providers.jackson.UnrecognizedPropertyExceptionHandler
2 org.jboss.resteasy.plugins.providers.jackson.PatchMethodFilter
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-jaxb-provider</artifactId>
2424 <scope>provided</scope>
2525 </dependency>
2626 <!-- javax.xml.bind.JAXBElement provider is required by spec -->
27 <dependency>
28 <groupId>org.jboss.spec.javax.xml.bind</groupId>
29 <artifactId>jboss-jaxb-api_2.3_spec</artifactId>
30 </dependency>
31 <dependency>
32 <groupId>com.sun.xml.bind</groupId>
33 <artifactId>jaxb-core</artifactId>
34 </dependency>
2735 <dependency>
2836 <groupId>com.sun.xml.bind</groupId>
2937 <artifactId>jaxb-impl</artifactId>
5858 break;
5959 }
6060 }
61 if (found == false) return false;
61 if (!found) return false;
6262 }
6363 return true;
6464 }
9898 return packageName;
9999 }
100100
101 public static Class<?> findDefaultObjectFactoryClass(Class<?> type) throws PrivilegedActionException
101 public static Class<?> findDefaultObjectFactoryClass(Class<?> type)
102102 {
103103 XmlType typeAnnotation = type.getAnnotation(XmlType.class);
104104 if (typeAnnotation == null) return null;
105105 if (!typeAnnotation.factoryClass().equals(XmlType.DEFAULT.class)) return null;
106 StringBuilder b = new StringBuilder(getPackageName(type));
106 final StringBuilder b = new StringBuilder(getPackageName(type));
107107 b.append(OBJECT_FACTORY_NAME);
108 Class<?> factoryClass = null;
108 Class<?> factoryClass;
109109 try
110110 {
111111 if (System.getSecurityManager() == null)
114114 }
115115 else
116116 {
117 final String smB = b.toString();
118117 factoryClass = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>()
119118 {
120119 @Override
121 public Class<?> run() throws Exception
120 public Class<?> run() throws ClassNotFoundException
122121 {
123 return Thread.currentThread().getContextClassLoader().loadClass(smB);
122 return Thread.currentThread().getContextClassLoader().loadClass(b.toString());
124123 }
125124 });
126125 }
127126 }
128 catch (PrivilegedActionException pae) {
129 if (pae.getException() instanceof ClassNotFoundException) {
130 return null;
131 } else {
132 throw pae;
133 }
134 }
135 catch (ClassNotFoundException e)
127 catch (PrivilegedActionException | ClassNotFoundException e)
136128 {
137129 return null;
138130 }
172164 if (type == null)
173165 continue;
174166 classes1.add(type);
175 try {
176 Class<?> factory = findDefaultObjectFactoryClass(type);
177 if (factory != null)
178 classes1.add(factory);
179 } catch (PrivilegedActionException pae)
180 {
181 throw new JAXBException(pae);
182 }
183 }
167 Class<?> factory = findDefaultObjectFactoryClass(type);
168 if (factory != null)
169 classes1.add(factory);
170 }
184171 }
185172 Class<?>[] classArray = classes1.toArray(new Class[classes1.size()]);
186173 return createContextObject(parameterAnnotations, classArray);
00 package org.jboss.resteasy.plugins.providers.jaxb;
11
2 import org.jboss.resteasy.core.interception.jaxrs.DecoratorMatcher;
2 import org.jboss.resteasy.core.interception.DecoratorMatcher;
33 import org.jboss.resteasy.plugins.providers.AbstractEntityProvider;
44 import org.jboss.resteasy.plugins.providers.jaxb.i18n.*;
55 import org.jboss.resteasy.spi.ResteasyConfiguration;
2222 import java.io.InputStream;
2323 import java.lang.reflect.Constructor;
2424 import java.security.AccessController;
25 import java.security.PrivilegedAction;
2526 import java.security.PrivilegedActionException;
2627 import java.security.PrivilegedExceptionAction;
2728 import java.util.Collections;
4647 try
4748 {
4849 // check to see if NamespacePrefixMapper is in classpath
49 Class mapper = null;
50 final Class[] namespace = new Class[1];
51 final Class[] mapper = new Class[1];
5052
5153 if (System.getSecurityManager() == null)
5254 {
53 Class namespace = JAXBContextWrapper.class.getClassLoader().loadClass("com.sun.xml.bind.marshaller.NamespacePrefixMapper");
54 mapper = JAXBContextWrapper.class.getClassLoader().loadClass("org.jboss.resteasy.plugins.providers.jaxb.XmlNamespacePrefixMapper");
55 namespace[0] = JAXBContextWrapper.class.getClassLoader().loadClass("com.sun.xml.bind.marshaller.NamespacePrefixMapper");
56 mapper[0] = JAXBContextWrapper.class.getClassLoader().loadClass("org.jboss.resteasy.plugins.providers.jaxb.XmlNamespacePrefixMapper");
5557 }
5658 else
5759 {
58 mapper = AccessController.doPrivileged(new PrivilegedExceptionAction<Class>() {
59 @Override public Class run() throws Exception {
60 Class namespace = JAXBContextWrapper.class.getClassLoader().loadClass("com.sun.xml.bind.marshaller.NamespacePrefixMapper");
61 return JAXBContextWrapper.class.getClassLoader().loadClass("org.jboss.resteasy.plugins.providers.jaxb.XmlNamespacePrefixMapper");
62
60 AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
61 @Override public Void run() throws Exception {
62 namespace[0] = JAXBContextWrapper.class.getClassLoader().loadClass("com.sun.xml.bind.marshaller.NamespacePrefixMapper");
63 mapper[0] = JAXBContextWrapper.class.getClassLoader().loadClass("org.jboss.resteasy.plugins.providers.jaxb.XmlNamespacePrefixMapper");
64
65 return null;
6366 }
6467 });
6568 }
6669
67 mapperConstructor = mapper.getConstructors()[0];
68 }
69 catch (ClassNotFoundException e)
70 {
71
72 }
73 catch (PrivilegedActionException pae) {
74
75 }
76
77 }
78
79 private JAXBContext wrappedContext;
70 mapperConstructor = mapper[0].getConstructors()[0];
71 }
72 catch (ClassNotFoundException | PrivilegedActionException e)
73 {
74
75 }
76
77 }
78
79 private final JAXBContext wrappedContext;
80 private final ThreadLocal<Unmarshaller> unmarshaller = new ThreadLocal<Unmarshaller>();
8081
8182 /**
8283 * An optional namespace mapper that is used to apply prefixes to elements with a given namespace.
102103 * @param config
103104 * @throws JAXBException
104105 */
105 public JAXBContextWrapper(final Class<?>[] classes, final Map<String, Object> properties, JAXBConfig config)
106 throws JAXBException
106 public JAXBContextWrapper(final Class<?>[] classes, final Map<String, Object> properties, JAXBConfig config) throws JAXBException
107107 {
108108 processConfig(config);
109109 try
119119 @Override
120120 public JAXBContext run() throws JAXBException
121121 {
122 return JAXBContext.newInstance(classes, properties);
122 return JAXBContext.newInstance(classes, properties);
123123 }
124124 });
125125 }
137137 * @param config
138138 * @throws JAXBException
139139 */
140 public JAXBContextWrapper(String contextPath, JAXBConfig config) throws JAXBException
140 public JAXBContextWrapper(final String contextPath, JAXBConfig config) throws JAXBException
141141 {
142142 processConfig(config);
143 wrappedContext = JAXBContext.newInstance(contextPath);
143 try
144 {
145 if (System.getSecurityManager() == null)
146 {
147 wrappedContext = JAXBContext.newInstance(contextPath);
148 }
149 else
150 {
151 wrappedContext = AccessController.doPrivileged(new PrivilegedExceptionAction<JAXBContext>()
152 {
153 @Override
154 public JAXBContext run() throws JAXBException
155 {
156 return JAXBContext.newInstance(contextPath);
157 }
158 });
159 }
160 }
161 catch (PrivilegedActionException paex)
162 {
163 throw new JAXBException(paex.getMessage());
164 }
144165 }
145166
146167 /**
275296 */
276297 public Unmarshaller createUnmarshaller() throws JAXBException
277298 {
278 return wrappedContext.createUnmarshaller();
299 Unmarshaller u = unmarshaller.get();
300 if (u == null)
301 {
302 u = wrappedContext.createUnmarshaller();
303 unmarshaller.set(u);
304 }
305 return u;
279306 }
280307
281308 /**
8989 try
9090 {
9191 LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName());
92 ContextResolver<JAXBContextFinder> resolver = providers.getContextResolver(JAXBContextFinder.class, mediaType);
93 JAXBContextFinder finder = resolver.getContext(type);
94 if (finder == null)
95 {
96 if (true) throw new JAXBUnmarshalException(Messages.MESSAGES.couldNotFindJAXBContextFinder(mediaType));
97 else throw new JAXBMarshalException(Messages.MESSAGES.couldNotFindJAXBContextFinder(mediaType));
98 }
99 JAXBContext jaxb = finder.findCacheXmlTypeContext(mediaType, annotations, type);
92 JAXBContext jaxb = getJAXBContext(type, mediaType);
93
94 if (jaxb == null) {
95 jaxb = getJAXBContextFinder(type, annotations, mediaType);
96 }
97
10098 Unmarshaller unmarshaller = jaxb.createUnmarshaller();
10199 unmarshaller = decorateUnmarshaller(type, annotations, mediaType, unmarshaller);
102
100
103101 Object obj = null;
104102 if (needsSecurity())
105103 {
127125 }
128126 else
129127 {
130 obj = unmarshaller.unmarshal(new StreamSource(entityStream));
128 obj = unmarshaller.unmarshal(new StreamSource(entityStream));
131129 }
132130 }
133131 if (obj instanceof JAXBElement)
140138 {
141139 return obj;
142140 }
141 }
142 catch (JAXBException e)
143 {
144 throw new JAXBUnmarshalException(e);
145 }
146 }
147
148 /**
149 * Check for a user provided JAXBContext implementation. It takes priority over our builtin one.
150 * @param type
151 * @param mediaType
152 * @return
153 * @throws IOException
154 */
155 private javax.xml.bind.JAXBContext getJAXBContext(Class<Object> type, MediaType mediaType) throws IOException {
156 LogMessages.LOGGER.debugf("Provider : %s, Method : getJAXBContext", getClass().getName());
157
158 ContextResolver<javax.xml.bind.JAXBContext> resolver = providers.getContextResolver(
159 javax.xml.bind.JAXBContext.class, mediaType);
160
161 javax.xml.bind.JAXBContext finder = null;
162 if (resolver != null)
163 {
164 finder = resolver.getContext(type);
165 if (finder == null)
166 {
167 throw new JAXBUnmarshalException(Messages.MESSAGES.couldNotFindUsersJAXBContext(mediaType));
168 }
169 }
170
171 return finder;
172 }
173
174 /**
175 * Check for the resteasy builtin JAXBContext implementation.
176 * @param type
177 * @param annotations
178 * @param mediaType
179 * @return
180 * @throws IOException
181 */
182 private JAXBContext getJAXBContextFinder(Class<Object> type, Annotation[] annotations, MediaType mediaType) throws IOException
183 {
184 try
185 {
186 LogMessages.LOGGER.debugf("Provider : %s, Method : getJAXBContextFinder", getClass().getName());
187 ContextResolver<JAXBContextFinder> resolver = providers.getContextResolver(JAXBContextFinder.class, mediaType);
188 JAXBContextFinder finder = resolver.getContext(type);
189 if (finder == null)
190 {
191 throw new JAXBUnmarshalException(Messages.MESSAGES.couldNotFindJAXBContextFinder(mediaType));
192 }
193 JAXBContext jaxb = finder.findCacheXmlTypeContext(mediaType, annotations, type);
194 return jaxb;
143195 }
144196 catch (JAXBException e)
145197 {
164216 * in the same package as the type we're trying to marshall. This method simply locates this class and
165217 * instantiates it if found.
166218 *
167 * @param t
168219 * @param type
169220 * @return
170221 */
175226 Class<?> factoryClass = AbstractJAXBContextFinder.findDefaultObjectFactoryClass(type);
176227 if (factoryClass != null && factoryClass.isAnnotationPresent(XmlRegistry.class))
177228 {
178 Object factory = factoryClass.newInstance();
179 return factory;
229 return factoryClass.newInstance();
180230 }
181231 else
182232 {
183233 throw new JAXBMarshalException(Messages.MESSAGES.validXmlRegistryCouldNotBeLocated());
184234 }
185235 }
186 catch (InstantiationException e)
236 catch (InstantiationException | IllegalAccessException e)
187237 {
188238 throw new JAXBMarshalException(e);
189 }
190 catch (IllegalAccessException e)
191 {
192 throw new JAXBMarshalException(e);
193 }
194 catch (PrivilegedActionException pae)
195 {
196 throw new JAXBMarshalException(pae);
197239 }
198240
199241 }
211253 try
212254 {
213255 final Object factory = findObjectFactory(type);
214 Method[] method = new Method[0];
256 Method[] method;
215257 if (System.getSecurityManager() == null)
216258 {
217259 method = factory.getClass().getDeclaredMethods();
228270 });
229271 }
230272
231 for (int i = 0; i < method.length; i++)
232 {
233 Method current = method[i];
273 for (Method current : method)
274 {
234275 if (current.getParameterTypes().length == 1 && current.getParameterTypes()[0].equals(type)
235276 && current.getName().startsWith("create"))
236277 {
237 Object result = current.invoke(factory, new Object[]
238 {t});
278 Object result = current.invoke(factory, t);
239279 return JAXBElement.class.cast(result);
240280 }
241281 }
242282 throw new JAXBMarshalException(Messages.MESSAGES.createMethodNotFound(type));
243283 }
244 catch (IllegalArgumentException e)
284 catch (IllegalArgumentException | IllegalAccessException | PrivilegedActionException e)
245285 {
246286 throw new JAXBMarshalException(e);
247287 }
248 catch (IllegalAccessException e)
249 {
250 throw new JAXBMarshalException(e);
251 }
252288 catch (InvocationTargetException e)
253289 {
254290 throw new JAXBMarshalException(e.getCause());
255291 }
256 catch (PrivilegedActionException pae)
257 {
258 throw new JAXBMarshalException(pae);
259 }
260292 }
261293 }
11
22 import org.jboss.resteasy.annotations.DecorateTypes;
33 import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
4 import org.jboss.resteasy.spi.DecoratorProcessor;
4 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
55
66 import javax.ws.rs.core.MediaType;
77 import javax.xml.bind.Marshaller;
66 import java.security.AccessController;
77 import java.security.PrivilegedActionException;
88 import java.security.PrivilegedExceptionAction;
9 import java.util.Collections;
10 import java.util.Map;
11 import java.util.WeakHashMap;
912
1013 import javax.xml.XMLConstants;
1114 import javax.xml.bind.JAXBElement;
2023 import javax.xml.parsers.SAXParser;
2124 import javax.xml.parsers.SAXParserFactory;
2225 import javax.xml.stream.XMLEventReader;
23 import javax.xml.stream.XMLInputFactory;
2426 import javax.xml.stream.XMLStreamReader;
2527 import javax.xml.transform.Source;
2628 import javax.xml.transform.sax.SAXSource;
4244 * Created Feb 1, 2012
4345 */
4446 public class SecureUnmarshaller implements Unmarshaller {
47
48 private static class SAXParserProvider
49 {
50 private static final Map<ClassLoader, SAXParserProvider> saxParserProviders = Collections.synchronizedMap(new WeakHashMap<>());
51 private final SAXParserFactory[] factories = new SAXParserFactory[8];
52
53 private SAXParserProvider()
54 {
55 //NOOP
56 }
57
58 public static SAXParserProvider getInstance()
59 {
60 ClassLoader tccl = Thread.currentThread().getContextClassLoader();
61 SAXParserProvider spp;
62 spp = saxParserProviders.get(tccl);
63 if (spp == null)
64 {
65 spp = new SAXParserProvider();
66 SAXParserProvider s = saxParserProviders.putIfAbsent(tccl, spp);
67 if (s != null) spp = s;
68 }
69 return spp;
70 }
71
72 public SAXParser getParser(boolean disableExternalEntities, boolean enableSecureProcessingFeature, boolean disableDTDs) throws ParserConfigurationException, SAXException
73 {
74 int index = (disableExternalEntities ? 1 : 0) | (enableSecureProcessingFeature ? 1 << 1 : 0) | (disableDTDs ? 1 << 2 : 0);
75 SAXParserFactory f = factories[index];
76 if (f == null)
77 {
78 f = SAXParserFactory.newInstance();
79 configureParserFactory(f, disableExternalEntities, enableSecureProcessingFeature, disableDTDs);
80 factories[index] = f;
81 }
82 SAXParser sp = f.newSAXParser();
83 configParser(sp, disableExternalEntities);
84 return sp;
85 }
86 }
4587
4688 private Unmarshaller delegate;
4789 boolean disableExternalEntities;
157199 {
158200 try
159201 {
160 SAXParserFactory spf = SAXParserFactory.newInstance();
161 configureParserFactory(spf);
162 SAXParser sp = spf.newSAXParser();
163 configParser(sp);
202 SAXParser sp = SAXParserProvider.getInstance().getParser(disableExternalEntities, enableSecureProcessingFeature, disableDTDs);
164203 XMLReader xmlReader = sp.getXMLReader();
165204 final SAXSource saxSource = new SAXSource(xmlReader, source);
166205 if (System.getSecurityManager() == null) {
201240 {
202241 try
203242 {
204 SAXParserFactory spf = SAXParserFactory.newInstance();
205 configureParserFactory(spf);
206 SAXParser sp = spf.newSAXParser();
207 configParser(sp);
243 SAXParser sp = SAXParserProvider.getInstance().getParser(disableExternalEntities, enableSecureProcessingFeature, disableDTDs);
208244 XMLReader xmlReader = sp.getXMLReader();
209245 ((SAXSource) source).setXMLReader(xmlReader);
210246 return delegate.unmarshal(source);
222258 throw new UnsupportedOperationException(Messages.MESSAGES.unexpectedUse("Source, Class<T>"));
223259 }
224260
225 private void configParser(SAXParser sp) {
261 private static void configParser(SAXParser sp, boolean disableExternalEntities) {
226262 try {
227263 if (!disableExternalEntities)
228264 sp.setProperty("http://javax.xml.XMLConstants/property/accessExternalDTD", "all");
251287 {
252288 try
253289 {
254 SAXParserFactory spf = SAXParserFactory.newInstance();
255 configureParserFactory(spf);
256 SAXParser sp = spf.newSAXParser();
257 configParser(sp);
290 SAXParser sp = SAXParserProvider.getInstance().getParser(disableExternalEntities, enableSecureProcessingFeature, disableDTDs);
258291 XMLReader xmlReader = sp.getXMLReader();
259292 ((SAXSource) source).setXMLReader(xmlReader);
260293 return delegate.unmarshal(source, declaredType);
289322 {
290323 this.delegate = delegate;
291324 }
292
293 protected void configureParserFactory(SAXParserFactory factory) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException
325
326 protected static void configureParserFactory(SAXParserFactory factory, boolean disableExternalEntities, boolean enableSecureProcessingFeature, boolean disableDTDs) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException
294327 {
295328 factory.setFeature("http://xml.org/sax/features/validation", false);
296329 factory.setFeature("http://xml.org/sax/features/namespaces", true);
11
22 import org.jboss.resteasy.annotations.DecorateTypes;
33 import org.jboss.resteasy.annotations.providers.jaxb.Stylesheet;
4 import org.jboss.resteasy.spi.DecoratorProcessor;
4 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
55 import org.jboss.resteasy.util.StringContextReplacement;
66
77 import javax.ws.rs.core.MediaType;
11
22 import org.jboss.resteasy.annotations.DecorateTypes;
33 import org.jboss.resteasy.annotations.providers.jaxb.XmlHeader;
4 import org.jboss.resteasy.spi.DecoratorProcessor;
4 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
55 import org.jboss.resteasy.util.StringContextReplacement;
66
77 import javax.ws.rs.core.MediaType;
5353
5454 @Message(id = BASE + 55, value = "A valid XmlRegistry could not be located.")
5555 String validXmlRegistryCouldNotBeLocated();
56
57 @Message(id = BASE + 60, value = "Could not find user's JAXBContext implementation for media type: %s")
58 String couldNotFindUsersJAXBContext(MediaType mediaType);
5659 }
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-jettison-provider</artifactId>
0 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
2 <modelVersion>4.0.0</modelVersion>
3 <parent>
4 <groupId>org.jboss.resteasy</groupId>
5 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.5.0.Final</version>
7 <relativePath>../../pom.xml</relativePath>
8 </parent>
9 <artifactId>resteasy-json-binding-provider</artifactId>
10 <packaging>jar</packaging>
11 <name>RESTEasy JSON-Binding Provider</name>
12 <description/>
13
14 <dependencies>
15 <dependency>
16 <groupId>org.jboss.resteasy</groupId>
17 <artifactId>resteasy-jaxrs</artifactId>
18 <version>${project.version}</version>
19 <scope>provided</scope>
20 </dependency>
21 <dependency>
22 <groupId>org.jboss.resteasy</groupId>
23 <artifactId>resteasy-client</artifactId>
24 <version>${project.version}</version>
25 <scope>provided</scope>
26 </dependency>
27 <dependency>
28 <groupId>org.jboss.spec.javax.servlet</groupId>
29 <artifactId>jboss-servlet-api_3.1_spec</artifactId>
30 </dependency>
31 <dependency>
32 <groupId>org.jboss.resteasy</groupId>
33 <artifactId>tjws</artifactId>
34 <version>${project.version}</version>
35 <scope>test</scope>
36 </dependency>
37 <dependency>
38 <groupId>org.glassfish</groupId>
39 <artifactId>javax.json</artifactId>
40 <scope>provided</scope>
41 </dependency>
42 <dependency>
43 <groupId>javax.json.bind</groupId>
44 <artifactId>javax.json.bind-api</artifactId>
45 </dependency>
46 <dependency>
47 <groupId>org.eclipse</groupId>
48 <artifactId>yasson</artifactId>
49 </dependency>
50 <dependency>
51 <groupId>org.jboss.logging</groupId>
52 <artifactId>jboss-logging-annotations</artifactId>
53 </dependency>
54 </dependencies>
55
56
57
58 </project>
0 package org.jboss.resteasy.plugins.providers.jsonb;
1
2 import org.eclipse.yasson.JsonBindingProvider;
3 import org.eclipse.yasson.internal.JsonBindingBuilder;
4 import org.glassfish.json.JsonProviderImpl;
5
6 import javax.json.bind.Jsonb;
7 import javax.ws.rs.core.Context;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.ext.ContextResolver;
10 import java.nio.charset.Charset;
11
12
13 /**
14 * Created by rsearls
15 */
16 public class AbstractJsonBindingProvider extends JsonBindingProvider {
17
18 private static final String JSON = "json";
19 private static final String PLUS_JSON = "+json";
20
21 @Context
22 javax.ws.rs.ext.Providers providers;
23 private static Jsonb jsonbObj = null;
24
25 protected Jsonb getJsonb(Class<?> type) {
26 ContextResolver<Jsonb> contextResolver = providers.getContextResolver(Jsonb.class, MediaType.APPLICATION_JSON_TYPE);
27 if (contextResolver != null)
28 {
29 return contextResolver.getContext(type);
30 } else
31 {
32 if (jsonbObj == null)
33 {
34 JsonProviderImpl jProviderImpl = new JsonProviderImpl();
35 JsonBindingBuilder jbBuilder = new JsonBindingBuilder();
36 jsonbObj = jbBuilder.withProvider(jProviderImpl).build();
37 }
38 return jsonbObj;
39 }
40 }
41
42 public static Charset getCharset(final MediaType mediaType) {
43 if (mediaType != null)
44 {
45 String charset = mediaType.getParameters().get("charset");
46 if (charset != null) return Charset.forName(charset);
47 }
48 return Charset.defaultCharset();
49 }
50
51 public static boolean isSupportedMediaType(final MediaType mediaType) {
52 return mediaType.getSubtype().equals(JSON) || mediaType.getSubtype().endsWith(PLUS_JSON);
53 }
54 }
0 package org.jboss.resteasy.plugins.providers.jsonb;
1
2 import org.jboss.resteasy.plugins.providers.jsonb.i18n.Messages;
3
4 import javax.json.bind.Jsonb;
5 import javax.annotation.Priority;
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.Priorities;
8 import javax.ws.rs.ProcessingException;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.MultivaluedMap;
12 import javax.ws.rs.ext.MessageBodyReader;
13 import javax.ws.rs.ext.MessageBodyWriter;
14 import javax.ws.rs.ext.Provider;
15
16 import java.io.InputStream;
17 import java.io.OutputStream;
18 import java.lang.annotation.Annotation;
19 import java.lang.reflect.Type;
20
21 import javax.xml.bind.annotation.XmlRootElement;
22 import javax.xml.bind.annotation.XmlType;
23
24 import org.jboss.resteasy.util.FindAnnotation;
25
26 /**
27 * Created by rsearls on 6/26/17.
28 */
29 @Provider
30 @Produces({"application/json", "application/*+json", "text/json", "*/*"})
31 @Consumes({"application/json", "application/*+json", "text/json", "*/*"})
32 @Priority(Priorities.USER-100)
33 public class JsonBindingProvider extends AbstractJsonBindingProvider
34 implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
35
36 @Override
37 public boolean isReadable(Class<?> type, Type genericType,
38 Annotation[] annotations, MediaType mediaType) {
39 return (isSupportedMediaType(mediaType))
40 && ((!type.isAnnotationPresent(XmlRootElement.class) && !type.isAnnotationPresent(XmlType.class))
41 || (FindAnnotation.findJsonBindingAnnotations(annotations).length != 0));
42 }
43
44 @Override
45 public Object readFrom(Class<Object> type, Type genericType,
46 Annotation[] annotations, MediaType mediaType,
47 MultivaluedMap<String, String> httpHeaders,
48 InputStream entityStream) throws java.io.IOException, javax.ws.rs.WebApplicationException {
49 Jsonb jsonb = getJsonb(type);
50 try
51 {
52 return jsonb.fromJson(entityStream, genericType);
53 } catch (Throwable e)
54 {
55 throw new ProcessingException(Messages.MESSAGES.jsonBDeserializationError(e.toString()));
56 }
57 }
58
59 @Override
60 public boolean isWriteable(Class<?> type, Type genericType,
61 Annotation[] annotations, MediaType mediaType) {
62 return (isSupportedMediaType(mediaType))
63 && ((!type.isAnnotationPresent(XmlRootElement.class) && !type.isAnnotationPresent(XmlType.class))
64 || (FindAnnotation.findJsonBindingAnnotations(annotations).length != 0));
65 }
66
67 @Override
68 public long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations,
69 MediaType mediaType) {
70 return -1L;
71 }
72
73 @Override
74 public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations,
75 MediaType mediaType,
76 MultivaluedMap<String, Object> httpHeaders,
77 OutputStream entityStream)
78 throws java.io.IOException, javax.ws.rs.WebApplicationException {
79 Jsonb jsonb = getJsonb(type);
80 try
81 {
82 entityStream.write(jsonb.toJson(t).getBytes(getCharset(mediaType)));
83 entityStream.flush();
84 } catch (Throwable e)
85 {
86 throw new ProcessingException(Messages.MESSAGES.jsonBSerializationError(e.toString()));
87 }
88 }
89 }
0 package org.jboss.resteasy.plugins.providers.jsonb.i18n;
1
2 import org.jboss.logging.BasicLogger;
3 import org.jboss.logging.Logger;
4 import org.jboss.logging.annotations.MessageLogger;
5
6 /**
7 *
8 */
9
10 @MessageLogger(projectCode = "RESTEASY")
11 public interface LogMessages extends BasicLogger
12 {
13 LogMessages LOGGER = Logger.getMessageLogger(LogMessages.class, LogMessages.class.getPackage().getName());
14 }
0 package org.jboss.resteasy.plugins.providers.jsonb.i18n;
1
2 import org.jboss.logging.annotations.Message;
3 import org.jboss.logging.annotations.Message.Format;
4 import org.jboss.logging.annotations.MessageBundle;
5
6 /**
7 */
8 @MessageBundle(projectCode = "RESTEASY")
9 public interface Messages
10 {
11 Messages MESSAGES = org.jboss.logging.Messages.getBundle(Messages.class);
12 int BASE = 8200;
13
14 @Message(id = BASE + 00, value = "JSON Binding deserialization error {0}", format=Format.MESSAGE_FORMAT)
15 String jsonBDeserializationError(String element);
16
17 @Message(id = BASE + 05, value = "JSON Binding serialization error {0}", format=Format.MESSAGE_FORMAT)
18 String jsonBSerializationError(String element);
19 }
0 org.jboss.resteasy.plugins.providers.jsonb.JsonBindingProvider
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-json-p-provider</artifactId>
3535 <scope>test</scope>
3636 </dependency>
3737 <dependency>
38 <groupId>javax.json</groupId>
39 <artifactId>javax.json-api</artifactId>
40 </dependency>
41 <dependency>
4238 <groupId>org.glassfish</groupId>
4339 <artifactId>javax.json</artifactId>
4440 </dependency>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-multipart-provider</artifactId>
66
77 import java.io.IOException;
88 import java.io.OutputStream;
9 import java.util.List;
910 import java.util.Map;
1011
1112 /**
1516 public class AbstractMultipartFormDataWriter extends AbstractMultipartWriter {
1617 @Override
1718 protected void writeParts(MultipartOutput multipartOutput,
18 OutputStream entityStream, byte[] boundaryBytes) throws IOException {
19 OutputStream entityStream, byte[] boundaryBytes) throws IOException {
1920 if (!(multipartOutput instanceof MultipartFormDataOutput))
20 throw new IllegalArgumentException(Messages.MESSAGES.hadToWriteMultipartOutput(multipartOutput, this, MultipartFormDataOutput.class));
21 throw new IllegalArgumentException(Messages.MESSAGES.hadToWriteMultipartOutput(multipartOutput, this, MultipartFormDataOutput.class));
2122 MultipartFormDataOutput form = (MultipartFormDataOutput) multipartOutput;
22 for (Map.Entry<String, OutputPart> entry : form.getFormData()
23 .entrySet()) {
24 if (entry.getValue().getEntity() == null)
25 continue;
26 MultivaluedMap<String, Object> headers = new MultivaluedMapImpl<String, Object>();
27 headers.putSingle("Content-Disposition", "form-data; name=\""
28 + entry.getKey() + "\""
29 + getFilename(entry.getValue()));
30 writePart(entityStream, boundaryBytes, entry.getValue(), headers);
23 for (Map.Entry<String, List<OutputPart>> entry : form.getFormDataMap().entrySet()) {
24 for (OutputPart outputPart : entry.getValue()) {
25 if (outputPart.getEntity() == null) {
26 continue;
27 }
28 MultivaluedMap<String, Object> headers = new MultivaluedMapImpl<String, Object>();
29 headers.putSingle("Content-Disposition", "form-data; name=\""
30 + entry.getKey() + "\""
31 + getFilename(outputPart));
32 writePart(entityStream, boundaryBytes, outputPart, headers);
33 }
3134 }
35 }
3236
33 }
34
3537 private String getFilename(OutputPart part) {
3638 String filename = part.getFilename();
3739 if (filename == null) {
22 import javax.ws.rs.core.GenericType;
33 import javax.ws.rs.core.MediaType;
44 import java.lang.reflect.Type;
5 import java.util.HashMap;
56 import java.util.LinkedHashMap;
7 import java.util.LinkedList;
8 import java.util.List;
69 import java.util.Map;
710
811 /**
1215 public class MultipartFormDataOutput extends MultipartOutput
1316 {
1417 protected Map<String, OutputPart> formData = new LinkedHashMap<String, OutputPart>();
18 protected Map<String, List<OutputPart>> formDataMap = new HashMap<String, List<OutputPart>>();
19
20 private void addFormDataMap(String key, OutputPart part) {
21 List<OutputPart> list = getFormDataMap().get(key);
22 if (list == null) {
23 list = new LinkedList<OutputPart>();
24 formDataMap.put(key, list);
25 }
26 list.add(part);
27 }
28
29 public Map<String, List<OutputPart>> getFormDataMap() {
30 return formDataMap;
31 }
1532
1633 public OutputPart addFormData(String key, Object entity, MediaType mediaType)
1734 {
1835 OutputPart part = super.addPart(entity, mediaType);
1936 formData.put(key, part);
37 addFormDataMap(key, part);
2038 return part;
2139 }
2240
2442 {
2543 OutputPart part = super.addPart(entity, mediaType, filename);
2644 formData.put(key, part);
45 addFormDataMap(key, part);
2746 return part;
2847 }
2948
3150 {
3251 OutputPart part = super.addPart(entity, type, mediaType);
3352 formData.put(key, part);
53 addFormDataMap(key, part);
3454 return part;
3555 }
3656
3858 {
3959 OutputPart part = super.addPart(entity, type, mediaType, filename);
4060 formData.put(key, part);
61 addFormDataMap(key, part);
4162 return part;
4263 }
4364
4566 {
4667 OutputPart part = super.addPart(entity, type, genericType, mediaType);
4768 formData.put(key, part);
69 addFormDataMap(key, part);
4870 return part;
4971 }
5072
5274 {
5375 OutputPart part = super.addPart(entity, type, genericType, mediaType, filename);
5476 formData.put(key, part);
77 addFormDataMap(key, part);
5578 return part;
5679 }
5780
22 <parent>
33 <groupId>org.jboss.resteasy</groupId>
44 <artifactId>resteasy-jaxrs-all</artifactId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../pom.xml</relativePath>
77 </parent>
88 <name>RESTEasy Providers</name>
2424 <module>jackson</module>
2525 <module>jackson2</module>
2626 <module>json-p-ee7</module>
27 <module>json-binding</module>
2728 <module>resteasy-atom</module>
2829 <module>multipart</module>
2930 <module>yaml</module>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-atom-provider</artifactId>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-html</artifactId>
2727 /**
2828 *
2929 * @author Jeff Schnitzer <jeff@infohazard.org>
30 * @author Thomas Broyer
3130 */
31 @SuppressWarnings("unchecked")
3232 @Provider
3333 @Produces("text/html")
3434 public class HtmlRenderableWriter implements MessageBodyWriter<Renderable>
5858 */
5959 //@Override
6060 public void writeTo(Renderable viewingPleasure, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
61 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
61 MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException
6262 {
6363 try
6464 {
65 viewingPleasure.render(
66 // disable async processing as that would mess with interceptors,
67 // and entityStream is committed after writeTo and interceptors returns.
68 new HttpServletRequestWrapper(getContextData(HttpServletRequest.class)) {
69
70 @Override
71 public boolean isAsyncSupported() {
72 return false;
73 }
65 viewingPleasure.render(
66 // disable async processing as that would mess with interceptors,
67 // and entityStream is committed after writeTo and interceptors returns.
68 new HttpServletRequestWrapper(getContextData(HttpServletRequest.class)) {
7469
75 @Override
76 public boolean isAsyncStarted() {
77 return false;
78 }
70 @Override
71 public boolean isAsyncSupported() {
72 return false;
73 }
7974
80 @Override
81 public AsyncContext getAsyncContext() {
82 throw new IllegalStateException();
83 }
75 @Override
76 public boolean isAsyncStarted() {
77 return false;
78 }
8479
85 @Override
86 public AsyncContext startAsync() throws IllegalStateException {
87 throw new IllegalStateException();
88 }
80 @Override
81 public AsyncContext getAsyncContext() {
82 throw new IllegalStateException();
83 }
8984
90 @Override
91 public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
92 throw new IllegalStateException();
93 }
94 },
95
96 // RESTEASY-1422: wrap entityStream to make sure headers added through JAX-RS are committed when the ServletOutputStream is written to.
97 // Also disable async processing on the ServletOutputStream, for consistency with the request.
98 new HttpServletResponseWrapper(getContextData(HttpServletResponse.class)) {
99
100 private ServletOutputStream outputStream;
101 private PrintWriter writer;
85 @Override
86 public AsyncContext startAsync() throws IllegalStateException {
87 throw new IllegalStateException();
88 }
10289
103 @Override
104 public ServletOutputStream getOutputStream() {
105
106 if (writer != null) {
107 throw new IllegalStateException();
108 }
109 if (outputStream == null) {
110 outputStream = new ServletOutputStream() {
111
112 @Override
113 public boolean isReady() {
114 return true;
115 }
90 @Override
91 public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
92 throw new IllegalStateException();
93 }
94 },
11695
117 @Override
118 public void setWriteListener(WriteListener writeListener) {
119 throw new IllegalStateException();
120 }
96 // RESTEASY-1422: wrap entityStream to make sure headers added through JAX-RS are committed when the ServletOutputStream is written to.
97 // Also disable async processing on the ServletOutputStream, for consistency with the request.
98 new HttpServletResponseWrapper(getContextData(HttpServletResponse.class)) {
12199
122 @Override
123 public void write(int b) throws IOException {
124 entityStream.write(b);
125 }
100 private ServletOutputStream outputStream;
101 private PrintWriter writer;
126102
127 @Override
128 public void write(byte[] b) throws IOException {
129 entityStream.write(b);
130 }
103 @Override
104 public ServletOutputStream getOutputStream() {
131105
132 @Override
133 public void write(byte[] b, int off, int len) throws IOException {
134 entityStream.write(b, off, len);
135 }
106 if (writer != null) {
107 throw new IllegalStateException();
108 }
109 if (outputStream == null) {
110 outputStream = new ServletOutputStream() {
136111
137 @Override
138 public void flush() throws IOException {
139 entityStream.flush();
140 }
112 @Override
113 public boolean isReady() {
114 return true;
115 }
141116
142 @Override
143 public void close() throws IOException {
144 entityStream.close();
145 }
146 };
147 }
148 return outputStream;
149 }
117 @Override
118 public void setWriteListener(WriteListener writeListener) {
119 throw new IllegalStateException();
120 }
150121
151 @Override
152 public PrintWriter getWriter() throws IOException {
153 if (outputStream != null) {
154 throw new IllegalStateException();
155 }
156 if (writer == null) {
157 writer = new PrintWriter(new OutputStreamWriter(entityStream, getCharacterEncoding()));
158 }
159 return writer;
160 }
161 });
122 @Override
123 public void write(int b) throws IOException {
124 entityStream.write(b);
125 }
126
127 @Override
128 public void write(byte[] b) throws IOException {
129 entityStream.write(b);
130 }
131
132 @Override
133 public void write(byte[] b, int off, int len) throws IOException {
134 entityStream.write(b, off, len);
135 }
136
137 @Override
138 public void flush() throws IOException {
139 entityStream.flush();
140 }
141
142 @Override
143 public void close() throws IOException {
144 entityStream.close();
145 }
146 };
147 }
148 return outputStream;
149 }
150
151 @Override
152 public PrintWriter getWriter() throws IOException {
153 if (outputStream != null) {
154 throw new IllegalStateException();
155 }
156 if (writer == null) {
157 writer = new PrintWriter(new OutputStreamWriter(entityStream, getCharacterEncoding()));
158 }
159 return writer;
160 }
161 });
162162 }
163163 catch (ServletException ex)
164164 {
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-validator-provider-11</artifactId>
+0
-482
providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationException.java less more
0 package org.jboss.resteasy.api.validation;
1
2 import java.io.BufferedReader;
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
7 import java.io.Serializable;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.Set;
14
15 import javax.validation.ConstraintViolation;
16 import javax.validation.ConstraintViolationException;
17 import javax.ws.rs.core.MediaType;
18
19 import org.jboss.resteasy.api.validation.ConstraintType.Type;
20 import org.jboss.resteasy.plugins.providers.validation.ViolationsContainer;
21 import org.jboss.resteasy.plugins.validation.ConstraintTypeUtil11;
22 import org.jboss.resteasy.plugins.validation.GeneralValidatorImpl;
23 import org.jboss.resteasy.plugins.validation.SimpleViolationsContainer;
24 import org.jboss.resteasy.plugins.validation.i18n.Messages;
25 import org.jboss.resteasy.spi.ResteasyConfiguration;
26 import org.jboss.resteasy.spi.ResteasyProviderFactory;
27
28 /**
29 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
30 * @version $Revision: 1.1 $
31 *
32 * Copyright Mar 6, 2012
33 *
34 * @TODO Need to work on representation of exceptions
35 * @TODO Add javadoc.
36 */
37 public class ResteasyViolationException extends ConstraintViolationException
38 {
39 private static final long serialVersionUID = 2623733139912277260L;
40
41 private List<CloneableMediaType> accept;
42 private Exception exception;
43
44 private List<ResteasyConstraintViolation> fieldViolations;
45 private List<ResteasyConstraintViolation> propertyViolations;
46 private List<ResteasyConstraintViolation> classViolations;
47 private List<ResteasyConstraintViolation> parameterViolations;
48 private List<ResteasyConstraintViolation> returnValueViolations;
49
50 private List<ResteasyConstraintViolation> allViolations;
51 private List<List<ResteasyConstraintViolation>> violationLists;
52
53 transient private ConstraintTypeUtil11 util = new ConstraintTypeUtil11();
54 private boolean suppressPath;
55
56 /**
57 * New constructor
58 * @param constraintViolations
59 */
60 public ResteasyViolationException(Set<? extends ConstraintViolation<?>> constraintViolations)
61 {
62 super(constraintViolations);
63 checkSuppressPath();
64 accept = new ArrayList<CloneableMediaType>();
65 accept.add(CloneableMediaType.TEXT_PLAIN_TYPE);
66 }
67
68 /**
69 * New constructor
70 *
71 * @param constraintViolations
72 * @param accept
73 */
74 public ResteasyViolationException(Set<? extends ConstraintViolation<?>> constraintViolations, List<MediaType> accept)
75 {
76 super(constraintViolations);
77 checkSuppressPath();
78 this.accept = toCloneableMediaTypeList(accept);
79 }
80
81 /**
82 * New constructor
83 *
84 * @param container
85 */
86 public ResteasyViolationException(SimpleViolationsContainer container)
87 {
88 this(container.getViolations());
89 exception = container.getException();
90 }
91
92 /**
93 * New constructor
94 *
95 * @param container
96 * @param accept
97 */
98
99 public ResteasyViolationException(SimpleViolationsContainer container, List<MediaType> accept)
100 {
101 this(container.getViolations(), accept);
102 exception = container.getException();
103 }
104
105 public ResteasyViolationException(ViolationsContainer<?> container)
106 {
107 super(null);
108 convertToStrings(container);
109 exception = container.getException();
110 accept = new ArrayList<CloneableMediaType>();
111 accept.add(CloneableMediaType.TEXT_PLAIN_TYPE);
112 }
113
114 public ResteasyViolationException(ViolationsContainer<?> container, List<MediaType> accept)
115 {
116 super(null);
117 convertToStrings(container);
118 exception = container.getException();
119 this.accept = toCloneableMediaTypeList(accept);
120 }
121
122 public ResteasyViolationException(String stringRep)
123 {
124 super(null);
125 checkSuppressPath();
126 convertFromString(stringRep);
127 }
128
129 public List<MediaType> getAccept()
130 {
131 return toMediaTypeList(accept);
132 }
133
134 public void setAccept(List<MediaType> accept)
135 {
136 this.accept = toCloneableMediaTypeList(accept);
137 }
138
139 public Exception getException()
140 {
141 return exception;
142 }
143
144 public void setException(Exception exception)
145 {
146 this.exception = exception;
147 }
148
149 public List<ResteasyConstraintViolation> getViolations()
150 {
151 convertViolations();
152 if (allViolations == null)
153 {
154 allViolations = new ArrayList<ResteasyConstraintViolation>();
155 allViolations.addAll(fieldViolations);
156 allViolations.addAll(propertyViolations);
157 allViolations.addAll(classViolations);
158 allViolations.addAll(parameterViolations);
159 allViolations.addAll(returnValueViolations);
160 }
161 return allViolations;
162 }
163
164 public List<ResteasyConstraintViolation> getFieldViolations()
165 {
166 convertViolations();
167 return fieldViolations;
168 }
169
170 public List<ResteasyConstraintViolation> getPropertyViolations()
171 {
172 convertViolations();
173 return propertyViolations;
174 }
175
176 public List<ResteasyConstraintViolation> getClassViolations()
177 {
178 convertViolations();
179 return classViolations;
180 }
181
182 public List<ResteasyConstraintViolation> getParameterViolations()
183 {
184 convertViolations();
185 return parameterViolations;
186 }
187
188 public List<ResteasyConstraintViolation> getReturnValueViolations()
189 {
190 convertViolations();
191 return returnValueViolations;
192 }
193
194 public int size()
195 {
196 return getViolations().size();
197 }
198
199 public List<List<ResteasyConstraintViolation>> getViolationLists()
200 {
201 convertViolations();
202 return violationLists;
203 }
204
205 public String toString()
206 {
207 convertViolations();
208 StringBuffer sb = new StringBuffer();
209 for (Iterator<List<ResteasyConstraintViolation>> it = violationLists.iterator(); it.hasNext(); )
210 {
211 List<ResteasyConstraintViolation> violations = it.next();
212 for (Iterator<ResteasyConstraintViolation> it2 = violations.iterator(); it2.hasNext(); )
213 {
214 sb.append(it2.next().toString()).append('\r');
215 }
216 }
217 return sb.toString();
218 }
219
220 protected void convertToStrings(ViolationsContainer<?> container)
221 {
222 if (violationLists != null)
223 {
224 return;
225 }
226 violationLists = new ArrayList<List<ResteasyConstraintViolation>>();
227 fieldViolations = container.getFieldViolations();
228 propertyViolations = container.getPropertyViolations();
229 classViolations = container.getClassViolations();
230 parameterViolations = container.getParameterViolations();
231 returnValueViolations = container.getReturnValueViolations();
232
233 violationLists.add(fieldViolations);
234 violationLists.add(propertyViolations);
235 violationLists.add(classViolations);
236 violationLists.add(parameterViolations);
237 violationLists.add(returnValueViolations);
238 }
239
240 protected void convertFromString(String stringRep)
241 {
242 convertViolations();
243 InputStream is = new ByteArrayInputStream(stringRep.getBytes());
244 BufferedReader br = new BufferedReader(new InputStreamReader(is));
245 String line;
246 try
247 {
248 line = br.readLine();
249 while (line != null )
250 {
251 ConstraintType.Type type = ConstraintType.Type.valueOf(line.substring(1, line.length() - 1));
252 line = br.readLine();
253 String path = line.substring(1, line.length() - 1);
254 line = br.readLine();
255 String message = line.substring(1, line.length() - 1);
256 line = br.readLine();
257 String value = line.substring(1, line.length() - 1);
258 ResteasyConstraintViolation rcv = new ResteasyConstraintViolation(type, path, message, value);
259
260 switch (type)
261 {
262 case FIELD:
263 fieldViolations.add(rcv);
264 break;
265
266 case PROPERTY:
267 propertyViolations.add(rcv);
268 break;
269
270 case CLASS:
271 classViolations.add(rcv);
272 break;
273
274 case PARAMETER:
275 parameterViolations.add(rcv);
276 break;
277
278 case RETURN_VALUE:
279 returnValueViolations.add(rcv);
280 break;
281
282 default:
283 throw new RuntimeException(Messages.MESSAGES.unexpectedViolationType(type));
284 }
285 line = br.readLine(); // consume ending '\r'
286 line = br.readLine();
287 }
288 }
289 catch (IOException e)
290 {
291 throw new RuntimeException(Messages.MESSAGES.unableToParseException());
292 }
293
294 violationLists = new ArrayList<List<ResteasyConstraintViolation>>();
295 violationLists.add(fieldViolations);
296 violationLists.add(propertyViolations);
297 violationLists.add(classViolations);
298 violationLists.add(parameterViolations);
299 violationLists.add(returnValueViolations);
300 }
301
302 protected int getField(int start, String line)
303 {
304 int beginning = line.indexOf('[', start);
305 if (beginning == -1)
306 {
307 throw new RuntimeException(Messages.MESSAGES.exceptionHasInvalidFormat(line));
308 }
309 int index = beginning;
310 int bracketCount = 1;
311 while (++index < line.length())
312 {
313 char c = line.charAt(index);
314 if (c == '[')
315 {
316 bracketCount++;
317 }
318 else if (c == ']')
319 {
320 bracketCount--;
321 }
322 if (bracketCount == 0)
323 {
324 break;
325 }
326 }
327 if (bracketCount != 0)
328 {
329 throw new RuntimeException(Messages.MESSAGES.exceptionHasInvalidFormat(line));
330 }
331 return index;
332 }
333
334 protected void checkSuppressPath()
335 {
336 ResteasyConfiguration context = ResteasyProviderFactory.getContextData(ResteasyConfiguration.class);
337 if (context != null)
338 {
339 String s = context.getParameter(GeneralValidatorImpl.SUPPRESS_VIOLATION_PATH);
340 if (s != null)
341 {
342 suppressPath = Boolean.parseBoolean(s);
343 }
344 }
345 }
346
347 protected void convertViolations()
348 {
349 if (violationLists != null)
350 {
351 return;
352 }
353
354 fieldViolations = new ArrayList<ResteasyConstraintViolation>();
355 propertyViolations = new ArrayList<ResteasyConstraintViolation>();
356 classViolations = new ArrayList<ResteasyConstraintViolation>();
357 parameterViolations = new ArrayList<ResteasyConstraintViolation>();
358 returnValueViolations = new ArrayList<ResteasyConstraintViolation>();
359
360 if (getConstraintViolations() != null)
361 {
362 for (Iterator<ConstraintViolation<?>> it = getConstraintViolations().iterator(); it.hasNext(); )
363 {
364 ResteasyConstraintViolation rcv = convertViolation(it.next());
365 switch (rcv.getConstraintType())
366 {
367 case FIELD:
368 fieldViolations.add(rcv);
369 break;
370
371 case PROPERTY:
372 propertyViolations.add(rcv);
373 break;
374
375 case CLASS:
376 classViolations.add(rcv);
377 break;
378
379 case PARAMETER:
380 parameterViolations.add(rcv);
381 break;
382
383 case RETURN_VALUE:
384 returnValueViolations.add(rcv);
385 break;
386
387 default:
388 throw new RuntimeException(Messages.MESSAGES.unexpectedViolationType(rcv.getConstraintType()));
389 }
390 }
391 }
392
393 violationLists = new ArrayList<List<ResteasyConstraintViolation>>();
394 violationLists.add(fieldViolations);
395 violationLists.add(propertyViolations);
396 violationLists.add(classViolations);
397 violationLists.add(parameterViolations);
398 violationLists.add(returnValueViolations);
399 }
400
401 protected ResteasyConstraintViolation convertViolation(ConstraintViolation<?> violation)
402 {
403 Type ct = util.getConstraintType(violation);
404 String path = (suppressPath ? "*" : violation.getPropertyPath().toString());
405 return new ResteasyConstraintViolation(ct, path, violation.getMessage(), convertArrayToString(violation.getInvalidValue()));
406 }
407
408 static protected String convertArrayToString(Object o)
409 {
410 String result = null;
411 if (o instanceof Object[])
412 {
413 Object[] array = Object[].class.cast(o);
414 StringBuffer sb = new StringBuffer("[").append(convertArrayToString(array[0]));
415 for (int i = 1; i < array.length; i++)
416 {
417 sb.append(", ").append(convertArrayToString(array[i]));
418 }
419 sb.append("]");
420 result = sb.toString();
421 }
422 else
423 {
424 result = (o == null ? "" : o.toString());
425 }
426 return result;
427 }
428
429 /**
430 * It seems that EJB3 wants to clone ResteasyViolationException,
431 * and MediaType is not serializable.
432 *
433 */
434 static class CloneableMediaType implements Serializable
435 {
436 public static final CloneableMediaType TEXT_PLAIN_TYPE = new CloneableMediaType("plain", "text");
437 private static final long serialVersionUID = 9179565449557464429L;
438 private String type;
439 private String subtype;
440 private Map<String, String> parameters;
441
442 public CloneableMediaType(MediaType mediaType)
443 {
444 type = mediaType.getType();
445 subtype = mediaType.getSubtype();
446 parameters = new HashMap<String, String>(mediaType.getParameters());
447 }
448
449 public CloneableMediaType(String type, String subtype)
450 {
451 this.type = type;
452 this.subtype = subtype;
453 }
454
455 public MediaType toMediaType()
456 {
457 return new MediaType(type, subtype, parameters);
458 }
459 }
460
461 static protected List<CloneableMediaType> toCloneableMediaTypeList(List<MediaType> list)
462 {
463 List<CloneableMediaType> cloneableList = new ArrayList<CloneableMediaType>();
464 for (Iterator<MediaType> it = list.iterator(); it.hasNext(); )
465 {
466 cloneableList.add(new CloneableMediaType(it.next()));
467 }
468 return cloneableList;
469 }
470
471 static protected List<MediaType> toMediaTypeList(List<CloneableMediaType> cloneableList)
472 {
473 List<MediaType> list = new ArrayList<MediaType>();
474 for (Iterator<CloneableMediaType> it = cloneableList.iterator(); it.hasNext(); )
475 {
476 CloneableMediaType cmt = it.next();
477 list.add(new MediaType(cmt.type, cmt.subtype, cmt.parameters));
478 }
479 return list;
480 }
481 }
+0
-130
providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationExceptionMapper.java less more
0 package org.jboss.resteasy.api.validation;
1
2 import java.util.Iterator;
3 import java.util.List;
4
5 import javax.validation.ConstraintDeclarationException;
6 import javax.validation.ConstraintDefinitionException;
7 import javax.validation.GroupDefinitionException;
8 import javax.validation.ValidationException;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.Response;
11 import javax.ws.rs.core.Response.ResponseBuilder;
12 import javax.ws.rs.core.Response.Status;
13 import javax.ws.rs.ext.ExceptionMapper;
14 import javax.ws.rs.ext.Provider;
15
16
17 /**
18 *
19 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
20 * @version $Revision: 1.1 $
21 *
22 * Created Mar 31, 2012
23 */
24 @Provider
25 public class ResteasyViolationExceptionMapper implements ExceptionMapper<ValidationException>
26 {
27 public Response toResponse(ValidationException exception)
28 {
29 if (exception instanceof ConstraintDefinitionException)
30 {
31 return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
32 }
33 if (exception instanceof ConstraintDeclarationException)
34 {
35 return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
36 }
37 if (exception instanceof GroupDefinitionException)
38 {
39 return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
40 }
41 if (exception instanceof ResteasyViolationException)
42 {
43 ResteasyViolationException resteasyViolationException = ResteasyViolationException.class.cast(exception);
44 Exception e = resteasyViolationException.getException();
45 if (e != null)
46 {
47 return buildResponse(unwrapException(e), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
48 }
49 else if (resteasyViolationException.getReturnValueViolations().size() == 0)
50 {
51 return buildViolationReportResponse(resteasyViolationException, Status.BAD_REQUEST);
52 }
53 else
54 {
55 return buildViolationReportResponse(resteasyViolationException, Status.INTERNAL_SERVER_ERROR);
56 }
57 }
58 return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
59 }
60
61 protected Response buildResponse(Object entity, String mediaType, Status status)
62 {
63 ResponseBuilder builder = Response.status(status).entity(entity);
64 builder.type(MediaType.TEXT_PLAIN);
65 builder.header(Validation.VALIDATION_HEADER, "true");
66 return builder.build();
67 }
68
69 protected Response buildViolationReportResponse(ResteasyViolationException exception, Status status)
70 {
71 ResponseBuilder builder = Response.status(status);
72 builder.header(Validation.VALIDATION_HEADER, "true");
73
74 // Check standard media types.
75 MediaType mediaType = getAcceptMediaType(exception.getAccept());
76 if (mediaType != null)
77 {
78 builder.type(mediaType);
79 builder.entity(new ViolationReport(exception));
80 return builder.build();
81 }
82
83 // Default media type.
84 builder.type(MediaType.TEXT_PLAIN);
85 builder.entity(exception.toString());
86 return builder.build();
87 }
88
89
90 protected String unwrapException(Throwable t)
91 {
92 StringBuffer sb = new StringBuffer();
93 doUnwrapException(sb, t);
94 return sb.toString();
95 }
96
97 private void doUnwrapException(StringBuffer sb, Throwable t)
98 {
99 if (t == null)
100 {
101 return;
102 }
103 sb.append(t.toString());
104 if (t.getCause() != null && t != t.getCause())
105 {
106 sb.append('[');
107 doUnwrapException(sb, t.getCause());
108 sb.append(']');
109 }
110 }
111
112 private MediaType getAcceptMediaType (List<MediaType> accept)
113 {
114 Iterator<MediaType> it = accept.iterator();
115 while (it.hasNext())
116 {
117 MediaType mt = it.next();
118 if (MediaType.APPLICATION_XML_TYPE.getType().equals(mt.getType()) && MediaType.APPLICATION_XML_TYPE.getSubtype().equals(mt.getSubtype()))
119 {
120 return MediaType.APPLICATION_XML_TYPE;
121 }
122 if (MediaType.APPLICATION_JSON_TYPE.getType().equals(mt.getType()) && MediaType.APPLICATION_JSON_TYPE.getSubtype().equals(mt.getSubtype()))
123 {
124 return MediaType.APPLICATION_JSON_TYPE;
125 }
126 }
127 return null;
128 }
129 }
+0
-110
providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/api/validation/ViolationReport.java less more
0 package org.jboss.resteasy.api.validation;
1
2 import java.util.ArrayList;
3
4 import javax.xml.bind.annotation.XmlAccessType;
5 import javax.xml.bind.annotation.XmlAccessorType;
6 import javax.xml.bind.annotation.XmlRootElement;
7
8 /**
9 *
10 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
11 * @version $Revision: 1.1 $
12 *
13 * Copyright July 27, 2013
14 */
15 @XmlRootElement(name="violationReport")
16 @XmlAccessorType(XmlAccessType.FIELD)
17 public class ViolationReport
18 {
19 private String exception;
20
21 private ArrayList<ResteasyConstraintViolation> fieldViolations = new ArrayList<ResteasyConstraintViolation>();
22 private ArrayList<ResteasyConstraintViolation> propertyViolations = new ArrayList<ResteasyConstraintViolation>();
23 private ArrayList<ResteasyConstraintViolation> classViolations = new ArrayList<ResteasyConstraintViolation>();
24 private ArrayList<ResteasyConstraintViolation> parameterViolations = new ArrayList<ResteasyConstraintViolation>();
25 private ArrayList<ResteasyConstraintViolation> returnValueViolations = new ArrayList<ResteasyConstraintViolation>();
26
27 public ViolationReport(ResteasyViolationException exception)
28 {
29 Exception e = exception.getException();
30 if (e != null)
31 {
32 this.exception = e.toString();
33 }
34 this.fieldViolations = (ArrayList<ResteasyConstraintViolation>) exception.getFieldViolations();
35 this.propertyViolations = (ArrayList<ResteasyConstraintViolation>) exception.getPropertyViolations();
36 this.classViolations = (ArrayList<ResteasyConstraintViolation>) exception.getClassViolations();
37 this.parameterViolations = (ArrayList<ResteasyConstraintViolation>) exception.getParameterViolations();
38 this.returnValueViolations = (ArrayList<ResteasyConstraintViolation>) exception.getReturnValueViolations();
39 }
40
41 public ViolationReport(String s)
42 {
43 this(new ResteasyViolationException(s));
44 }
45
46 public ViolationReport()
47 {
48 }
49
50 public String getException()
51 {
52 return exception;
53 }
54
55 public ArrayList<ResteasyConstraintViolation> getFieldViolations()
56 {
57 return fieldViolations;
58 }
59
60 public ArrayList<ResteasyConstraintViolation> getPropertyViolations()
61 {
62 return propertyViolations;
63 }
64
65 public ArrayList<ResteasyConstraintViolation> getClassViolations()
66 {
67 return classViolations;
68 }
69
70 public ArrayList<ResteasyConstraintViolation> getParameterViolations()
71 {
72 return parameterViolations;
73 }
74
75 public ArrayList<ResteasyConstraintViolation> getReturnValueViolations()
76 {
77 return returnValueViolations;
78 }
79
80 public void setException(String exception)
81 {
82 this.exception = exception;
83 }
84
85 public void setFieldViolations(ArrayList<ResteasyConstraintViolation> fieldViolations)
86 {
87 this.fieldViolations = fieldViolations;
88 }
89
90 public void setPropertyViolations(ArrayList<ResteasyConstraintViolation> propertyViolations)
91 {
92 this.propertyViolations = propertyViolations;
93 }
94
95 public void setClassViolations(ArrayList<ResteasyConstraintViolation> classViolations)
96 {
97 this.classViolations = classViolations;
98 }
99
100 public void setParameterViolations(ArrayList<ResteasyConstraintViolation> parameterViolations)
101 {
102 this.parameterViolations = parameterViolations;
103 }
104
105 public void setReturnValueViolations(ArrayList<ResteasyConstraintViolation> returnValueViolations)
106 {
107 this.returnValueViolations = returnValueViolations;
108 }
109 }
+0
-142
providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/ConstraintTypeUtil11.java less more
0 package org.jboss.resteasy.plugins.validation;
1
2 import java.lang.reflect.Method;
3 import java.util.Iterator;
4
5 import javax.validation.ConstraintViolation;
6 import javax.validation.ElementKind;
7 import javax.validation.Path.Node;
8
9 import org.jboss.resteasy.api.validation.ConstraintType;
10 import org.jboss.resteasy.plugins.providers.validation.ConstraintTypeUtil;
11 import org.jboss.resteasy.plugins.validation.i18n.Messages;
12 import java.security.AccessController;
13 import java.security.PrivilegedActionException;
14 import java.security.PrivilegedExceptionAction;
15
16 /**
17 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
18 * @version $Revision: 1.1 $
19 *
20 * Copyright Mar 6, 2012
21 */
22 public class ConstraintTypeUtil11 implements ConstraintTypeUtil
23 {
24 public ConstraintType.Type getConstraintType(Object o)
25 {
26 if (!(o instanceof ConstraintViolation))
27 {
28 throw new RuntimeException(Messages.MESSAGES.unknownObjectPassedAsConstraintViolation(o));
29 }
30 ConstraintViolation<?> v = ConstraintViolation.class.cast(o);
31
32 Iterator<Node> nodes = v.getPropertyPath().iterator();
33 Node firstNode = nodes.next();
34 if (firstNode.getKind() == ElementKind.METHOD)
35 {
36 Node secondNode = nodes.next();
37
38 if (secondNode.getKind() == ElementKind.PARAMETER ||
39 secondNode.getKind() == ElementKind.CROSS_PARAMETER)
40 {
41 return ConstraintType.Type.PARAMETER;
42 }
43 else if (secondNode.getKind() == ElementKind.RETURN_VALUE)
44 {
45 return ConstraintType.Type.RETURN_VALUE;
46 }
47 else
48 {
49 throw new RuntimeException(Messages.MESSAGES.unexpectedPathNodeViolation(secondNode.getKind()));
50 }
51 }
52
53 if (firstNode.getKind() == ElementKind.BEAN)
54 {
55 return ConstraintType.Type.CLASS;
56 }
57
58 if (firstNode.getKind() == ElementKind.PROPERTY)
59 {
60 String fieldName = firstNode.getName();
61 try
62 {
63 String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
64 getMethod(v.getRootBeanClass(), getterName);
65 return ConstraintType.Type.PROPERTY;
66 }
67 catch (NoSuchMethodException e)
68 {
69 try
70 {
71 String getterName = "is" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
72 Method m = getMethod(v.getLeafBean().getClass(), getterName);
73 if (m.getReturnType().equals(boolean.class))
74 {
75 return ConstraintType.Type.PROPERTY;
76 }
77 else
78 {
79 return ConstraintType.Type.FIELD;
80 }
81 }
82 catch (NoSuchMethodException e1)
83 {
84 return ConstraintType.Type.FIELD;
85 }
86 }
87 }
88
89 throw new RuntimeException(Messages.MESSAGES.unexpectedPathNode(firstNode.getKind()));
90 }
91
92 private static Method getMethod(Class<?> clazz, String methodName) throws NoSuchMethodException
93 {
94 Method method = null;
95 method = checkMethodAccess(clazz, methodName);
96
97 while (method == null)
98 {
99 clazz = clazz.getSuperclass();
100 if (clazz == null)
101 {
102 break;
103 }
104
105 method = checkMethodAccess(clazz, methodName);
106 }
107 if (method == null)
108 {
109 throw new NoSuchMethodException(methodName);
110 }
111 return method;
112 }
113
114 private static Method checkMethodAccess(final Class<?> clazz, final String methodName) {
115 Method method = null;
116 try
117 {
118 if (System.getSecurityManager() == null)
119 {
120 method = clazz.getDeclaredMethod(methodName);
121 }
122 else
123 {
124 method = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() {
125 @Override
126 public Method run() throws Exception {
127 return clazz.getDeclaredMethod(methodName);
128 }
129 });
130 }
131 }
132 catch(PrivilegedActionException pae) {
133 }
134 catch (NoSuchMethodException e)
135 {
136 // Ignore.
137 }
138
139 return method;
140 }
141 }
1010 import java.util.Set;
1111
1212 import javax.enterprise.context.ApplicationScoped;
13 import javax.validation.ConstraintDeclarationException;
14 import javax.validation.ConstraintDefinitionException;
1315 import javax.validation.ConstraintViolation;
1416 import javax.validation.ConstraintViolationException;
17 import javax.validation.GroupDefinitionException;
1518 import javax.validation.MessageInterpolator;
1619 import javax.validation.ValidationException;
1720 import javax.validation.Validator;
105108 SimpleViolationsContainer violationsContainer = getViolationsContainer(request, object);
106109 violationsContainer.setException(e);
107110 violationsContainer.setFieldsValidated(true);
108 throw new ResteasyViolationException(violationsContainer);
111 throw toValidationException(e, violationsContainer);
109112 }
110113
111114 SimpleViolationsContainer violationsContainer = getViolationsContainer(request, object);
112115 violationsContainer.addViolations(cvs);
113116 violationsContainer.setFieldsValidated(true);
117 }
118
119 private ValidationException toValidationException(Exception exception, SimpleViolationsContainer simpleViolationsContainer)
120 {
121 if (exception instanceof ConstraintDeclarationException ||
122 exception instanceof ConstraintDefinitionException ||
123 exception instanceof GroupDefinitionException)
124 {
125 return (ValidationException) exception;
126 }
127 return new ResteasyViolationException(simpleViolationsContainer);
114128 }
115129
116130 @Override
164178 catch (Exception e)
165179 {
166180 violationsContainer.setException(e);
167 throw new ResteasyViolationException(violationsContainer);
181 throw toValidationException(e, violationsContainer);
168182 }
169183 violationsContainer.addViolations(cvs);
170184 if ((violationsContainer.isFieldsValidated()
190204 catch (Exception e)
191205 {
192206 violationsContainer.setException(e);
193 throw new ResteasyViolationException(violationsContainer);
207 throw toValidationException(e, violationsContainer);
194208 }
195209 violationsContainer.addViolations(cvs);
196210 if (violationsContainer.size() > 0)
00 package org.jboss.resteasy.plugins.validation;
11
22 import java.io.Serializable;
3 import java.util.HashSet;
43 import java.util.Set;
54
65 import javax.validation.ConstraintViolation;
1211 *
1312 * Copyright Jul 18, 2015
1413 */
15 public class SimpleViolationsContainer implements Serializable
14 public class SimpleViolationsContainer extends org.jboss.resteasy.api.validation.SimpleViolationsContainer implements Serializable
1615 {
1716 private static final long serialVersionUID = -7895854137980651539L;
1817
19 private Set<ConstraintViolation<Object>> violations = new HashSet<ConstraintViolation<Object>>();
20 private Exception exception;
21 private Object target;
22 private boolean fieldsValidated;
23
2418 public SimpleViolationsContainer(Object target)
2519 {
26 this.target = target;
20 super(target);
2721 }
2822
2923 public SimpleViolationsContainer(Set<ConstraintViolation<Object>> cvs)
3024 {
31 violations.addAll(cvs);
32 }
33
34 public void addViolations(Set<ConstraintViolation<Object>> cvs)
35 {
36 violations.addAll(cvs);
37 }
38
39 public int size()
40 {
41 return violations.size();
42 }
43
44 public Exception getException()
45 {
46 return exception;
47 }
48
49 public void setException(Exception exception)
50 {
51 this.exception = exception;
52 }
53
54 public Object getTarget()
55 {
56 return target;
57 }
58
59 public void setTarget(Object target)
60 {
61 this.target = target;
62 }
63
64 public Set<ConstraintViolation<Object>> getViolations()
65 {
66 return violations;
67 }
68
69 public boolean isFieldsValidated()
70 {
71 return fieldsValidated;
72 }
73
74 public void setFieldsValidated(boolean fieldsValidated)
75 {
76 this.fieldsValidated = fieldsValidated;
25 super(cvs);
7726 }
7827 }
00 package org.jboss.resteasy.plugins.validation.i18n;
11
2 import javax.validation.ElementKind;
32 import javax.validation.ValidatorFactory;
43
54 import org.jboss.logging.annotations.Message;
65 import org.jboss.logging.annotations.MessageBundle;
7 import org.jboss.resteasy.api.validation.ConstraintType;
86
97 /**
108 *
1917 Messages MESSAGES = org.jboss.logging.Messages.getBundle(Messages.class);
2018 int BASE = 8500;
2119
22 @Message(id = BASE + 0, value = "ResteasyViolationException has invalid format: %s")
23 String exceptionHasInvalidFormat(String line);
20 // @Message(id = BASE + 0, value = "ResteasyViolationException has invalid format: %s")
21 // String exceptionHasInvalidFormat(String line);
2422
2523 @Message(id = BASE + 05, value = "Expect two non-null methods")
2624 String expectTwoNonNullMethods();
3432 @Message(id = BASE + 20, value = "Unable to load Validation support")
3533 String unableToLoadValidationSupport();
3634
37 @Message(id = BASE + 25, value = "Unable to parse ResteasyViolationException")
38 String unableToParseException();
35 // @Message(id = BASE + 25, value = "Unable to parse ResteasyViolationException")
36 // String unableToParseException();
3937
40 @Message(id = BASE + 30, value = "unexpected path node type: %s")
41 String unexpectedPathNode(ElementKind kind);
38 // @Message(id = BASE + 30, value = "unexpected path node type: %s")
39 // String unexpectedPathNode(ElementKind kind);
4240
43 @Message(id = BASE + 35, value = "unexpected path node type in method violation: %s")
44 String unexpectedPathNodeViolation(ElementKind kind);
41 // @Message(id = BASE + 35, value = "unexpected path node type in method violation: %s")
42 // String unexpectedPathNodeViolation(ElementKind kind);
4543
46 @Message(id = BASE + 40, value = "unexpected violation type: %s")
47 String unexpectedViolationType(ConstraintType.Type type);
44 // @Message(id = BASE + 40, value = "unexpected violation type: %s")
45 // String unexpectedViolationType(ConstraintType.Type type);
4846
49 @Message(id = BASE + 45, value = "unknown object passed as constraint violation: %s")
50 String unknownObjectPassedAsConstraintViolation(Object o);
47 // @Message(id = BASE + 45, value = "unknown object passed as constraint violation: %s")
48 // String unknownObjectPassedAsConstraintViolation(Object o);
5149
5250 @Message(id = BASE + 50, value = "Unable to find CDI supporting ValidatorFactory. Using default ValidatorFactory")
5351 String usingValidatorFactoryDoesNotSupportCDI();
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-yaml-provider</artifactId>
00 package org.jboss.resteasy.plugins.providers;
11
2
3 import org.jboss.resteasy.logging.Logger;
24 import org.jboss.resteasy.plugins.providers.yaml.i18n.LogMessages;
35 import org.jboss.resteasy.plugins.providers.yaml.i18n.Messages;
46 import org.jboss.resteasy.spi.ReaderException;
3436 @Provider
3537 @Consumes({"text/yaml", "text/x-yaml", "application/x-yaml"})
3638 @Produces({"text/yaml", "text/x-yaml", "application/x-yaml"})
39 @Deprecated
3740 public class YamlProvider extends AbstractEntityProvider<Object> {
3841
3942 // MessageBodyReader
44 <parent>
55 <groupId>org.jboss.resteasy</groupId>
66 <artifactId>resteasy-jaxrs-all</artifactId>
7 <version>3.1.4.Final</version>
7 <version>3.5.0.Final</version>
88 <relativePath>../pom.xml</relativePath>
99 </parent>
1010
9797 </dependency>
9898 <dependency>
9999 <groupId>org.jboss.resteasy</groupId>
100 <artifactId>resteasy-json-binding-provider</artifactId>
101 <version>${project.version}</version>
102 </dependency>
103 <dependency>
104 <groupId>org.jboss.resteasy</groupId>
100105 <artifactId>resteasy-jdk-http</artifactId>
101106 <version>${project.version}</version>
102107 </dependency>
22 <parent>
33 <groupId>org.jboss.resteasy</groupId>
44 <artifactId>resteasy-jaxrs-all</artifactId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../pom.xml</relativePath>
77 </parent>
88 <name>RESTEasy Cache</name>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-cache-core</artifactId>
1717 </dependency>
1818 <dependency>
1919 <groupId>org.jboss.spec.javax.ws.rs</groupId>
20 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
20 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
2121 </dependency>
2222 <dependency>
2323 <groupId>org.jboss.resteasy</groupId>
1818 import java.util.HashSet;
1919 import java.util.Iterator;
2020 import java.util.List;
21 import java.util.Map;
2221 import java.util.Set;
2322 import java.util.concurrent.TimeUnit;
2423
4140 private String etag;
4241 private transient MultivaluedMap<String, Object> headers;
4342 private transient MediaType mediaType;
44 private transient MultivaluedMap<String, String> varyHeaders;
4543
46 private CacheEntry(MultivaluedMap<String, Object> headers, byte[] cached, int expires, String etag, MediaType mediaType, MultivaluedMap<String, String> varyHeaders)
44 private CacheEntry(MultivaluedMap<String, Object> headers, byte[] cached, int expires, String etag, MediaType mediaType)
4745 {
4846 this.cached = cached;
4947 this.expires = expires;
5048 this.headers = headers;
5149 this.etag = etag;
5250 this.mediaType = mediaType;
53 this.varyHeaders = varyHeaders;
5451 }
5552
5653 public int getExpirationInSeconds()
7168 public MultivaluedMap<String, Object> getHeaders()
7269 {
7370 return headers;
74 }
75
76 public MultivaluedMap<String, String> getVaryHeaders()
77 {
78 return varyHeaders;
7971 }
8072
8173 public byte[] getCached()
9284 {
9385 stream.defaultWriteObject();
9486 stream.writeObject(stringifyHeaders(headers));
95 stream.writeObject(stringifyHeaders(varyHeaders));
9687 stream.writeUTF(mediaType.toString());
9788 }
9889
10192 {
10293 stream.defaultReadObject();
10394 headers = unstringifyHeaders(MultivaluedMap.class.cast(stream.readObject()));
104 varyHeaders = unstringifyHeaders(MultivaluedMap.class.cast(stream.readObject()));
10595 mediaType = MediaType.valueOf(stream.readUTF());
10696 }
10797 }
115105 this.cache = cache;
116106 }
117107
118 public Entry get(String uri, MediaType accept, MultivaluedMap<String, String> headers)
108 public Entry get(String uri, MediaType accept)
119109 {
120110 @SuppressWarnings("unchecked")
121111 Set<String> entries = (Set<String>)cache.get(uri);
125115 {
126116 CacheEntry cacheEntry = (CacheEntry)cache.get(entry);
127117 if (cacheEntry == null) continue;
128 if (accept.isCompatible(cacheEntry.getMediaType()) && !ServerCache.mayVary(cacheEntry, headers))
118 if (accept.isCompatible(cacheEntry.getMediaType()))
129119 {
130120 return cacheEntry;
131121 }
134124 }
135125
136126 @SuppressWarnings("unchecked")
137 public Entry add(String uri, MediaType mediaType, CacheControl cc, MultivaluedMap<String, Object> headers, byte[] entity, String etag, MultivaluedMap<String, String> varyHeaders)
127 public Entry add(String uri, MediaType mediaType, CacheControl cc, MultivaluedMap<String, Object> headers, byte[] entity, String etag)
138128 {
139129 // there's a race condition here with a concurrent get() method above. Too bad JBoss Cache doesn't have a way to create
140130 // a node before hand then insert it
141 CacheEntry cacheEntry = new CacheEntry(headers, entity, cc.getMaxAge(), etag, mediaType, varyHeaders);
142 StringBuffer varyHeadersString = new StringBuffer();
143 varyHeaders.forEach((name, values) -> values.forEach(value -> varyHeadersString.append(name).append(value)));
144 String entryName = uri + " " + mediaType.toString() + " " + varyHeadersString.toString();
131 CacheEntry cacheEntry = new CacheEntry(headers, entity, cc.getMaxAge(), etag, mediaType);
132 String entryName = uri + " " + mediaType.toString();
145133 Set<String> entries = (Set<String>)cache.get(uri);
146134 Set<String> newEntries = new HashSet<String>();
147135 newEntries.add(entryName);
170158 cache.clear();
171159 }
172160
173 protected static MultivaluedMap<String, ?> stringifyHeaders(MultivaluedMap<String, ?> headers)
161 protected static MultivaluedMap<String, Object> stringifyHeaders(MultivaluedMap<String, Object> headers)
174162 {
175163 MultivaluedMap<String, Object> holders = new MultivaluedTreeMap<String, Object>();
176164 for (Iterator<String> it1 = headers.keySet().iterator(); it1.hasNext(); )
178166 String key = it1.next();
179167 List<Object> outList = new ArrayList<Object>();
180168 holders.put(key, outList);
181 List<?> list = headers.get(key);
182 for (Iterator<?> it2 = list.iterator(); it2.hasNext(); )
169 List<Object> list = headers.get(key);
170 for (Iterator<Object> it2 = list.iterator(); it2.hasNext(); )
183171 {
184172 Object o = it2.next();
185173 if (o instanceof CacheControl)
00 package org.jboss.resteasy.plugins.cache.server;
1
2 import java.util.List;
3 import java.util.Map;
41
52 import javax.ws.rs.core.CacheControl;
63 import javax.ws.rs.core.MediaType;
129 */
1310 public interface ServerCache
1411 {
15 public static boolean mayVary(Entry cached, MultivaluedMap<String, String> current) {
16 boolean mayVary = false;
17 for (Map.Entry<String, List<String>> entry : cached.getVaryHeaders().entrySet()) {
18 String headerName = entry.getKey();
19 mayVary |= !(current.containsKey(headerName) && current.get(headerName).containsAll(entry.getValue()));
20 }
21 return mayVary;
22 }
23
2412 public static interface Entry
2513 {
2614 int getExpirationInSeconds();
3220 byte[] getCached();
3321
3422 MultivaluedMap<String, Object> getHeaders();
35
36 MultivaluedMap<String, String> getVaryHeaders();
3723 }
3824
39 Entry add(String uri, MediaType mediaType, CacheControl cc, MultivaluedMap<String, Object> headers, byte[] entity, String etag, MultivaluedMap<String, String> varyHeaders);
25 Entry add(String uri, MediaType mediaType, CacheControl cc, MultivaluedMap<String, Object> headers, byte[] entity, String etag);
4026
41 Entry get(String uri, MediaType accept, MultivaluedMap<String, String> headers);
27 Entry get(String uri, MediaType accept);
4228
4329 void remove(String uri);
4430
4949 if (acceptableMediaTypes != null && acceptableMediaTypes.size() > 0)
5050 {
5151 // only see if most desired is cached.
52 entry = cache.get(key, acceptableMediaTypes.get(0), request.getHeaders());
52 entry = cache.get(key, acceptableMediaTypes.get(0));
5353 }
5454 else
5555 {
56 entry = cache.get(key, MediaType.WILDCARD_TYPE, request.getHeaders());
56 entry = cache.get(key, MediaType.WILDCARD_TYPE);
5757 }
5858 if (entry != null)
5959 {
1010 import javax.ws.rs.core.Context;
1111 import javax.ws.rs.core.EntityTag;
1212 import javax.ws.rs.core.HttpHeaders;
13 import javax.ws.rs.core.MultivaluedHashMap;
14 import javax.ws.rs.core.MultivaluedMap;
1513 import javax.ws.rs.core.Request;
1614 import javax.ws.rs.core.Response;
1715 import javax.ws.rs.ext.WriterInterceptor;
138136 }
139137
140138 if (!cc.isPrivate() && !cc.isNoStore()) {
141 MultivaluedMap<String, String> varyHeaders = new MultivaluedHashMap<>();
142 if (context.getHeaders().containsKey(HttpHeaders.VARY)) {
143 for (Object varyHeader : context.getHeaders().get(HttpHeaders.VARY)) {
144 if (request.getMutableHeaders().containsKey(varyHeader)) {
145 varyHeaders.addAll((String) varyHeader, request.getMutableHeaders().get(varyHeader));
146 }
147 }
148 }
149 cache.add(request.getUri().getRequestUri().toString(), context.getMediaType(), cc, context.getHeaders(), entity, etag, varyHeaders);
139 cache.add(request.getUri().getRequestUri().toString(), context.getMediaType(), cc, context.getHeaders(), entity, etag);
150140 }
151141
152142 // check to see if ETags are the same. If they are, we don't need to send a response back.
2525 private final long timestamp = System.currentTimeMillis();
2626 private final MultivaluedMap<String, Object> headers;
2727 private String etag;
28 private final MultivaluedMap<String, String> varyHeaders;
2928
30 private CacheEntry(MultivaluedMap<String, Object> headers, byte[] cached, int expires, String etag, MultivaluedMap<String, String> varyHeaders)
29 private CacheEntry(MultivaluedMap<String, Object> headers, byte[] cached, int expires, String etag)
3130 {
3231 this.cached = cached;
3332 this.expires = expires;
3433 this.headers = headers;
3534 this.etag = etag;
36 this.varyHeaders = varyHeaders;
3735 }
3836
3937 public int getExpirationInSeconds()
5654 return headers;
5755 }
5856
59 public MultivaluedMap<String, String> getVaryHeaders()
60 {
61 return varyHeaders;
62 }
63
6457 public byte[] getCached()
6558 {
6659 return cached;
7164
7265 private Map<String, Map<MediaType, CacheEntry>> cache = new ConcurrentHashMap<String, Map<MediaType, CacheEntry>>();
7366
74 public Entry get(String uri, MediaType accept, MultivaluedMap<String, String> headers)
67 public Entry get(String uri, MediaType accept)
7568 {
7669 Map<MediaType, CacheEntry> entry = cache.get(uri);
7770 if (entry == null || entry.isEmpty()) return null;
7871 for (Map.Entry<MediaType, CacheEntry> produce : entry.entrySet())
7972 {
80 if (accept.isCompatible(produce.getKey()) && !ServerCache.mayVary(produce.getValue(), headers)) return produce.getValue();
73 if (accept.isCompatible(produce.getKey())) return produce.getValue();
8174 }
8275 return null;
8376 }
8477
85 public Entry add(String uri, MediaType mediaType, CacheControl cc, MultivaluedMap<String, Object> headers, byte[] entity, String etag, MultivaluedMap<String, String> varyHeaders)
78 public Entry add(String uri, MediaType mediaType, CacheControl cc, MultivaluedMap<String, Object> headers, byte[] entity, String etag)
8679 {
87 CacheEntry cacheEntry = new CacheEntry(headers, entity, cc.getMaxAge(), etag, varyHeaders);
80 CacheEntry cacheEntry = new CacheEntry(headers, entity, cc.getMaxAge(), etag);
8881 Map<MediaType, CacheEntry> entry = cache.get(uri);
8982 if (entry == null)
9083 {
55 import java.util.Hashtable;
66
77 import javax.ws.rs.Consumes;
8 import javax.ws.rs.DefaultValue;
98 import javax.ws.rs.GET;
10 import javax.ws.rs.HeaderParam;
119 import javax.ws.rs.PUT;
1210 import javax.ws.rs.Path;
1311 import javax.ws.rs.Produces;
14 import javax.ws.rs.client.Client;
15 import javax.ws.rs.client.ClientBuilder;
16 import javax.ws.rs.client.Entity;
17 import javax.ws.rs.client.Invocation.Builder;
1812 import javax.ws.rs.core.HttpHeaders;
1913 import javax.ws.rs.core.Response;
2014
2115 import org.apache.commons.io.FileUtils;
2216 import org.jboss.resteasy.annotations.cache.Cache;
17 import org.jboss.resteasy.client.ClientRequest;
18 import org.jboss.resteasy.client.ClientResponse;
2319 import org.jboss.resteasy.core.Dispatcher;
2420 import org.jboss.resteasy.plugins.cache.server.ServerCacheFeature;
2521 import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
2622 import org.jboss.resteasy.spi.ResteasyDeployment;
2723 import org.jboss.resteasy.test.TestPortProvider;
2824 import org.junit.After;
29 import org.junit.AfterClass;
3025 import org.junit.Assert;
3126 import org.junit.Before;
32 import org.junit.BeforeClass;
3327 import org.junit.Test;
3428
3529 /**
5044 private static NettyJaxrsServer server;
5145 protected static ResteasyDeployment deployment;
5246 protected static Dispatcher dispatcher;
53 protected static Client client;
5447
5548 @Path("/cache")
5649 public static class TestResource
9992 count++;
10093 return "stuff";
10194 }
102
103 @GET
104 @Produces("text/plain")
105 @Path("vary")
106 @Cache(maxAge = 2)
107 public Response getVary(@HeaderParam("X-Test-Vary") @DefaultValue("default") String testVary)
108 {
109 count++;
110 return Response.ok(testVary).header(HttpHeaders.VARY, "X-Test-Vary").header("X-Count", count).build();
111 }
11295 }
11396
11497 @Path("/cache")
120103
121104 }
122105
123 @BeforeClass
124 public static void beforeClass()
125 {
126 client = ClientBuilder.newClient();
127 }
128
129 @AfterClass
130 public static void afterClass()
131 {
132 client.close();
133 }
134
106
135107 @Before
136108 public void before() throws Exception
137109 {
172144 count = 0;
173145 String etag = null;
174146 {
175 Builder request = client.target(generateURL("/cache/stuff")).request();
176 Response response = request.get();
177 Assert.assertEquals(200, response.getStatus());
178 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
179 Assert.assertNotNull(cc);
180 etag = response.getHeaderString(HttpHeaders.ETAG);
181 Assert.assertNotNull(etag);
182 Assert.assertEquals(response.readEntity(String.class), "stuff");
147 ClientRequest request = new ClientRequest(generateURL("/cache/stuff"));
148 ClientResponse<String> response = request.get(String.class);
149 Assert.assertEquals(200, response.getStatus());
150 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
151 Assert.assertNotNull(cc);
152 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
153 Assert.assertNotNull(etag);
154 Assert.assertEquals(response.getEntity(), "stuff");
183155 }
184156
185157
186158 Thread.sleep(2000);
187159
188160 {
189 Builder request = client.target(generateURL("/cache/stuff")).request();
161 ClientRequest request = new ClientRequest(generateURL("/cache/stuff"));
190162 request.header(HttpHeaders.IF_NONE_MATCH, etag);
191 Response response = request.get();
163 ClientResponse<String> response = request.get(String.class);
192164 Assert.assertEquals(Response.Status.NOT_MODIFIED.getStatusCode(), response.getStatus());
193165 Assert.assertEquals(2, count);
194 response.close();
195166 }
196167 }
197168
202173 count = 0;
203174 String etag = null;
204175 {
205 Builder request = client.target(generateURL("/cache")).request();
206 Response response = request.get();
207 Assert.assertEquals(200, response.getStatus());
208 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
209 Assert.assertNotNull(cc);
210 etag = response.getHeaderString(HttpHeaders.ETAG);
211 Assert.assertNotNull(etag);
212 Assert.assertEquals(response.readEntity(String.class), "hello world" + 1);
213 }
214
215
216 {
217 Builder request = client.target(generateURL("/cache")).request();
218 Response response = request.get();
219 Assert.assertEquals(200, response.getStatus());
220 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
221 Assert.assertNotNull(cc);
222 etag = response.getHeaderString(HttpHeaders.ETAG);
223 Assert.assertNotNull(etag);
224 Assert.assertEquals(response.readEntity(String.class), "hello world" + 1);
176 ClientRequest request = new ClientRequest(generateURL("/cache"));
177 ClientResponse<String> response = request.get(String.class);
178 Assert.assertEquals(200, response.getStatus());
179 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
180 Assert.assertNotNull(cc);
181 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
182 Assert.assertNotNull(etag);
183 Assert.assertEquals(response.getEntity(), "hello world" + 1);
184 }
185
186
187 {
188 ClientRequest request = new ClientRequest(generateURL("/cache"));
189 ClientResponse<String> response = request.get(String.class);
190 Assert.assertEquals(200, response.getStatus());
191 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
192 Assert.assertNotNull(cc);
193 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
194 Assert.assertNotNull(etag);
195 Assert.assertEquals(response.getEntity(), "hello world" + 1);
225196 }
226197 // test if-not-match
227198 {
228 Builder request = client.target(generateURL("/cache")).request();
199 ClientRequest request = new ClientRequest(generateURL("/cache"));
229200 request.header(HttpHeaders.IF_NONE_MATCH, etag);
230 Response response = request.get();
201 ClientResponse<String> response = request.get(String.class);
231202 Assert.assertEquals(Response.Status.NOT_MODIFIED.getStatusCode(), response.getStatus());
232 response.close();
233203 }
234204
235205
236206 Thread.sleep(2000);
237207
238208 {
239 Builder request = client.target(generateURL("/cache")).request();
240 Response response = request.get();
241 Assert.assertEquals(200, response.getStatus());
242 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
243 Assert.assertNotNull(cc);
244 etag = response.getHeaderString(HttpHeaders.ETAG);
245 Assert.assertNotNull(etag);
246 Assert.assertEquals(response.readEntity(String.class), "hello world" + 2);
247 }
248
249 {
250 Builder request = client.target(generateURL("/cache")).request();
251 Response response = request.get();
252 Assert.assertEquals(200, response.getStatus());
253 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
254 Assert.assertNotNull(cc);
255 etag = response.getHeaderString(HttpHeaders.ETAG);
256 Assert.assertNotNull(etag);
257 Assert.assertEquals(response.readEntity(String.class), "hello world" + 2);
258 }
259
260 {
261 Builder request = client.target(generateURL("/cache")).request();
262 Response response = request.put(Entity.entity("yo", "text/plain"));
263 response.close();
264 }
265 {
266 Builder request = client.target(generateURL("/cache")).request();
267 Response response = request.get();
268 Assert.assertEquals(200, response.getStatus());
269 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
270 Assert.assertNotNull(cc);
271 etag = response.getHeaderString(HttpHeaders.ETAG);
272 Assert.assertNotNull(etag);
273 Assert.assertEquals(response.readEntity(String.class), "hello world" + 3);
209 ClientRequest request = new ClientRequest(generateURL("/cache"));
210 ClientResponse<String> response = request.get(String.class);
211 Assert.assertEquals(200, response.getStatus());
212 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
213 Assert.assertNotNull(cc);
214 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
215 Assert.assertNotNull(etag);
216 Assert.assertEquals(response.getEntity(), "hello world" + 2);
217 }
218
219 {
220 ClientRequest request = new ClientRequest(generateURL("/cache"));
221 ClientResponse<String> response = request.get(String.class);
222 Assert.assertEquals(200, response.getStatus());
223 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
224 Assert.assertNotNull(cc);
225 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
226 Assert.assertNotNull(etag);
227 Assert.assertEquals(response.getEntity(), "hello world" + 2);
228 }
229
230 {
231 ClientRequest request = new ClientRequest(generateURL("/cache"));
232 ClientResponse response = request.body("text/plain", "yo").put();
233 Assert.assertEquals(204, response.getStatus());
234 }
235 {
236 ClientRequest request = new ClientRequest(generateURL("/cache"));
237 ClientResponse<String> response = request.get(String.class);
238 Assert.assertEquals(200, response.getStatus());
239 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
240 Assert.assertNotNull(cc);
241 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
242 Assert.assertNotNull(etag);
243 Assert.assertEquals(response.getEntity(), "hello world" + 3);
274244 }
275245 }
276246
283253 htmlCount = 0;
284254 String etag = null;
285255 {
286 Builder request = client.target(generateURL("/cache/accepts")).request().accept("text/plain");
287 Response response = request.get();
288 Assert.assertEquals(200, response.getStatus());
289 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
290 Assert.assertNotNull(cc);
291 etag = response.getHeaderString(HttpHeaders.ETAG);
292 Assert.assertNotNull(etag);
293 Assert.assertEquals(response.readEntity(String.class), "plain" + 1);
294 }
295
296 {
297 Builder request = client.target(generateURL("/cache/accepts")).request().accept("text/plain");
298 Response response = request.get();
299 Assert.assertEquals(200, response.getStatus());
300 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
301 Assert.assertNotNull(cc);
302 etag = response.getHeaderString(HttpHeaders.ETAG);
303 Assert.assertNotNull(etag);
304 Assert.assertEquals(response.readEntity(String.class), "plain" + 1);
305 }
306
307 {
308 Builder request = client.target(generateURL("/cache/accepts")).request().accept("text/html");
309 Response response = request.get();
310 Assert.assertEquals(200, response.getStatus());
311 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
312 Assert.assertNotNull(cc);
313 etag = response.getHeaderString(HttpHeaders.ETAG);
314 Assert.assertNotNull(etag);
315 Assert.assertEquals(response.readEntity(String.class), "html" + 1);
316 }
317 {
318 Builder request = client.target(generateURL("/cache/accepts")).request().accept("text/html");
319 Response response = request.get();
320 Assert.assertEquals(200, response.getStatus());
321 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
322 Assert.assertNotNull(cc);
323 etag = response.getHeaderString(HttpHeaders.ETAG);
324 Assert.assertNotNull(etag);
325 Assert.assertEquals(response.readEntity(String.class), "html" + 1);
256 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
257 request.accept("text/plain");
258 ClientResponse<String> response = request.get(String.class);
259 Assert.assertEquals(200, response.getStatus());
260 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
261 Assert.assertNotNull(cc);
262 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
263 Assert.assertNotNull(etag);
264 Assert.assertEquals(response.getEntity(), "plain" + 1);
265 }
266
267 {
268 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
269 request.accept("text/plain");
270 ClientResponse<String> response = request.get(String.class);
271 Assert.assertEquals(200, response.getStatus());
272 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
273 Assert.assertNotNull(cc);
274 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
275 Assert.assertNotNull(etag);
276 Assert.assertEquals(response.getEntity(), "plain" + 1);
277 }
278
279 {
280 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
281 request.accept("text/html");
282 ClientResponse<String> response = request.get(String.class);
283 Assert.assertEquals(200, response.getStatus());
284 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
285 Assert.assertNotNull(cc);
286 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
287 Assert.assertNotNull(etag);
288 Assert.assertEquals(response.getEntity(), "html" + 1);
289 }
290 {
291 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
292 request.accept("text/html");
293 ClientResponse<String> response = request.get(String.class);
294 Assert.assertEquals(200, response.getStatus());
295 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
296 Assert.assertNotNull(cc);
297 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
298 Assert.assertNotNull(etag);
299 Assert.assertEquals(response.getEntity(), "html" + 1);
326300 }
327301 }
328302
334308 htmlCount = 0;
335309 String etag = null;
336310 {
337 Builder request = client.target(generateURL("/cache/accepts")).request().accept("text/plain");
338 Response response = request.get();
339 Assert.assertEquals(200, response.getStatus());
340 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
341 Assert.assertNotNull(cc);
342 etag = response.getHeaderString(HttpHeaders.ETAG);
343 Assert.assertNotNull(etag);
344 Assert.assertEquals(response.readEntity(String.class), "plain" + 1);
345 }
346
347 {
348 Builder request = client.target(generateURL("/cache/accepts")).request().accept("text/html");
349 Response response = request.get();
350 Assert.assertEquals(200, response.getStatus());
351 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
352 Assert.assertNotNull(cc);
353 etag = response.getHeaderString(HttpHeaders.ETAG);
354 Assert.assertNotNull(etag);
355 Assert.assertEquals(response.readEntity(String.class), "html" + 1);
356 }
357
358 {
359 Builder request = client.target(generateURL("/cache/accepts")).request();
311 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
312 request.accept("text/plain");
313 ClientResponse<String> response = request.get(String.class);
314 Assert.assertEquals(200, response.getStatus());
315 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
316 Assert.assertNotNull(cc);
317 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
318 Assert.assertNotNull(etag);
319 Assert.assertEquals(response.getEntity(), "plain" + 1);
320 }
321
322 {
323 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
324 request.accept("text/html");
325 ClientResponse<String> response = request.get(String.class);
326 Assert.assertEquals(200, response.getStatus());
327 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
328 Assert.assertNotNull(cc);
329 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
330 Assert.assertNotNull(etag);
331 Assert.assertEquals(response.getEntity(), "html" + 1);
332 }
333
334 {
335 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
360336 request.header(HttpHeaders.ACCEPT, "text/html;q=0.5, text/plain");
361 Response response = request.get();
362 Assert.assertEquals(200, response.getStatus());
363 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
364 Assert.assertNotNull(cc);
365 etag = response.getHeaderString(HttpHeaders.ETAG);
366 Assert.assertNotNull(etag);
367 Assert.assertEquals(response.readEntity(String.class), "plain" + 1);
368 }
369 {
370 Builder request = client.target(generateURL("/cache/accepts")).request();
337 ClientResponse<String> response = request.get(String.class);
338 Assert.assertEquals(200, response.getStatus());
339 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
340 Assert.assertNotNull(cc);
341 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
342 Assert.assertNotNull(etag);
343 Assert.assertEquals(response.getEntity(), "plain" + 1);
344 }
345 {
346 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
371347 request.header(HttpHeaders.ACCEPT, "text/plain;q=0.5, text/html");
372 Response response = request.get();
373 Assert.assertEquals(200, response.getStatus());
374 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
375 Assert.assertNotNull(cc);
376 etag = response.getHeaderString(HttpHeaders.ETAG);
377 Assert.assertNotNull(etag);
378 Assert.assertEquals(response.readEntity(String.class), "html" + 1);
348 ClientResponse<String> response = request.get(String.class);
349 Assert.assertEquals(200, response.getStatus());
350 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
351 Assert.assertNotNull(cc);
352 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
353 Assert.assertNotNull(etag);
354 Assert.assertEquals(response.getEntity(), "html" + 1);
379355 }
380356 }
381357
387363 htmlCount = 0;
388364 String etag = null;
389365 {
390 Builder request = client.target(generateURL("/cache/accepts")).request().accept("text/plain");
391 Response response = request.get();
392 Assert.assertEquals(200, response.getStatus());
393 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
394 Assert.assertNotNull(cc);
395 etag = response.getHeaderString(HttpHeaders.ETAG);
396 Assert.assertNotNull(etag);
397 Assert.assertEquals(response.readEntity(String.class), "plain" + 1);
366 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
367 request.accept("text/plain");
368 ClientResponse<String> response = request.get(String.class);
369 Assert.assertEquals(200, response.getStatus());
370 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
371 Assert.assertNotNull(cc);
372 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
373 Assert.assertNotNull(etag);
374 Assert.assertEquals(response.getEntity(), "plain" + 1);
398375 }
399376
400377 // we test that the preferred can be handled
401378 {
402 Builder request = client.target(generateURL("/cache/accepts")).request();
379 ClientRequest request = new ClientRequest(generateURL("/cache/accepts"));
403380 request.header(HttpHeaders.ACCEPT, "text/plain;q=0.5, text/html");
404 Response response = request.get();
405 Assert.assertEquals(200, response.getStatus());
406 String cc = response.getHeaderString(HttpHeaders.CACHE_CONTROL);
407 Assert.assertNotNull(cc);
408 etag = response.getHeaderString(HttpHeaders.ETAG);
409 Assert.assertNotNull(etag);
410 Assert.assertEquals(response.readEntity(String.class), "html" + 1);
411 }
412 }
413
414 @Test
415 public void testVary() throws Exception {
416 int cachedCount;
417 {
418 Builder request = client.target(generateURL("/cache/vary")).request();
419 Response foo = request.accept("text/plain").header("X-Test-Vary", "foo").get();
420 Assert.assertEquals("foo", foo.readEntity(String.class));
421 cachedCount = Integer.parseInt(foo.getHeaderString("X-Count"));
422 }
423 {
424 Builder request = client.target(generateURL("/cache/vary")).request();
425 Response bar = request.accept("text/plain").header("X-Test-Vary", "bar").get();
426 Assert.assertEquals("bar", bar.readEntity(String.class));
427 }
428 {
429 Builder request = client.target(generateURL("/cache/vary")).request();
430 Response foo = request.accept("text/plain").header("X-Test-Vary", "foo").get();
431 Assert.assertEquals("foo", foo.readEntity(String.class));
432 int currentCount = Integer.parseInt(foo.getHeaderString("X-Count"));
433 Assert.assertEquals(cachedCount, currentCount);
434 }
381 ClientResponse<String> response = request.get(String.class);
382 Assert.assertEquals(200, response.getStatus());
383 String cc = response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
384 Assert.assertNotNull(cc);
385 etag = response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
386 Assert.assertNotNull(etag);
387 Assert.assertEquals(response.getEntity(), "html" + 1);
388 }
435389 }
436390 }
77 import java.io.InputStreamReader;
88
99 import javax.ws.rs.Consumes;
10 import javax.ws.rs.DefaultValue;
1110 import javax.ws.rs.GET;
12 import javax.ws.rs.HeaderParam;
1311 import javax.ws.rs.PUT;
1412 import javax.ws.rs.Path;
1513 import javax.ws.rs.Produces;
151149 count++;
152150 return "stuff";
153151 }
154
155 @GET
156 @Produces("text/plain")
157 @Path("vary")
158 @Cache(maxAge = 2)
159 public Response getVary(@HeaderParam("X-Test-Vary") @DefaultValue("default") String testVary)
160 {
161 count++;
162 return Response.ok(testVary).header(HttpHeaders.VARY, "X-Test-Vary").header("X-Count", count).build();
163 }
164152 }
165153
166154 @Path("/cache")
425413 Assert.assertNotNull(etag);
426414 Assert.assertEquals(response.readEntity(String.class), "html" + 1);
427415 }
428 }
429
430 @Test
431 public void testVary() throws Exception {
432 int cachedCount;
433 {
434 Builder request = client.target(generateURL("/cache/vary")).request();
435 Response foo = request.accept("text/plain").header("X-Test-Vary", "foo").get();
436 Assert.assertEquals("foo", foo.readEntity(String.class));
437 cachedCount = Integer.parseInt(foo.getHeaderString("X-Count"));
438 }
439 {
440 Builder request = client.target(generateURL("/cache/vary")).request();
441 Response bar = request.accept("text/plain").header("X-Test-Vary", "bar").get();
442 Assert.assertEquals("bar", bar.readEntity(String.class));
443 }
444 {
445 Builder request = client.target(generateURL("/cache/vary")).request();
446 Response foo = request.accept("text/plain").header("X-Test-Vary", "foo").get();
447 Assert.assertEquals("foo", foo.readEntity(String.class));
448 int currentCount = Integer.parseInt(foo.getHeaderString("X-Count"));
449 Assert.assertEquals(cachedCount, currentCount);
450 }
451416 }
452417
453418 @Test
475440
476441 }
477442
478 }
443 }
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 </parent>
88 <artifactId>resteasy-cdi</artifactId>
99 <name>RESTEasy CDI integration module</name>
1717
1818 <dependency>
1919 <groupId>org.jboss.spec.javax.ws.rs</groupId>
20 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
20 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
2121 </dependency>
2222
2323 <dependency>
2929 <groupId>javax.enterprise</groupId>
3030 <artifactId>cdi-api</artifactId>
3131 </dependency>
32
32
3333 <dependency>
3434 <groupId>javax.validation</groupId>
3535 <artifactId>validation-api</artifactId>
3636 <version>1.1.0.Final</version>
3737 </dependency>
38
38
3939 <dependency>
4040 <groupId>org.jboss.spec.javax.ejb</groupId>
4141 <artifactId>jboss-ejb-api_3.2_spec</artifactId>
5858 <dependency>
5959 <groupId>org.jboss.logging</groupId>
6060 <artifactId>jboss-logging-processor</artifactId>
61 </dependency>
61 </dependency>
62
63 <dependency>
64 <groupId>org.eclipse.microprofile.rest.client</groupId>
65 <artifactId>microprofile-rest-client-api</artifactId>
66 <scope>provided</scope>
67 </dependency>
68
69 <dependency>
70 <groupId>org.eclipse.microprofile.config</groupId>
71 <artifactId>microprofile-config-api</artifactId>
72 <scope>provided</scope>
73 </dependency>
74
6275 </dependencies>
6376
6477 <profiles>
0 package org.jboss.resteasy.cdi.microprofile;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4 import java.net.MalformedURLException;
5 import java.net.URL;
6 import java.util.ArrayList;
7 import java.util.Collections;
8 import java.util.HashSet;
9 import java.util.List;
10 import java.util.Set;
11
12 import javax.enterprise.context.Dependent;
13 import javax.enterprise.context.spi.CreationalContext;
14 import javax.enterprise.inject.Any;
15 import javax.enterprise.inject.Default;
16 import javax.enterprise.inject.spi.Bean;
17 import javax.enterprise.inject.spi.BeanManager;
18 import javax.enterprise.inject.spi.InjectionPoint;
19 import javax.enterprise.inject.spi.PassivationCapable;
20 import javax.enterprise.util.AnnotationLiteral;
21
22 import org.eclipse.microprofile.config.Config;
23 import org.eclipse.microprofile.config.ConfigProvider;
24 import org.eclipse.microprofile.rest.client.RestClientBuilder;
25 import org.eclipse.microprofile.rest.client.inject.RestClient;
26
27 public class RestClientDelegateBean implements Bean<Object>, PassivationCapable {
28
29 public static final String REST_URL_FORMAT = "%s/mp-rest/url";
30
31 public static final String REST_SCOPE_FORMAT = "%s/mp-rest/scope";
32
33 private final Class<?> proxyType;
34
35 private final Class<? extends Annotation> scope;
36
37 private final BeanManager beanManager;
38
39 private final Config config;
40
41 RestClientDelegateBean(Class<?> proxyType, BeanManager beanManager) {
42 this.proxyType = proxyType;
43 this.beanManager = beanManager;
44 this.config = ConfigProvider.getConfig(); // TODO should this be injected?
45 this.scope = this.resolveScope();
46 }
47 @Override
48 public String getId() {
49 return proxyType.getName();
50 }
51
52 @Override
53 public Class<?> getBeanClass() {
54 return proxyType;
55 }
56
57 @Override
58 public Set<InjectionPoint> getInjectionPoints() {
59 return Collections.emptySet();
60 }
61
62 @Override
63 public boolean isNullable() {
64 return false;
65 }
66
67 @Override
68 public Object create(CreationalContext<Object> creationalContext) {
69 RestClientBuilder builder = RestClientBuilder.newBuilder();
70 String baseUrl = getBaseUrl();
71 try {
72 return builder.baseUrl(new URL(baseUrl)).build(proxyType);
73 } catch (MalformedURLException e) {
74 throw new IllegalArgumentException("The value of URL was invalid "+baseUrl);
75 }
76 }
77
78 @Override
79 public void destroy(Object instance, CreationalContext<Object> creationalContext) {
80
81 }
82
83 @Override
84 public Set<Type> getTypes() {
85 return Collections.singleton(proxyType);
86 }
87
88 @Override
89 public Set<Annotation> getQualifiers() {
90 //return Collections.singleton(RestClient.LITERAL);
91 Set<Annotation> qualifiers = new HashSet<Annotation>();
92 qualifiers.add( new AnnotationLiteral<Default>() {} );
93 qualifiers.add( new AnnotationLiteral<Any>() {} );
94 qualifiers.add(RestClient.LITERAL);
95 return qualifiers;
96 }
97
98 @Override
99 public Class<? extends Annotation> getScope() {
100 return scope;
101 }
102
103 @Override
104 public String getName() {
105 return proxyType.getName();
106 }
107
108 @Override
109 public Set<Class<? extends Annotation>> getStereotypes() {
110 return Collections.emptySet();
111 }
112
113 @Override
114 public boolean isAlternative() {
115 return false;
116 }
117
118 private String getBaseUrl() {
119 String property = String.format(REST_URL_FORMAT, proxyType.getName());
120 return config.getValue(property, String.class);
121 }
122
123 private Class<? extends Annotation> resolveScope() {
124
125 String property = String.format(REST_SCOPE_FORMAT, proxyType.getName());
126 String configuredScope = config.getOptionalValue(property, String.class).orElse(null);
127
128 if(configuredScope != null) {
129 try {
130 return (Class<? extends Annotation>)Class.forName(configuredScope);
131 } catch (Exception e) {
132 throw new IllegalArgumentException("Invalid scope: " + configuredScope ,e);
133 }
134 }
135
136 List<Annotation> possibleScopes = new ArrayList<>();
137 Annotation[] annotations = proxyType.getDeclaredAnnotations();
138 for(Annotation annotation : annotations) {
139 if(beanManager.isScope(annotation.annotationType())) {
140 possibleScopes.add(annotation);
141 }
142 }
143 if(possibleScopes.isEmpty()) {
144 return Dependent.class;
145 }
146 else if(possibleScopes.size() == 1) {
147 return possibleScopes.get(0).annotationType();
148 }
149 else {
150 throw new IllegalArgumentException("Ambiguous scope definition on "+ proxyType +": " + possibleScopes);
151 }
152 }
153 }
0 package org.jboss.resteasy.cdi.microprofile;
1
2
3 import java.util.LinkedHashSet;
4 import java.util.Set;
5
6 import javax.enterprise.event.Observes;
7 import javax.enterprise.inject.spi.AfterBeanDiscovery;
8 import javax.enterprise.inject.spi.AfterDeploymentValidation;
9 import javax.enterprise.inject.spi.BeanManager;
10 import javax.enterprise.inject.spi.Extension;
11 import javax.enterprise.inject.spi.ProcessAnnotatedType;
12 import javax.enterprise.inject.spi.WithAnnotations;
13
14 import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
15
16 /**
17 * Created by hbraun on 15.01.18.
18 */
19 public class RestClientExtension implements Extension {
20
21 private static Set<Class<?>> proxyTypes = new LinkedHashSet<>();
22
23 private static Set<Throwable> errors = new LinkedHashSet<>();
24
25 public void registerClient(@Observes @WithAnnotations({RegisterRestClient.class}) ProcessAnnotatedType<?> pat) {
26 Class<?> typeDef = pat.getAnnotatedType().getJavaClass();
27 if(typeDef.isInterface()) {
28 proxyTypes.add(typeDef);
29 pat.veto();
30 } else {
31 errors.add(new IllegalArgumentException("Rest client needs to be interface: " + typeDef));
32 }
33 }
34
35 public void createProxy(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
36 for (Class<?> proxyType : proxyTypes) {
37 afterBeanDiscovery.addBean(new RestClientDelegateBean(proxyType, beanManager));
38 }
39 }
40
41 public void reportErrors(@Observes AfterDeploymentValidation afterDeploymentValidation) {
42 for (Throwable error : errors) {
43 afterDeploymentValidation.addDeploymentProblem(error);
44 }
45 }
46 }
0 org.jboss.resteasy.cdi.ResteasyCdiExtension
0 org.jboss.resteasy.cdi.ResteasyCdiExtension
1 org.jboss.resteasy.cdi.microprofile.RestClientExtension
44 <parent>
55 <artifactId>resteasy-jaxrs-all</artifactId>
66 <groupId>org.jboss.resteasy</groupId>
7 <version>3.1.4.Final</version>
7 <version>3.5.0.Final</version>
88 <relativePath>../pom.xml</relativePath>
99 </parent>
1010
2121 <groupId>org.jboss.resteasy</groupId>
2222 <artifactId>resteasy-jaxrs</artifactId>
2323 <version>${project.version}</version>
24 </dependency>
25 <dependency>
26 <groupId>org.jboss.resteasy</groupId>
27 <artifactId>resteasy-jaxrs-services</artifactId>
28 <version>${project.version}</version>
29 </dependency>
30
24 <exclusions>
25 <exclusion>
26 <groupId>org.jboss.spec.javax.ws.rs</groupId>
27 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
28 </exclusion>
29 </exclusions>
30 </dependency>
3131 <dependency>
3232 <groupId>org.jboss.logging</groupId>
3333 <artifactId>jboss-logging</artifactId>
34 </dependency>
34 </dependency>
3535 <dependency>
3636 <groupId>org.jboss.logging</groupId>
3737 <artifactId>jboss-logging-annotations</artifactId>
4444 <groupId>org.apache.httpcomponents</groupId>
4545 <artifactId>httpclient</artifactId>
4646 </dependency>
47 <dependency>
48 <groupId>org.apache.httpcomponents</groupId>
49 <artifactId>httpasyncclient</artifactId>
50 <optional>true</optional>
51 </dependency>
52 <dependency>
53 <groupId>org.glassfish</groupId>
54 <artifactId>javax.json</artifactId>
55 <scope>provided</scope>
56 </dependency>
4757 </dependencies>
48
49 <profiles>
58 <profiles>
59 <profile>
60 <id>jaxrs20</id>
61 <activation>
62 <property>
63 <name>jaxrs20</name>
64 </property>
65 </activation>
66 <dependencies>
67 <dependency>
68 <groupId>org.jboss.spec.javax.ws.rs</groupId>
69 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
70 </dependency>
71 </dependencies>
72 <build>
73 <directory>target/jaxrs20</directory>
74 <plugins>
75 <plugin>
76 <groupId>org.codehaus.mojo</groupId>
77 <artifactId>build-helper-maven-plugin</artifactId>
78 <version>3.0.0</version>
79 <executions>
80 <execution>
81 <id>add-jaxrs20-sources</id>
82 <phase>generate-sources</phase>
83 <goals>
84 <goal>add-source</goal>
85 </goals>
86 <inherited>false</inherited>
87 <configuration>
88 <sources>
89 <source>${basedir}/src/main/jaxrs20/</source>
90 </sources>
91 </configuration>
92 </execution>
93 </executions>
94 </plugin>
95 <plugin>
96 <groupId>org.apache.maven.plugins</groupId>
97 <artifactId>maven-jar-plugin</artifactId>
98 <configuration>
99 <classifier>jaxrs20</classifier>
100 </configuration>
101 </plugin>
102 <plugin>
103 <groupId>org.apache.maven.plugins</groupId>
104 <artifactId>maven-source-plugin</artifactId>
105 <configuration>
106 <classifier>jaxrs20-sources</classifier>
107 </configuration>
108 </plugin>
109 </plugins>
110 </build>
111 </profile>
112 <profile>
113 <id>jaxrs21</id>
114 <activation>
115 <property>
116 <name>!jaxrs20</name>
117 </property>
118 </activation>
119 <dependencies>
120 <dependency>
121 <groupId>org.jboss.spec.javax.ws.rs</groupId>
122 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
123 </dependency>
124 </dependencies>
125 <build>
126 <plugins>
127 <plugin>
128 <groupId>org.codehaus.mojo</groupId>
129 <artifactId>build-helper-maven-plugin</artifactId>
130 <version>3.0.0</version>
131 <executions>
132 <execution>
133 <id>add-jaxrs21-sources</id>
134 <phase>generate-sources</phase>
135 <goals>
136 <goal>add-source</goal>
137 </goals>
138 <inherited>false</inherited>
139 <configuration>
140 <sources>
141 <source>${basedir}/src/main/jaxrs21/</source>
142 </sources>
143 </configuration>
144 </execution>
145 </executions>
146 </plugin>
147 </plugins>
148 </build>
149 </profile>
50150 <profile>
51151 <id>i18n</id>
52152 <activation>
59159 <plugin>
60160 <groupId>org.apache.maven.plugins</groupId>
61161 <artifactId>maven-resources-plugin</artifactId>
62 <executions>
162 <executions>
63163 <execution>
64164 <id>copy-resources</id>
65165 <phase>initialize</phase>
67167 <goal>copy-resources</goal>
68168 </goals>
69169 <configuration>
70 <outputDirectory>${basedir}/src/main/resources/org/jboss/resteasy/client/jaxrs/i18n</outputDirectory>
170 <outputDirectory>
171 ${basedir}/src/main/resources/org/jboss/resteasy/client/jaxrs/i18n
172 </outputDirectory>
71173 <resources>
72174 <resource>
73175 <directory>${basedir}/src/test/resources/i18n</directory>
83185 </plugin>
84186
85187 <plugin>
86 <groupId>org.apache.maven.plugins</groupId>
87 <artifactId>maven-surefire-plugin</artifactId>
88 <executions>
89 <execution>
90 <id>i18</id>
91 <phase>test</phase>
92 <goals>
93 <goal>test</goal>
94 </goals>
95 <configuration>
96 <skip>false</skip>
97 <reuseForks>false</reuseForks>
98 <includes>
99 <include>**/I18nTestMessages_*.java</include>
100 </includes>
101 </configuration>
102 </execution>
103 </executions>
188 <groupId>org.apache.maven.plugins</groupId>
189 <artifactId>maven-surefire-plugin</artifactId>
190 <executions>
191 <execution>
192 <id>i18</id>
193 <phase>test</phase>
194 <goals>
195 <goal>test</goal>
196 </goals>
197 <configuration>
198 <skip>false</skip>
199 <reuseForks>false</reuseForks>
200 <includes>
201 <include>**/I18nTestMessages_*.java</include>
202 </includes>
203 </configuration>
204 </execution>
205 </executions>
104206 </plugin>
105207 </plugins>
106208 </build>
0 package org.jboss.resteasy.client.jaxrs;
1
2 import java.util.concurrent.Future;
3
4 import javax.ws.rs.client.InvocationCallback;
5
6 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
7 import org.jboss.resteasy.client.jaxrs.internal.ClientResponse;
8
9 /**
10 * Interface for an async HttpClientEngine
11 *
12 * @author Markus Kull
13 */
14 public interface AsyncClientHttpEngine extends ClientHttpEngine
15 {
16
17 /**
18 * Interface for extracting a result out of a ClientResponse
19 *
20 * @param <T> Result-Type
21 */
22 public interface ResultExtractor<T>
23 {
24 /**
25 * Extracts a result out of a Response
26 *
27 * @param response Response
28 * @return result
29 */
30 public T extractResult(ClientResponse response);
31 }
32
33 /**
34 * Submits an asynchronous request.
35 *
36 * @param request Request
37 * @param buffered buffer the response?
38 * @param callback Optional callback receiving the result, which is run inside the io-thread. may be null.
39 * @param extractor ResultExtractor for extracting a result out of a ClientResponse. Is run inside the io-thread
40 * @return Future with the result or Exception
41 */
42 public <T> Future<T> submit(ClientInvocation request, boolean buffered, InvocationCallback<T> callback, ResultExtractor<T> extractor);
43
44 }
00 package org.jboss.resteasy.client.jaxrs;
11
22 import java.io.IOException;
3 import java.security.AccessController;
4 import java.security.PrivilegedAction;
35 import java.security.SecureRandom;
46 import java.util.ArrayList;
57 import java.util.List;
164166 }
165167 }
166168
167 protected ClientHttpEngine createEngine(HttpClientConnectionManager cm, RequestConfig.Builder rcBuilder,
168 HttpHost defaultProxy, int responseBufferSize, HostnameVerifier verifier, SSLContext theContext)
169 protected ClientHttpEngine createEngine(final HttpClientConnectionManager cm, final RequestConfig.Builder rcBuilder,
170 final HttpHost defaultProxy, final int responseBufferSize, final HostnameVerifier verifier, final SSLContext theContext)
169171 {
170 HttpClient httpClient = HttpClientBuilder.create()
171 .setConnectionManager(cm)
172 .setDefaultRequestConfig(rcBuilder.build())
173 .setProxy(defaultProxy)
174 .disableContentCompression().build();
175 ApacheHttpClient43Engine engine = (ApacheHttpClient43Engine) ApacheHttpClient4EngineFactory.create(httpClient,
172 final HttpClient httpClient;
173 if (System.getSecurityManager() == null)
174 {
175 httpClient = HttpClientBuilder.create()
176 .setConnectionManager(cm)
177 .setDefaultRequestConfig(rcBuilder.build())
178 .setProxy(defaultProxy)
179 .disableContentCompression().build();
180 }
181 else
182 {
183 httpClient = AccessController.doPrivileged(new PrivilegedAction<HttpClient>()
184 {
185 @Override
186 public HttpClient run()
187 {
188 return HttpClientBuilder.create()
189 .setConnectionManager(cm)
190 .setDefaultRequestConfig(rcBuilder.build())
191 .setProxy(defaultProxy)
192 .disableContentCompression().build();
193 }
194 });
195 }
196
197 ApacheHttpClient43Engine engine = (ApacheHttpClient43Engine) ApacheHttpClient4EngineFactory.create(httpClient,
176198 true);
177199 engine.setResponseBufferSize(responseBufferSize);
178200 engine.setHostnameVerifier(verifier);
1313
1414 import java.lang.reflect.Method;
1515 import java.lang.reflect.Proxy;
16 import java.security.AccessController;
17 import java.security.PrivilegedAction;
1618 import java.util.Arrays;
1719 import java.util.HashMap;
1820 import java.util.Set;
2325
2426 private final Class<T> iface;
2527 private final ResteasyWebTarget webTarget;
26 private ClassLoader loader = Thread.currentThread().getContextClassLoader();
28 private ClassLoader loader;
2729 private MediaType serverConsumes;
2830 private MediaType serverProduces;
2931
9294
9395 private ProxyBuilder(Class<T> iface, ResteasyWebTarget webTarget)
9496 {
97 if (System.getSecurityManager() == null)
98 {
99 this.loader = Thread.currentThread().getContextClassLoader();
100 }
101 else
102 {
103 this.loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
104 {
105 @Override
106 public ClassLoader run()
107 {
108 return Thread.currentThread().getContextClassLoader();
109 }
110 });
111 }
95112 this.iface = iface;
96113 this.webTarget = webTarget;
97114 }
22 import org.jboss.resteasy.client.jaxrs.i18n.Messages;
33 import org.jboss.resteasy.client.jaxrs.internal.ClientConfiguration;
44 import org.jboss.resteasy.client.jaxrs.internal.ClientWebTarget;
5 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
6 import org.jboss.resteasy.spi.NotImplementedYetException;
7 import org.jboss.resteasy.spi.ResteasyProviderFactory;
85
96 import javax.net.ssl.HostnameVerifier;
107 import javax.net.ssl.SSLContext;
1613 import javax.ws.rs.core.UriBuilder;
1714
1815 import java.net.URI;
16 import java.security.AccessController;
17 import java.security.PrivilegedAction;
1918 import java.util.Map;
2019 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.Executors;
20 import java.util.concurrent.ScheduledExecutorService;
2221
2322 /**
2423 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
2827 {
2928 protected volatile ClientHttpEngine httpEngine;
3029 protected volatile ExecutorService asyncInvocationExecutor;
30 protected volatile ScheduledExecutorService scheduledExecutorService;
3131 protected ClientConfiguration configuration;
3232 protected boolean closed;
3333 protected boolean cleanupExecutor;
3434
3535
36 ResteasyClient(ClientHttpEngine httpEngine, ExecutorService asyncInvocationExecutor, boolean cleanupExecutor, ClientConfiguration configuration)
36 ResteasyClient(ClientHttpEngine httpEngine, ExecutorService asyncInvocationExecutor, boolean cleanupExecutor,
37 ScheduledExecutorService scheduledExecutorService, ClientConfiguration configuration)
3738 {
3839 this.cleanupExecutor = cleanupExecutor;
3940 this.httpEngine = httpEngine;
4041 this.asyncInvocationExecutor = asyncInvocationExecutor;
4142 this.configuration = configuration;
43 this.scheduledExecutorService = scheduledExecutorService;
44 }
45
46 ResteasyClient(ClientHttpEngine httpEngine, ExecutorService asyncInvocationExecutor, boolean cleanupExecutor, ClientConfiguration configuration)
47 {
48 this.cleanupExecutor = cleanupExecutor;
49 this.httpEngine = httpEngine;
50 this.asyncInvocationExecutor = asyncInvocationExecutor;
51 this.configuration = configuration;
4252 }
4353
4454 public ClientHttpEngine httpEngine()
5161 public ExecutorService asyncInvocationExecutor()
5262 {
5363 return asyncInvocationExecutor;
64 }
65
66 public ScheduledExecutorService getScheduledExecutor()
67 {
68 return this.scheduledExecutorService;
5469 }
5570
5671 public void abortIfClosed()
7287 httpEngine.close();
7388 if (cleanupExecutor)
7489 {
75 asyncInvocationExecutor.shutdown();
90 if (System.getSecurityManager() == null)
91 {
92 asyncInvocationExecutor.shutdown();
93 }
94 else
95 {
96 AccessController.doPrivileged(new PrivilegedAction<Void>()
97 {
98 @Override
99 public Void run()
100 {
101 asyncInvocationExecutor.shutdown();
102 return null;
103 }
104 });
105 }
76106 }
77107 }
78108 catch (Exception e)
00 package org.jboss.resteasy.client.jaxrs;
11
22 import org.apache.http.HttpHost;
3 import org.apache.http.impl.nio.client.HttpAsyncClients;
4 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpAsyncClient4Engine;
35 import org.jboss.resteasy.client.jaxrs.i18n.Messages;
46 import org.jboss.resteasy.client.jaxrs.internal.ClientConfiguration;
57 import org.jboss.resteasy.client.jaxrs.internal.LocalResteasyProviderFactory;
2224 import java.util.Map;
2325 import java.util.concurrent.ExecutorService;
2426 import java.util.concurrent.Executors;
27 import java.util.concurrent.ScheduledExecutorService;
2528 import java.util.concurrent.TimeUnit;
2629
2730 /**
5659 protected HostnameVerificationPolicy policy = HostnameVerificationPolicy.WILDCARD;
5760 protected ResteasyProviderFactory providerFactory;
5861 protected ExecutorService asyncExecutor;
62 protected ScheduledExecutorService scheduledExecutorService;
5963 protected boolean cleanupExecutor;
6064 protected SSLContext sslContext;
6165 protected Map<String, Object> properties = new HashMap<String, Object>();
6266 protected ClientHttpEngine httpEngine;
63 protected int connectionPoolSize;
67 protected int connectionPoolSize = 50;
6468 protected int maxPooledPerRoute = 0;
6569 protected long connectionTTL = -1;
6670 protected TimeUnit connectionTTLUnit = TimeUnit.MILLISECONDS;
9195 *
9296 * @param asyncExecutor
9397 * @return
94 */
98 * @deprecated use {@link ResteasyClientBuilder#executorService(ExecutorService)} instead
99 */
100 @Deprecated
95101 public ResteasyClientBuilder asyncExecutor(ExecutorService asyncExecutor)
96102 {
97103 return asyncExecutor(asyncExecutor, false);
104110 * @param cleanupExecutor true if the Client should close the executor when it is closed
105111 * @return
106112 */
113 @Deprecated
107114 public ResteasyClientBuilder asyncExecutor(ExecutorService asyncExecutor, boolean cleanupExecutor)
108115 {
109116 this.asyncExecutor = asyncExecutor;
125132 return this;
126133 }
127134
135 public ResteasyClientBuilder readTimeout(long timeout, TimeUnit unit)
136 {
137 this.socketTimeout = timeout;
138 this.socketTimeoutUnits = unit;
139 return this;
140 }
141
128142 /**
129143 * The timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout
130144 *
132146 * @param unit
133147 * @return
134148 */
149 @Deprecated
135150 public ResteasyClientBuilder socketTimeout(long timeout, TimeUnit unit)
136151 {
137 this.socketTimeout = timeout;
138 this.socketTimeoutUnits = unit;
152 return readTimeout(timeout, unit);
153 }
154
155 public ResteasyClientBuilder connectTimeout(long timeout, TimeUnit unit)
156 {
157 this.establishConnectionTimeout = timeout;
158 this.establishConnectionTimeoutUnits = unit;
139159 return this;
140160 }
141161
146166 * @param unit
147167 * @return
148168 */
169 @Deprecated
149170 public ResteasyClientBuilder establishConnectionTimeout(long timeout, TimeUnit unit)
150171 {
151 this.establishConnectionTimeout = timeout;
152 this.establishConnectionTimeoutUnits = unit;
153 return this;
172 return connectTimeout(timeout, unit);
154173 }
155174
156175
236255 public ResteasyClientBuilder httpEngine(ClientHttpEngine httpEngine)
237256 {
238257 this.httpEngine = httpEngine;
258 return this;
259 }
260
261 public ResteasyClientBuilder useAsyncHttpEngine()
262 {
263 this.httpEngine = new ApacheHttpAsyncClient4Engine(HttpAsyncClients.createSystem(), true);
239264 return this;
240265 }
241266
329354 if (providerFactory == null)
330355 {
331356 // create a new one
332 providerFactory = new LocalResteasyProviderFactory(ResteasyProviderFactory.newInstance());
357 providerFactory = new LocalResteasyProviderFactory(new ResteasyProviderFactory());
333358 RegisterBuiltin.register(providerFactory);
334359 }
335360 return providerFactory;
353378 }
354379
355380 ClientHttpEngine engine = httpEngine != null ? httpEngine : new ClientHttpEngineBuilder4().resteasyClientBuilder(this).build();
356 return new ResteasyClient(engine, executor, cleanupExecutor, config);
381 return new ResteasyClient(engine, executor, cleanupExecutor, scheduledExecutorService, config);
357382
358383 }
359384
378403 }
379404
380405 ClientHttpEngine engine = httpEngine != null ? httpEngine : new ClientHttpEngineBuilder43().resteasyClientBuilder(this).build();
381 return new ResteasyClient(engine, executor, cleanupExecutor, config);
406 return new ResteasyClient(engine, executor, cleanupExecutor, scheduledExecutorService, config);
382407
383408 }
384409
487512 }
488513 return this;
489514 }
515
516 public ClientBuilder executorService(ExecutorService executorService)
517 {
518 return asyncExecutor(executorService, false);
519 }
520
521 public ClientBuilder scheduledExecutorService(ScheduledExecutorService scheduledExecutorService)
522 {
523 this.scheduledExecutorService = scheduledExecutorService;
524 return this;
525 }
490526 }
00 package org.jboss.resteasy.client.jaxrs;
11
22 import javax.ws.rs.client.WebTarget;
3 import javax.ws.rs.core.Configurable;
4 import javax.ws.rs.core.Configuration;
53 import javax.ws.rs.core.MultivaluedMap;
64 import java.lang.reflect.Method;
75 import java.util.Map;
0 package org.jboss.resteasy.client.jaxrs.engines;
1
2 import java.io.ByteArrayOutputStream;
3 import java.io.Closeable;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.net.URI;
7 import java.nio.ByteBuffer;
8 import java.util.List;
9 import java.util.Map;
10 import java.util.concurrent.ExecutionException;
11 import java.util.concurrent.Future;
12
13 import javax.net.ssl.HostnameVerifier;
14 import javax.net.ssl.SSLContext;
15 import javax.ws.rs.ProcessingException;
16 import javax.ws.rs.WebApplicationException;
17 import javax.ws.rs.client.InvocationCallback;
18 import javax.ws.rs.client.ResponseProcessingException;
19 import javax.ws.rs.core.MultivaluedMap;
20 import javax.ws.rs.core.Response;
21
22 import org.apache.commons.io.IOUtils;
23 import org.apache.http.ContentTooLongException;
24 import org.apache.http.Header;
25 import org.apache.http.HttpEntity;
26 import org.apache.http.HttpEntityEnclosingRequest;
27 import org.apache.http.HttpException;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.client.methods.HttpGet;
30 import org.apache.http.client.methods.HttpPost;
31 import org.apache.http.client.methods.HttpRequestBase;
32 import org.apache.http.client.methods.HttpUriRequest;
33 import org.apache.http.concurrent.BasicFuture;
34 import org.apache.http.concurrent.FutureCallback;
35 import org.apache.http.entity.ByteArrayEntity;
36 import org.apache.http.entity.ContentType;
37 import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
38 import org.apache.http.message.BasicHeader;
39 import org.apache.http.nio.ContentDecoder;
40 import org.apache.http.nio.IOControl;
41 import org.apache.http.nio.client.methods.HttpAsyncMethods;
42 import org.apache.http.nio.entity.ContentInputStream;
43 import org.apache.http.nio.protocol.AbstractAsyncResponseConsumer;
44 import org.apache.http.nio.protocol.HttpAsyncRequestProducer;
45 import org.apache.http.nio.protocol.HttpAsyncResponseConsumer;
46 import org.apache.http.nio.util.HeapByteBufferAllocator;
47 import org.apache.http.nio.util.SharedInputBuffer;
48 import org.apache.http.nio.util.SimpleInputBuffer;
49 import org.apache.http.protocol.HTTP;
50 import org.apache.http.protocol.HttpContext;
51 import org.jboss.resteasy.client.jaxrs.AsyncClientHttpEngine;
52 import org.jboss.resteasy.client.jaxrs.i18n.LogMessages;
53 import org.jboss.resteasy.client.jaxrs.internal.ClientConfiguration;
54 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
55 import org.jboss.resteasy.client.jaxrs.internal.ClientResponse;
56 import org.jboss.resteasy.util.CaseInsensitiveMap;
57
58 /**
59 * AsyncClientHttpEngine using apache http components HttpAsyncClient 4.<p/>
60 *
61 * Some words of caution: <ul>
62 * <li>Asynchronous IO means non-blocking IO utilizing few threads, typically at most as much threads as number of cores.
63 * As such, performance may profit from fewer thread switches and less memory usage due to fewer thread-stacks. But doing
64 * synchronous, blocking IO (the invoke-methods not returning a future) may suffer, because the data has to be transferred
65 * piecewiese to/from the io-threads.</li>
66 * <li>Request-Entities are fully buffered in memory, thus this engine is unsuitable for very large uploads.</li>
67 * <li>Response-Entities are buffered in memory, except if requesting a Response, InputStream or Reader as Result. Thus
68 * for large downloads or COMET one of these three return types must be requested, but there may be a performance penalty
69 * because the response-body is transferred piecewise from the io-threads. When using InvocationCallbacks, the response is
70 * always fully buffered in memory.</li>
71 * <li>InvocationCallbacks are called from within the io-threads and thus must not block or else the application may
72 * slow down to a halt. Reading the response is safe (because the response is buffered in memory), as are other async
73 * (and in-memory) Client-invocations (the submit-calls returning a future not containing Response, InputStream or Reader).
74 * Again, there must be no blocking IO inside InvocationCallback! (If you are wondering why not to allow blocking calls by
75 * wrapping InvocationCallbacks in extra threads: Because then the main advantage of async IO, less threading, is lost.)
76 * <li>InvocationCallbacks may be called seemingly "after" the future-object returns. Thus, responses should be handled
77 * solely in the InvocationCallback.</li>
78 * <li>InvocationCallbacks will see the same result as the future-object and vice versa. Thus, if the invocationcallback
79 * throws an exception, the future-object will not see it. Another reason to handle responses only in the InvocationCallback.
80 * </li>
81 *
82 * @author Markus Kull
83 */
84 public class ApacheHttpAsyncClient4Engine implements AsyncClientHttpEngine, Closeable
85 {
86 protected final CloseableHttpAsyncClient client;
87 protected final boolean closeHttpClient;
88
89 public ApacheHttpAsyncClient4Engine(CloseableHttpAsyncClient client, boolean closeHttpClient)
90 {
91 if (client == null) throw new NullPointerException("client");
92 this.client = client;
93 this.closeHttpClient = closeHttpClient;
94 if (closeHttpClient && !client.isRunning()) {
95 client.start();
96 }
97 }
98
99 @Override
100 public void close()
101 {
102 if (closeHttpClient)
103 {
104 IOUtils.closeQuietly(client);
105 }
106 }
107
108 @Override
109 public SSLContext getSslContext()
110 {
111 throw new UnsupportedOperationException();
112 }
113
114 @Override
115 public HostnameVerifier getHostnameVerifier()
116 {
117 throw new UnsupportedOperationException();
118 }
119
120 @Override
121 public ClientResponse invoke(ClientInvocation request)
122 {
123 // Doing blocking requests with an async httpclient is quite useless.
124 // But it is better to use the same httpclient in any case just for sharing+configuring only one connectionpool.
125 Future<ClientResponse> future = submit(request, false, null, new ResultExtractor<ClientResponse>() {
126 @Override
127 public ClientResponse extractResult(ClientResponse response)
128 {
129 return response;
130 }
131 });
132 try
133 {
134 return future.get();
135 }
136 catch (InterruptedException e)
137 {
138 future.cancel(true);
139 throw clientException(e, null);
140 }
141 catch (ExecutionException e)
142 {
143 throw clientException(e.getCause(), null);
144 }
145 }
146
147 @Override
148 public <T> Future<T> submit(
149 ClientInvocation request, boolean buffered, InvocationCallback<T> callback, ResultExtractor<T> extractor)
150 {
151 HttpUriRequest httpRequest = buildHttpRequest(request);
152
153 if (buffered)
154 {
155 // Request+Response fully buffered in memory. Optional callback is called inside io-thread after response-body and
156 // after the returned future is signaled to be completed.
157 //
158 // This differs to Resteasy 3.0.8 and earlier (which called the callback before the future completed) due to the
159 // following reasons:
160 // * ApacheHttpcomponents BasicFuture, guavas ListenableFuture and also jersey calls the callback after completing
161 // the future. The earlier Resteasy-behaviour may be more "safe" but any users switching from resteasy to another
162 // jax-rs implementation may encounter a nasty surprise.
163 // * ensure the result returned by the future is the same given to the callback.
164 // * As good practice, the result should only be handled in one place (future OR callback, not both)
165 // * Invocation-javadoc says "the underlying response instance will be automatically closed" seemingly implying
166 // the future-response is unusable (bc. closed) together with a callback
167 // Of course the one big drawback is that exceptions inside the callback are not visible to the application,
168 // but callbacks are mostly treated as fire-and-forget, meaning their result is not checked anyway.
169 HttpAsyncRequestProducer requestProducer = HttpAsyncMethods.create(httpRequest);
170 HttpAsyncResponseConsumer<T> responseConsumer = new BufferingResponseConsumer<T>(request, extractor);
171 FutureCallback<T> httpCallback = callback != null ? new CallbackAdapter<T>(callback) : null;
172
173 return client.execute(requestProducer, responseConsumer, httpCallback);
174 }
175 else
176 {
177 // unbuffered: Future returns immediately after headers. Reading the response-stream blocks, but one may check
178 // InputStream#available() to prevent blocking.
179
180 // would be easy to call an InvocationCallback after response-BODY, but cant see any usecase for it.
181 if (callback != null) throw new IllegalArgumentException("unbuffered InvocationCallback is not supported");
182
183 HttpAsyncRequestProducer requestProducer = HttpAsyncMethods.create(httpRequest);
184 StreamingResponseConsumer<T> responseConsumer = new StreamingResponseConsumer<T>(request, extractor);
185
186 Future<T> httpFuture = client.execute(requestProducer, responseConsumer, null);
187 return responseConsumer.future(httpFuture);
188 }
189 }
190
191
192 /**
193 * ResponseConsumer which transfers the response piecewise from the io-thread to the blocking handler-thread.
194 * {@link #future(Future)} returns a Future which completes immediately after receiving the response-headers
195 * but reading the response-inputstream blocks until data is available.
196 */
197 private static class StreamingResponseConsumer<T> implements HttpAsyncResponseConsumer<T>
198 {
199 private static final IOException unallowedBlockingReadException = new IOException("blocking reads inside an async io-handler are not allowed") {
200 public synchronized Throwable fillInStackTrace() {
201 //do nothing and return
202 return this;
203 }
204 };
205
206 private ClientConfiguration configuration;
207 private Map<String, Object> properties;
208 private ResultExtractor<T> extractor;
209
210 private ResultFuture<T> future;
211 private SharedInputStream sharedStream;
212
213 private volatile boolean hasResult;
214 private volatile T result;
215 private volatile Exception exception;
216 private volatile boolean completed;
217
218 public StreamingResponseConsumer(ClientInvocation request, ResultExtractor<T> extractor)
219 {
220 this.configuration = request.getClientConfiguration();
221 this.properties = request.getMutableProperties();
222 this.extractor = extractor;
223 }
224
225 private void releaseResources()
226 {
227 this.configuration = null;
228 this.properties = null;
229 this.extractor = null;
230
231 this.future = null;
232 this.sharedStream = null;
233 }
234
235 public synchronized Future<T> future(Future<T> httpFuture)
236 {
237 if (completed)
238 { // already failed or fully buffered
239 return httpFuture;
240 }
241 future = new ResultFuture<T>(httpFuture);
242 future.copyHttpFutureResult();
243 if (!future.isDone() && hasResult)
244 { // response(-headers) is available, but not yet the full response-stream. Return immediately the result
245 future.completed(getResult());
246 }
247 return future;
248 }
249
250 @Override
251 public synchronized void responseReceived(HttpResponse httpResponse) throws IOException, HttpException
252 {
253 SharedInputStream sharedStream = null;
254 ConnectionResponse clientResponse = null;
255 T result = null;
256 Exception exception = null;
257
258 boolean success = false;
259 try {
260 clientResponse = new ConnectionResponse(configuration, properties);
261 copyResponse(httpResponse, clientResponse);
262 final HttpEntity entity = httpResponse.getEntity();
263 if (entity != null)
264 {
265 sharedStream = new SharedInputStream(new SharedInputBuffer(16 * 1024));
266 // one could also set the stream after extracting the response, but this would prevent wrapping the stream
267 clientResponse.setConnection(sharedStream);
268 sharedStream.setException(unallowedBlockingReadException);
269 result = extractor.extractResult(clientResponse);
270 sharedStream.setException(null);
271 }
272 else
273 {
274 result = extractor.extractResult(clientResponse);
275 }
276 success = true;
277 }
278 catch(Exception e)
279 {
280 exception = clientException(e, clientResponse);
281 }
282 finally
283 {
284 if (success)
285 {
286 this.sharedStream = sharedStream;
287 this.result = result;
288 this.hasResult = true;
289 if (future != null) future.completed(result);
290 }
291 else
292 {
293 this.exception = exception;
294 completed = true;
295 if (future != null) future.failed(exception);
296 releaseResources();
297 }
298 }
299 }
300
301 @Override
302 public synchronized void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException
303 {
304 if (sharedStream != null) sharedStream.consumeContent(decoder, ioctrl);
305 }
306
307 @Override
308 public synchronized void responseCompleted(HttpContext context)
309 {
310 this.completed = true;
311 try
312 {
313 if (sharedStream != null)
314 { // only needed in case of empty response body (=null ioctrl)
315 sharedStream.consumeContent(EndOfStream.INSTANCE, null);
316 }
317 }
318 catch (IOException ioe)
319 { // cannot happen
320 throw new RuntimeException(ioe);
321 }
322 finally
323 {
324 releaseResources();
325 }
326 }
327
328 @Override
329 public Exception getException()
330 {
331 return exception;
332 }
333
334 @Override
335 public T getResult()
336 {
337 return result;
338 }
339
340 @Override
341 public boolean isDone()
342 { // cancels in case of closing the SharedInputStream
343 return completed;
344 }
345
346 @Override
347 public synchronized void close()
348 {
349 completed = true;
350 ResultFuture<T> future = this.future;
351 if (future != null)
352 {
353 // if connect fails, then the httpclient just calls close() after setting its future, but never our failed().
354 // so copy the httpFuture-result into our ResultFuture.
355 future.copyHttpFutureResult();
356 if (!future.isDone())
357 { // doesnt happen?
358 future.failed(clientException(new IOException("connect failed"), null));
359 }
360 }
361 releaseResources();
362 }
363
364 @Override
365 public synchronized void failed(Exception ex)
366 {
367 completed = true;
368 if (future != null) future.failed(clientException(ex, null));
369 if (sharedStream != null)
370 {
371 sharedStream.setException(ioException(ex));
372 IOUtils.closeQuietly(sharedStream);
373 }
374 releaseResources();
375 }
376
377 @Override
378 public synchronized boolean cancel()
379 {
380 completed = true;
381 if (future != null) future.cancelledResult();
382 if (sharedStream != null)
383 {
384 sharedStream.setException(new IOException("cancelled"));
385 IOUtils.closeQuietly(sharedStream);
386 }
387 releaseResources();
388 return true;
389 }
390
391 private static class ResultFuture<T> extends BasicFuture<T>
392 {
393 private final Future<T> httpFuture;
394
395 public ResultFuture(final Future<T> httpFuture)
396 {
397 super(null);
398 this.httpFuture = httpFuture;
399 }
400
401 @Override
402 public boolean cancel(boolean mayInterruptIfRunning)
403 {
404 boolean cancelled = super.cancel(mayInterruptIfRunning);
405 httpFuture.cancel(mayInterruptIfRunning);
406 return cancelled;
407 }
408
409 public void cancelledResult() {
410 super.cancel(true);
411 }
412
413 public void copyHttpFutureResult()
414 {
415 if (!isDone() && httpFuture.isDone())
416 {
417 try
418 {
419 completed(httpFuture.get());
420 }
421 catch(ExecutionException e)
422 {
423 failed(clientException(e.getCause(), null));
424 }
425 catch (InterruptedException e)
426 { // cant happen because already isDone
427 failed(e);
428 }
429 }
430 }
431 }
432
433 private class SharedInputStream extends ContentInputStream {
434
435 private final SharedInputBuffer sharedBuf;
436 private volatile IOException ex;
437 private volatile IOControl ioctrl;
438
439 public SharedInputStream(SharedInputBuffer sharedBuf)
440 {
441 super(sharedBuf);
442 this.sharedBuf = sharedBuf;
443 }
444
445 public void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException {
446 if (ioctrl != null) this.ioctrl = ioctrl;
447 sharedBuf.consumeContent(decoder, ioctrl);
448 }
449
450 @Override
451 public void close() throws IOException
452 {
453 completed = true; // next isDone() cancels.
454
455 // Workaround for deadlock: super.close() reads until no more data, but on cancellation no more data is
456 // pushed to consumeContent, thus deadlock. Instead notify the reactor by ioctrl.requestInput
457 sharedBuf.close(); // next reads will return EndOfStream. Also wakes up any waiting readers
458 IOControl ioctrl = this.ioctrl;
459 if (ioctrl != null) ioctrl.requestInput(); // notify reactor to check isDone()
460 super.close(); // does basically nothing due to closed buf
461 }
462
463 @Override
464 public int read(final byte[] b, final int off, final int len) throws IOException
465 {
466 throwIfError();
467 return super.read(b, off, len);
468 }
469
470 @Override
471 public int read(final byte[] b) throws IOException
472 {
473 throwIfError();
474 return super.read(b, 0, b.length);
475 }
476
477 @Override
478 public int read() throws IOException {
479 throwIfError();
480 return super.read();
481 }
482
483 private void throwIfError() throws IOException {
484 IOException ex = this.ex;
485 if (ex != null) {
486 //create a new exception here to make it easy figuring out where the offending blocking IO comes from
487 throw new IOException(ex);
488 }
489 }
490
491 public void setException(IOException e) {
492 this.ex = e;
493 }
494 }
495 }
496
497 /**
498 * Buffers response fully in memory.
499 *
500 * (Buffering is definitely easier to implement than streaming)
501 */
502 private static class BufferingResponseConsumer<T> extends AbstractAsyncResponseConsumer<T>
503 {
504
505 private ClientConfiguration configuration;
506 private Map<String, Object> properties;
507 private ResultExtractor<T> responseExtractor;
508 private ConnectionResponse clientResponse;
509 private SimpleInputBuffer buf;
510
511 public BufferingResponseConsumer(ClientInvocation request, ResultExtractor<T> responseExtractor)
512 {
513 this.configuration = request.getClientConfiguration();
514 this.properties = request.getMutableProperties();
515 this.responseExtractor = responseExtractor;
516 }
517
518 @Override
519 protected void onResponseReceived(HttpResponse response) throws HttpException, IOException
520 {
521 ConnectionResponse clientResponse = new ConnectionResponse(configuration, properties);
522 copyResponse(response, clientResponse);
523 final HttpEntity entity = response.getEntity();
524 if (entity != null)
525 {
526 long len = entity.getContentLength();
527 if (len > Integer.MAX_VALUE)
528 {
529 throw new ContentTooLongException("Entity content is too long: " + len);
530 }
531 if (len < 0)
532 {
533 len = 4096;
534 }
535 this.buf = new SimpleInputBuffer((int) len, new HeapByteBufferAllocator());
536 }
537 this.clientResponse = clientResponse;
538 }
539
540 @Override
541 protected void onEntityEnclosed(HttpEntity entity, ContentType contentType) throws IOException
542 {
543 }
544
545 @Override
546 protected void onContentReceived(ContentDecoder decoder, IOControl ioctrl) throws IOException
547 {
548 SimpleInputBuffer buf = this.buf;
549 if (buf == null) throw new NullPointerException("Content Buffer");
550 buf.consumeContent(decoder);
551 }
552
553 @Override
554 protected T buildResult(HttpContext context) throws Exception
555 {
556 if (buf != null) clientResponse.setConnection(new ContentInputStream(buf));
557 return responseExtractor.extractResult(clientResponse);
558 }
559
560 @Override
561 protected void releaseResources()
562 {
563 this.configuration = null;
564 this.properties = null;
565 this.responseExtractor = null;
566 this.clientResponse = null;
567 this.buf = null;
568 }
569 }
570
571 /**
572 * Adapter from http-FutureCallback<T> to InvocationCallback<T>
573 */
574 private static class CallbackAdapter<T> implements FutureCallback<T>
575 {
576 private final InvocationCallback<T> invocationCallback;
577
578 public CallbackAdapter(InvocationCallback<T> invocationCallback)
579 {
580 this.invocationCallback = invocationCallback;
581 }
582
583 @Override
584 public void cancelled()
585 {
586 invocationCallback.failed(new ProcessingException("cancelled"));
587 }
588
589 @Override
590 public void completed(T response)
591 {
592 try
593 {
594 invocationCallback.completed(response);
595 }
596 catch (Throwable t)
597 {
598 LogMessages.LOGGER.exceptionIgnored(t);
599 }
600 finally
601 {
602 // just to promote proper callback usage, because HttpAsyncClient is responsible
603 // for cleaning up the (buffered) connection
604 if (response instanceof Response)
605 {
606 ((Response) response).close();
607 }
608 }
609 }
610
611 @Override
612 public void failed(Exception ex)
613 {
614 invocationCallback.failed(clientException(ex, null));
615 }
616 }
617
618 /**
619 * ClientResponse with surefire releaseConnection
620 */
621 private static class ConnectionResponse extends ClientResponse
622 {
623
624 private InputStream connection;
625 private InputStream stream;
626
627 public ConnectionResponse(ClientConfiguration configuration, Map<String, Object> properties)
628 {
629 super(configuration);
630 setProperties(properties);
631 }
632
633 public synchronized void setConnection(InputStream connection)
634 {
635 this.connection = connection;
636 this.stream = connection;
637 }
638
639 @Override
640 protected synchronized void setInputStream(InputStream is)
641 {
642 stream = is;
643 }
644
645 @Override
646 public synchronized InputStream getInputStream()
647 {
648 return stream;
649 }
650
651 @Override
652 public synchronized void releaseConnection() throws IOException
653 {
654 boolean thrown = true;
655 try
656 {
657 if (stream != null) stream.close();
658 thrown = false;
659 }
660 finally
661 {
662 if (connection != null)
663 {
664 if (thrown)
665 {
666 IOUtils.closeQuietly(connection);
667 }
668 else
669 {
670 connection.close();
671 }
672 }
673 }
674 }
675 }
676
677 private static class EndOfStream implements ContentDecoder
678 {
679 public static EndOfStream INSTANCE = new EndOfStream();
680
681 @Override
682 public int read(ByteBuffer dst) throws IOException
683 {
684 return -1;
685 }
686
687 @Override
688 public boolean isCompleted()
689 {
690 return true;
691 }
692 }
693
694 private static HttpUriRequest buildHttpRequest(ClientInvocation request)
695 {
696 // Writers may change headers. Thus buffer the content before committing the headers.
697 // For simplicity's sake the content is buffered in memory. File-buffering (ZeroCopyConsumer...) would be
698 // possible, but resource management is error-prone.
699
700 HttpRequestBase httpRequest = createHttpMethod(request.getUri(), request.getMethod());
701 if (request.getEntity() != null)
702 {
703 byte[] requestContent = requestContent(request);
704 ByteArrayEntity entity = new ByteArrayEntity(requestContent);
705 entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, request.getHeaders().getMediaType().toString()));
706 commitHeaders(request, httpRequest);
707 ((HttpEntityEnclosingRequest) httpRequest).setEntity(entity);
708 }
709 else
710 {
711 commitHeaders(request, httpRequest);
712 }
713
714 return httpRequest;
715 }
716
717 private static byte[] requestContent(ClientInvocation request)
718 {
719 ByteArrayOutputStream baos = new ByteArrayOutputStream();
720 request.getDelegatingOutputStream().setDelegate(baos);
721 try
722 {
723 request.writeRequestBody(request.getEntityStream());
724 baos.close();
725 return baos.toByteArray();
726 }
727 catch (IOException e)
728 {
729 throw new RuntimeException(e);
730 }
731 }
732
733 private static HttpRequestBase createHttpMethod(URI url, String restVerb)
734 {
735 if ("GET".equals(restVerb))
736 {
737 return new HttpGet(url);
738 }
739 else if ("POST".equals(restVerb))
740 {
741 return new HttpPost(url);
742 }
743 else
744 {
745 final String verb = restVerb;
746 return new HttpPost(url)
747 {
748 @Override
749 public String getMethod()
750 {
751 return verb;
752 }
753 };
754 }
755 }
756
757 private static void commitHeaders(ClientInvocation request, HttpRequestBase httpMethod)
758 {
759 MultivaluedMap<String, String> headers = request.getHeaders().asMap();
760 for (Map.Entry<String, List<String>> header : headers.entrySet())
761 {
762 List<String> values = header.getValue();
763 for (String value : values)
764 {
765 httpMethod.addHeader(header.getKey(), value);
766 }
767 }
768 }
769
770 private static void copyResponse(HttpResponse httpResponse, ClientResponse clientResponse)
771 {
772 clientResponse.setStatus(httpResponse.getStatusLine().getStatusCode());
773 CaseInsensitiveMap<String> headers = new CaseInsensitiveMap<String>();
774 for (Header header : httpResponse.getAllHeaders())
775 {
776 headers.add(header.getName(), header.getValue());
777 }
778 clientResponse.setHeaders(headers);
779 }
780
781 private static RuntimeException clientException(Throwable ex, Response clientResponse) {
782 RuntimeException ret;
783 if (ex == null)
784 {
785 ret = new ProcessingException(new NullPointerException());
786 }
787 else if (ex instanceof WebApplicationException)
788 {
789 ret = (WebApplicationException) ex;
790 }
791 else if (ex instanceof ProcessingException)
792 {
793 ret = (ProcessingException) ex;
794 }
795 else if (clientResponse != null)
796 {
797 ret = new ResponseProcessingException(clientResponse, ex);
798 }
799 else
800 {
801 ret = new ProcessingException(ex);
802 }
803 return ret;
804 }
805
806 private static IOException ioException(Exception ex) {
807 return (ex instanceof IOException) ? (IOException) ex : new IOException(ex);
808 }
809
810 }
2020 import org.apache.http.params.SyncBasicHttpParams;
2121 import org.apache.http.protocol.HTTP;
2222 import org.apache.http.protocol.HttpContext;
23 import org.jboss.resteasy.client.core.SelfExpandingBufferredInputStream;
2324 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
2425 import org.jboss.resteasy.client.jaxrs.i18n.LogMessages;
2526 import org.jboss.resteasy.client.jaxrs.i18n.Messages;
6768 protected int responseBufferSize = 8192;
6869 protected HttpHost defaultProxy = null;
6970 protected boolean chunked = false;
71 protected boolean followRedirects = false;
7072
7173 /**
7274 * For uploading File's over JAX-RS framework, this property, together with {@link #fileUploadMemoryUnit},
400402 };
401403 response.setProperties(request.getMutableProperties());
402404 response.setStatus(res.getStatusLine().getStatusCode());
405 response.setReasonPhrase(res.getStatusLine().getReasonPhrase());
403406 response.setHeaders(extractHeaders(res));
404407 response.setClientConfiguration(request.getClientConfiguration());
405408 return response;
429432 }
430433 }
431434
432 protected boolean isRedirectRequired(final ClientInvocation request, final HttpRequestBase httpMethod)
433 {
434 if (httpMethod instanceof HttpGet && false) // todo && request.followRedirects())
435 {
436 return true;
437 }
438 return false;
439 }
440
435 @SuppressWarnings("deprecation")
441436 protected HttpClient createDefaultHttpClient()
442437 {
443438 HttpParams params = new SyncBasicHttpParams();
462457
463458 protected void loadHttpMethod(final ClientInvocation request, HttpRequestBase httpMethod) throws Exception
464459 {
465 if (isRedirectRequired(request,httpMethod)) // todo && request.followRedirects())
460 if (isFollowRedirects())
466461 {
467462 setRedirectRequired(request,httpMethod);
468463 }
545540 public void setChunked(boolean chunked)
546541 {
547542 this.chunked = chunked;
543 }
544
545 public boolean isFollowRedirects()
546 {
547 return followRedirects;
548 }
549
550 public void setFollowRedirects(boolean followRedirects)
551 {
552 this.followRedirects = followRedirects;
548553 }
549554
550555 /**
+0
-114
resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/SelfExpandingBufferredInputStream.java less more
0 package org.jboss.resteasy.client.jaxrs.engines;
1
2 import java.io.BufferedInputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
7
8 /**
9 * Extension of {@link BufferedInputStream} enforcing the contract where reset()
10 * always returns to the beginning of the stream, and the internal buffer
11 * expands automatically to the total length of content read from the underlying
12 * stream.
13 *
14 * @author ul8b
15 */
16 public class SelfExpandingBufferredInputStream extends BufferedInputStream
17 {
18 private static int defaultBufferSize = 8192;
19
20 public SelfExpandingBufferredInputStream(InputStream in)
21 {
22 super(in);
23 super.mark(defaultBufferSize);
24 }
25
26 public SelfExpandingBufferredInputStream(InputStream in, int size)
27 {
28 super(in, size);
29 super.mark(size);
30 }
31
32 /**
33 * Not supported. Mark position is always zero.
34 */
35 @Override
36 public synchronized void mark(int readlimit)
37 {
38 throw new UnsupportedOperationException(Messages.MESSAGES.alwaysMarkedAtIndex0());
39 }
40
41 @Override
42 public synchronized int read() throws IOException
43 {
44 if (pos == marklimit)
45 {
46 expand();
47 }
48 return super.read();
49 }
50
51 @Override
52 public synchronized int read(byte[] b, int off, int len) throws IOException
53 {
54 while (pos + len > marklimit)
55 {
56 expand();
57 }
58 return super.read(b, off, len);
59 }
60
61 @Override
62 public int read(byte[] b) throws IOException
63 {
64 while (pos + b.length > marklimit)
65 {
66 expand();
67 }
68 return super.read(b);
69 }
70
71 /**
72 * Double the current buffer size limit. Reset to zero, then double the
73 * buffer size and restore last position in the buffer.
74 *
75 * @throws IOException
76 */
77 private void expand() throws IOException
78 {
79 int lastPos = pos;
80 super.reset();
81 super.mark(marklimit * 2);
82 pos = lastPos;
83 }
84
85 /**
86 * Return the current maximum size of the internal buffer. This is
87 * independent of how much data is actually contained within the buffer.
88 */
89 public int getBufSize()
90 {
91 return buf.length;
92 }
93
94 public int getCount()
95 {
96 return count;
97 }
98
99 public int getPos()
100 {
101 return pos;
102 }
103
104 public int getMarkLimit()
105 {
106 return marklimit;
107 }
108
109 public int getMarkPos()
110 {
111 return markpos;
112 }
113 }
11
22 import org.jboss.logging.BasicLogger;
33 import org.jboss.logging.Logger;
4 import org.jboss.logging.Logger.Level;
5 import org.jboss.logging.annotations.Cause;
6 import org.jboss.logging.annotations.LogMessage;
7 import org.jboss.logging.annotations.Message;
48 import org.jboss.logging.annotations.MessageLogger;
59
610 /**
1418 public interface LogMessages extends BasicLogger
1519 {
1620 LogMessages LOGGER = Logger.getMessageLogger(LogMessages.class, LogMessages.class.getPackage().getName());
21
22 @LogMessage(level = Level.DEBUG)
23 @Message(id = Messages.BASE + 171, value = "Ignoring exception thrown within InvocationCallback")
24 void exceptionIgnored(@Cause Throwable ex);
1725 }
117117 @Message(id = BASE + 150, value = "templateValues was null")
118118 String templateValuesWasNull();
119119
120 @Message(id = BASE + 152, value = "Unable to create new instance of %s")
121 String unableToInstantiate(Class<?> clazz);
122
120123 @Message(id = BASE + 155, value = "Unable to invoke request")
121124 String unableToInvokeRequest();
122125
55 import javax.ws.rs.client.InvocationCallback;
66 import javax.ws.rs.core.GenericType;
77 import javax.ws.rs.core.Response;
8
9 import org.jboss.resteasy.spi.NotImplementedYetException;
10
811 import java.util.concurrent.Future;
912
1013 /**
2326 @Override
2427 public Future<Response> get()
2528 {
26 return method(HttpMethod.GET);
29 invocation.setMethod(HttpMethod.GET);
30 return invocation.submit();
2731 }
2832
2933 @Override
3034 public <T> Future<T> get(Class<T> responseType)
3135 {
32 return method(HttpMethod.GET, responseType);
36 invocation.setMethod(HttpMethod.GET);
37 return invocation.submit(responseType);
3338 }
3439
3540 @Override
3641 public <T> Future<T> get(GenericType<T> responseType)
3742 {
38 return method(HttpMethod.GET, responseType);
43 invocation.setMethod(HttpMethod.GET);
44 return invocation.submit(responseType);
3945 }
4046
4147 @Override
4248 public <T> Future<T> get(InvocationCallback<T> callback)
4349 {
44 return method(HttpMethod.GET, callback);
50 invocation.setMethod(HttpMethod.GET);
51 return invocation.submit(callback);
4552 }
4653
4754 @Override
4855 public Future<Response> trace()
4956 {
50 return method("TRACE");
57 invocation.setMethod("TRACE");
58 return invocation.submit();
5159 }
5260
5361 @Override
5462 public <T> Future<T> trace(Class<T> responseType)
5563 {
56 return method("TRACE", responseType);
64 invocation.setMethod("TRACE");
65 return invocation.submit(responseType);
5766 }
5867
5968 @Override
6069 public <T> Future<T> trace(GenericType<T> responseType)
6170 {
62 return method("TRACE", responseType);
71 invocation.setMethod("TRACE");
72 return invocation.submit(responseType);
6373 }
6474
6575 @Override
6676 public <T> Future<T> trace(InvocationCallback<T> callback)
6777 {
68 return method("TRACE", callback);
78 invocation.setMethod("TRACE");
79 return invocation.submit(callback);
6980 }
7081
7182 @Override
7283 public Future<Response> put(Entity<?> entity)
7384 {
74 return method(HttpMethod.PUT, entity);
85 invocation.setMethod(HttpMethod.PUT);
86 invocation.setEntity(entity);
87 return invocation.submit();
7588 }
7689
7790 @Override
7891 public <T> Future<T> put(Entity<?> entity, Class<T> responseType)
7992 {
80 return method(HttpMethod.PUT, entity, responseType);
93 invocation.setMethod(HttpMethod.PUT);
94 invocation.setEntity(entity);
95 return invocation.submit(responseType);
8196 }
8297
8398 @Override
8499 public <T> Future<T> put(Entity<?> entity, GenericType<T> responseType)
85100 {
86 return method(HttpMethod.PUT, entity, responseType);
101 invocation.setMethod(HttpMethod.PUT);
102 invocation.setEntity(entity);
103 return invocation.submit(responseType);
87104 }
88105
89106 @Override
90107 public <T> Future<T> put(Entity<?> entity, InvocationCallback<T> callback)
91108 {
92 return method(HttpMethod.PUT, entity, callback);
109 invocation.setMethod(HttpMethod.PUT);
110 invocation.setEntity(entity);
111 return invocation.submit(callback);
93112 }
94113
95114 @Override
96115 public Future<Response> post(Entity<?> entity)
97116 {
98 return method(HttpMethod.POST, entity);
117 invocation.setMethod(HttpMethod.POST);
118 invocation.setEntity(entity);
119 return invocation.submit();
99120 }
100121
101122 @Override
102123 public <T> Future<T> post(Entity<?> entity, Class<T> responseType)
103124 {
104 return method(HttpMethod.POST, entity, responseType);
125 invocation.setMethod(HttpMethod.POST);
126 invocation.setEntity(entity);
127 return invocation.submit(responseType);
105128 }
106129
107130 @Override
108131 public <T> Future<T> post(Entity<?> entity, GenericType<T> responseType)
109132 {
110 return method(HttpMethod.POST, entity, responseType);
133 invocation.setMethod(HttpMethod.POST);
134 invocation.setEntity(entity);
135 return invocation.submit(responseType);
111136 }
112137
113138 @Override
114139 public <T> Future<T> post(Entity<?> entity, InvocationCallback<T> callback)
115140 {
116 return method(HttpMethod.POST, entity, callback);
141 invocation.setMethod(HttpMethod.POST);
142 invocation.setEntity(entity);
143 return invocation.submit(callback);
117144 }
118145
119146 @Override
120147 public Future<Response> delete()
121148 {
122 return method(HttpMethod.DELETE);
149 invocation.setMethod(HttpMethod.DELETE);
150 return invocation.submit();
123151 }
124152
125153 @Override
126154 public <T> Future<T> delete(Class<T> responseType)
127155 {
128 return method(HttpMethod.DELETE, responseType);
156 invocation.setMethod(HttpMethod.DELETE);
157 return invocation.submit(responseType);
129158 }
130159
131160 @Override
132161 public <T> Future<T> delete(GenericType<T> responseType)
133162 {
134 return method(HttpMethod.DELETE, responseType);
163 invocation.setMethod(HttpMethod.DELETE);
164 return invocation.submit(responseType);
135165 }
136166
137167 @Override
138168 public <T> Future<T> delete(InvocationCallback<T> callback)
139169 {
140 return method(HttpMethod.DELETE, callback);
170 invocation.setMethod(HttpMethod.DELETE);
171 return invocation.submit(callback);
141172 }
142173
143174 @Override
144175 public Future<Response> head()
145176 {
146 return method(HttpMethod.HEAD);
177 invocation.setMethod(HttpMethod.HEAD);
178 return invocation.submit();
147179 }
148180
149181 @Override
150182 public Future<Response> head(InvocationCallback<Response> callback)
151183 {
152 return method(HttpMethod.HEAD,callback);
184 invocation.setMethod(HttpMethod.HEAD);
185 return invocation.submit(callback);
153186 }
154187
155188 @Override
156189 public Future<Response> options()
157190 {
158 return method(HttpMethod.OPTIONS);
191 invocation.setMethod(HttpMethod.OPTIONS);
192 return invocation.submit();
159193 }
160194
161195 @Override
162196 public <T> Future<T> options(Class<T> responseType)
163197 {
164 return method(HttpMethod.OPTIONS, responseType);
198 invocation.setMethod(HttpMethod.OPTIONS);
199 return invocation.submit(responseType);
165200 }
166201
167202 @Override
168203 public <T> Future<T> options(GenericType<T> responseType)
169204 {
170 return method(HttpMethod.OPTIONS, responseType);
205 invocation.setMethod(HttpMethod.OPTIONS);
206 return invocation.submit(responseType);
171207 }
172208
173209 @Override
174210 public <T> Future<T> options(InvocationCallback<T> callback)
175211 {
176 return method(HttpMethod.OPTIONS, callback);
212 invocation.setMethod(HttpMethod.OPTIONS);
213 return invocation.submit(callback);
177214 }
178215
179216
181218 public Future<Response> method(String name)
182219 {
183220 invocation.setMethod(name);
184 invocation.setEntity(null);
185221 return invocation.submit();
186222 }
187223
189225 public <T> Future<T> method(String name, Class<T> responseType)
190226 {
191227 invocation.setMethod(name);
192 invocation.setEntity(null);
193228 return invocation.submit(responseType);
194229 }
195230
197232 public <T> Future<T> method(String name, GenericType<T> responseType)
198233 {
199234 invocation.setMethod(name);
200 invocation.setEntity(null);
201235 return invocation.submit(responseType);
202236 }
203237
205239 public <T> Future<T> method(String name, InvocationCallback<T> callback)
206240 {
207241 invocation.setMethod(name);
208 invocation.setEntity(null);
209242 return invocation.submit(callback);
210243 }
211244
240273 invocation.setEntity(entity);
241274 return invocation.submit(callback);
242275 }
276
277 public Future<Response> patch(Entity<?> entity) {
278 throw new NotImplementedYetException();
279 }
280
281 public <T> Future<T> patch(Entity<?> entity, Class<T> responseType)
282 {
283 return method("PATCH", entity, responseType);
284 }
285
286 public <T> Future<T> patch(Entity<?> entity, GenericType<T> responseType)
287 {
288 return method("PATCH", entity, responseType);
289 }
290
291 public <T> Future<T> patch(Entity<?> entity, InvocationCallback<T> callback)
292 {
293 return method("PATCH", entity, callback);
294 }
295
296
243297 }
+0
-282
resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientConfiguration.java less more
0 package org.jboss.resteasy.client.jaxrs.internal;
1
2 import org.jboss.resteasy.core.ThreadLocalResteasyProviderFactory;
3 import org.jboss.resteasy.spi.HeaderValueProcessor;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
6
7 import javax.ws.rs.RuntimeType;
8 import javax.ws.rs.client.ClientRequestFilter;
9 import javax.ws.rs.client.ClientResponseFilter;
10 import javax.ws.rs.container.DynamicFeature;
11 import javax.ws.rs.core.Configurable;
12 import javax.ws.rs.core.Configuration;
13 import javax.ws.rs.core.Feature;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.ext.ContextResolver;
16 import javax.ws.rs.ext.ExceptionMapper;
17 import javax.ws.rs.ext.MessageBodyReader;
18 import javax.ws.rs.ext.MessageBodyWriter;
19 import javax.ws.rs.ext.Providers;
20 import javax.ws.rs.ext.ReaderInterceptor;
21 import javax.ws.rs.ext.RuntimeDelegate;
22 import javax.ws.rs.ext.WriterInterceptor;
23 import java.lang.annotation.Annotation;
24 import java.lang.reflect.AccessibleObject;
25 import java.lang.reflect.Type;
26 import java.util.Collection;
27 import java.util.Map;
28 import java.util.Set;
29
30 /**
31 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
32 * @version $Revision: 1 $
33 */
34 public class ClientConfiguration implements Configuration, Configurable<ClientConfiguration>, Providers, HeaderValueProcessor
35 {
36 protected ResteasyProviderFactory providerFactory;
37
38 public ClientConfiguration(ResteasyProviderFactory factory)
39 {
40 if (factory instanceof ThreadLocalResteasyProviderFactory)
41 {
42 factory = ((ThreadLocalResteasyProviderFactory)factory).getDelegate();
43 }
44 this.providerFactory = new LocalResteasyProviderFactory(factory);
45 }
46
47 public ClientConfiguration(ClientConfiguration parent)
48 {
49 this(parent.getProviderFactory());
50 setProperties(parent.getProperties());
51 }
52
53 public void setProperties(Map<String, Object> newProps)
54 {
55 providerFactory.setProperties(newProps);
56 }
57
58 protected ResteasyProviderFactory getProviderFactory()
59 {
60 return providerFactory;
61 }
62
63 public Map<String, Object> getMutableProperties()
64 {
65 return providerFactory.getMutableProperties();
66 }
67
68 /**
69 * Convert an object to a header string. First try StringConverter, then HeaderDelegate, then object.toString()
70 *
71 * @param object
72 * @return
73 */
74 public String toHeaderString(Object object)
75 {
76 if (object instanceof String) return (String)object;
77 return providerFactory.toHeaderString(object);
78 }
79
80 public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
81 {
82 MessageBodyWriter<T> writer = providerFactory.getClientMessageBodyWriter(type, genericType, annotations, mediaType);
83 if (writer!=null)
84 LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName());
85 return writer;
86 }
87
88 public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
89 {
90 MessageBodyReader<T> reader = providerFactory.getClientMessageBodyReader(type, genericType, annotations, mediaType);
91 if (reader!=null)
92 LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName());
93 return reader;
94 }
95
96 public WriterInterceptor[] getWriterInterceptors(Class declaring, AccessibleObject target)
97 {
98 return providerFactory.getClientWriterInterceptorRegistry().postMatch(declaring, target);
99 }
100
101 public ReaderInterceptor[] getReaderInterceptors(Class declaring, AccessibleObject target)
102 {
103 return providerFactory.getClientReaderInterceptorRegistry().postMatch(declaring, target);
104 }
105
106 public ClientRequestFilter[] getRequestFilters(Class declaring, AccessibleObject target)
107 {
108 return providerFactory.getClientRequestFilters().postMatch(declaring, target);
109 }
110
111 public ClientResponseFilter[] getResponseFilters(Class declaring, AccessibleObject target)
112 {
113 return providerFactory.getClientResponseFilters().postMatch(declaring, target);
114 }
115
116 public Set<DynamicFeature> getDynamicFeatures()
117 {
118 return providerFactory.getClientDynamicFeatures();
119 }
120
121 public String toString(Object object)
122 {
123 return providerFactory.toString(object, object.getClass(), null, null);
124 }
125
126
127
128
129 // interface implementation
130
131 // Providers
132
133 @Override
134 public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type)
135 {
136 return providerFactory.getExceptionMapper(type);
137 }
138
139 @Override
140 public <T> ContextResolver<T> getContextResolver(Class<T> contextType, MediaType mediaType)
141 {
142 return providerFactory.getContextResolver(contextType, mediaType);
143 }
144
145 // Configuration
146
147 @Override
148 public Map<String, Object> getProperties()
149 {
150 return providerFactory.getProperties();
151 }
152
153 @Override
154 public Object getProperty(String name)
155 {
156 return providerFactory.getProperty(name);
157 }
158
159 @Override
160 public Set<Class<?>> getClasses()
161 {
162 return providerFactory.getProviderClasses();
163 }
164
165 @Override
166 public Set<Object> getInstances()
167 {
168 return providerFactory.getProviderInstances();
169 }
170
171 @Override
172 public ClientConfiguration register(Class<?> providerClass)
173 {
174 providerFactory.register(providerClass);
175 return this;
176 }
177
178 @Override
179 public ClientConfiguration register(Object provider)
180 {
181 providerFactory.register(provider);
182 return this;
183 }
184
185 @Override
186 public ClientConfiguration register(Class<?> providerClass, int priority)
187 {
188 providerFactory.register(providerClass, priority);
189 return this;
190 }
191
192 @Override
193 public ClientConfiguration register(Object provider, int Priority)
194 {
195 providerFactory.register(provider, Priority);
196 return this;
197 }
198
199 @Override
200 public ClientConfiguration property(String name, Object value)
201 {
202 providerFactory.property(name, value);
203 return this;
204 }
205
206 @Override
207 public Configuration getConfiguration()
208 {
209 return this;
210 }
211
212 @Override
213 public ClientConfiguration register(Class<?> componentClass, Class<?>... contracts)
214 {
215 providerFactory.register(componentClass, contracts);
216 return this;
217 }
218
219 @Override
220 public ClientConfiguration register(Class<?> componentClass, Map<Class<?>, Integer> contracts)
221 {
222 providerFactory.register(componentClass, contracts);
223 return this;
224 }
225
226 @Override
227 public ClientConfiguration register(Object component, Class<?>... contracts)
228 {
229 providerFactory.register(component, contracts);
230 return this;
231 }
232
233 @Override
234 public ClientConfiguration register(Object component, Map<Class<?>, Integer> contracts)
235 {
236 providerFactory.register(component, contracts);
237 return this;
238 }
239
240 @Override
241 public RuntimeType getRuntimeType()
242 {
243 return RuntimeType.CLIENT;
244 }
245
246 @Override
247 public Collection<String> getPropertyNames()
248 {
249 return providerFactory.getProperties().keySet();
250 }
251
252 @Override
253 public boolean isEnabled(Feature feature)
254 {
255 return providerFactory.isEnabled(feature);
256 }
257
258 @Override
259 public boolean isEnabled(Class<? extends Feature> featureClass)
260 {
261 return providerFactory.isEnabled(featureClass);
262 }
263
264 @Override
265 public boolean isRegistered(Object component)
266 {
267 return providerFactory.isRegistered(component);
268 }
269
270 @Override
271 public boolean isRegistered(Class<?> componentClass)
272 {
273 return providerFactory.isRegistered(componentClass);
274 }
275
276 @Override
277 public Map<Class<?>, Integer> getContracts(Class<?> componentClass)
278 {
279 return providerFactory.getContracts(componentClass);
280 }
281 }
00 package org.jboss.resteasy.client.jaxrs.internal;
11
2 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
3 import org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext;
4 import org.jboss.resteasy.core.interception.jaxrs.ClientWriterInterceptorContext;
5 import org.jboss.resteasy.specimpl.MultivaluedTreeMap;
6 import org.jboss.resteasy.spi.ResteasyProviderFactory;
7 import org.jboss.resteasy.util.DelegatingOutputStream;
8 import org.jboss.resteasy.util.Types;
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.io.OutputStream;
5 import java.io.Reader;
6 import java.lang.annotation.Annotation;
7 import java.lang.reflect.Type;
8 import java.net.URI;
9 import java.util.HashMap;
10 import java.util.Map;
11 import java.util.Optional;
12 import java.util.Set;
13 import java.util.concurrent.Callable;
14 import java.util.concurrent.ExecutionException;
15 import java.util.concurrent.ExecutorService;
16 import java.util.concurrent.Future;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.TimeoutException;
919
1020 import javax.ws.rs.BadRequestException;
1121 import javax.ws.rs.ClientErrorException;
3545 import javax.ws.rs.ext.Providers;
3646 import javax.ws.rs.ext.WriterInterceptor;
3747
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.OutputStream;
41 import java.io.Reader;
42 import java.lang.annotation.Annotation;
43 import java.lang.reflect.Type;
44 import java.net.URI;
45 import java.util.ArrayList;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Map.Entry;
49 import java.util.concurrent.Callable;
50 import java.util.concurrent.Future;
48 import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper;
49 import org.jboss.resteasy.client.jaxrs.AsyncClientHttpEngine;
50 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
51 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
52 import org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext;
53 import org.jboss.resteasy.core.interception.ClientWriterInterceptorContext;
54 import org.jboss.resteasy.plugins.providers.sse.EventInput;
55 import org.jboss.resteasy.spi.ResteasyProviderFactory;
56 import org.jboss.resteasy.util.DelegatingOutputStream;
57 import org.jboss.resteasy.util.Types;
5158
5259 /**
5360 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
5663 public class ClientInvocation implements Invocation
5764 {
5865 protected ResteasyClient client;
66
5967 protected ClientRequestHeaders headers;
68
6069 protected String method;
70
6171 protected Object entity;
72
6273 protected Type entityGenericType;
74
6375 protected Class<?> entityClass;
76
6477 protected Annotation[] entityAnnotations;
78
6579 protected ClientConfiguration configuration;
80
6681 protected URI uri;
82
6783 protected boolean chunked;
6884
69 // todo need a better solution for this. Apache Http Client 4 does not let you obtain the OutputStream before executing
70 // this request. is problematic for obtaining and setting
71 // the output stream. It also does not let you modify the request headers before the output stream is available
72 // Since MessageBodyWriter allows you to modify headers, you're s
85 // todo need a better solution for this. Apache Http Client 4 does not let you obtain the OutputStream before executing this request.
86 // That is problematic for wrapping the output stream in e.g. a RequestFilter for transparent compressing.
7387 protected DelegatingOutputStream delegatingOutputStream = new DelegatingOutputStream();
88
7489 protected OutputStream entityStream = delegatingOutputStream;
7590
7691 public ClientInvocation(ResteasyClient client, URI uri, ClientRequestHeaders headers, ClientConfiguration parent)
7994 this.client = client;
8095 this.configuration = new ClientConfiguration(parent);
8196 this.headers = headers;
82 }
83
84 ClientInvocation(ClientInvocation clientInvocation)
85 {
86 this.client = clientInvocation.client;
87 this.configuration = new ClientConfiguration(clientInvocation.configuration);
88 this.headers = new ClientRequestHeaders(this.configuration);
89 MultivaluedTreeMap.copy(clientInvocation.headers.getHeaders(), this.headers.headers);
90 this.method = clientInvocation.method;
91 this.entity = clientInvocation.entity;
92 this.entityGenericType = clientInvocation.entityGenericType;
93 this.entityClass = clientInvocation.entityClass;
94 this.entityAnnotations = clientInvocation.entityAnnotations;
95 this.uri = clientInvocation.uri;
96 this.chunked = clientInvocation.chunked;
9797 }
9898
9999 /**
119119 else
120120 {
121121 T rtn = response.readEntity(responseType, annotations);
122 if (InputStream.class.isInstance(rtn)
123 || Reader.class.isInstance(rtn))
122 if (InputStream.class.isInstance(rtn) || Reader.class.isInstance(rtn)
123 || EventInput.class.isInstance(rtn))
124124 {
125125 if (response instanceof ClientResponse)
126126 {
127 ClientResponse clientResponse = (ClientResponse)response;
127 ClientResponse clientResponse = (ClientResponse) response;
128128 clientResponse.noReleaseConnection();
129129 }
130130 }
158158 }
159159 finally
160160 {
161 if (response.getMediaType() == null) response.close();
161 if (response.getMediaType() == null)
162 response.close();
162163 }
163164 }
164165 try
185186 }
186187 }
187188 }
188 if (status >= 300 && status < 400) throw new RedirectionException(response);
189 if (status >= 300 && status < 400)
190 throw new RedirectionException(response);
189191
190192 return handleErrorStatus(response);
191193 }
192194 finally
193195 {
194196 // close if no content
195 if (response.getMediaType() == null) response.close();
197 if (response.getMediaType() == null)
198 response.close();
196199 }
197200
198201 }
209212 final int status = response.getStatus();
210213 switch (status)
211214 {
212 case 400:
215 case 400 :
213216 throw new BadRequestException(response);
214 case 401:
217 case 401 :
215218 throw new NotAuthorizedException(response);
216 case 403:
219 case 403 :
217220 throw new ForbiddenException(response);
218 case 404:
221 case 404 :
219222 throw new NotFoundException(response);
220 case 405:
223 case 405 :
221224 throw new NotAllowedException(response);
222 case 406:
225 case 406 :
223226 throw new NotAcceptableException(response);
224 case 415:
227 case 415 :
225228 throw new NotSupportedException(response);
226 case 500:
229 case 500 :
227230 throw new InternalServerErrorException(response);
228 case 503:
231 case 503 :
229232 throw new ServiceUnavailableException(response);
230 default:
233 default :
231234 break;
232235 }
233236
234 if (status >= 400 && status < 500) throw new ClientErrorException(response);
235 if (status >= 500) throw new ServerErrorException(response);
236
237 if (status >= 400 && status < 500)
238 throw new ClientErrorException(response);
239 if (status >= 500)
240 throw new ServerErrorException(response);
237241
238242 throw new WebApplicationException(response);
239243 }
366370 {
367371 this.entity = null;
368372 this.entityClass = null;
369 this.entityGenericType = null;
373 this.entityGenericType = null;
370374 }
371375 else
372376 {
385389 }
386390
387391 WriterInterceptor[] interceptors = getWriterInterceptors();
388 AbstractWriterInterceptorContext ctx = new ClientWriterInterceptorContext(interceptors, configuration.getProviderFactory(), entity, entityClass, entityGenericType, entityAnnotations, headers.getMediaType(), headers.getHeaders(), outputStream, getMutableProperties());
392 AbstractWriterInterceptorContext ctx = new ClientWriterInterceptorContext(interceptors,
393 configuration.getProviderFactory(), entity, entityClass, entityGenericType, entityAnnotations,
394 headers.getMediaType(), headers.getHeaders(), outputStream, getMutableProperties());
389395 ctx.proceed();
390396 }
391397
392
393398 public WriterInterceptor[] getWriterInterceptors()
394399 {
395400 return configuration.getWriterInterceptors(null, null);
407412
408413 // Invocation methods
409414
410
411415 public Configuration getConfiguration()
412416 {
413417 return configuration;
424428 }
425429
426430 @Override
427 public Response invoke()
428 {
429 Providers current = ResteasyProviderFactory.getContextData(Providers.class);
430 ResteasyProviderFactory.pushContext(Providers.class, configuration);
431 public ClientResponse invoke()
432 {
433 Providers current = pushProvidersContext();
431434 try
432435 {
433436 ClientRequestContextImpl requestContext = new ClientRequestContextImpl(this);
434 ClientRequestFilter[] requestFilters = getRequestFilters();
435 ClientResponse aborted = null;
436 if (requestFilters != null && requestFilters.length > 0)
437 {
438 for (ClientRequestFilter filter : requestFilters)
439 {
440 try
441 {
442 filter.filter(requestContext);
443 if (requestContext.getAbortedWithResponse() != null)
444 {
445 aborted = new AbortedResponse(configuration, requestContext.getAbortedWithResponse());
446 break;
447 }
448 }
449 catch (ProcessingException e)
450 {
451 throw e;
452 }
453 catch (Throwable e)
454 {
455 throw new ProcessingException(e);
456 }
457 }
458 }
437 ClientResponse aborted = filterRequest(requestContext);
438
459439 // spec requires that aborted response go through filter/interceptor chains.
460 ClientResponse response = aborted;
461 if (response == null) response = client.httpEngine().invoke(this);
462 response.setProperties(configuration.getMutableProperties());
463
464 ClientResponseFilter[] responseFilters = getResponseFilters();
465 if (responseFilters != null && responseFilters.length > 0)
466 {
467 ClientResponseContextImpl responseContext = new ClientResponseContextImpl(response);
468 for (ClientResponseFilter filter : responseFilters)
469 {
470 try
471 {
472 filter.filter(requestContext, responseContext);
473 }
474 catch (ResponseProcessingException e)
475 {
476 throw e;
477 }
478 catch (Throwable e)
479 {
480 throw new ResponseProcessingException(response, e);
481 }
482 }
483 }
484 return response;
440 ClientResponse response = (aborted != null) ? aborted : client.httpEngine().invoke(this);
441 return filterResponse(requestContext, response);
485442 }
486443 finally
487444 {
488 ResteasyProviderFactory.popContextData(Providers.class);
489 if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
445 popProvidersContext(current);
490446 }
491447 }
492448
495451 public <T> T invoke(Class<T> responseType)
496452 {
497453 Response response = invoke();
498 if (Response.class.equals(responseType)) return (T)response;
454 if (Response.class.equals(responseType))
455 return (T) response;
499456 return extractResult(new GenericType<T>(responseType), response, null);
500457 }
501458
504461 public <T> T invoke(GenericType<T> responseType)
505462 {
506463 Response response = invoke();
507 if (responseType.getRawType().equals(Response.class)) return (T)response;
508 return ClientInvocation.extractResult(responseType, response, null);
464 if (responseType.getRawType().equals(Response.class))
465 return (T) response;
466 return extractResult(responseType, response, null);
509467 }
510468
511469 @Override
512470 public Future<Response> submit()
513471 {
514 return client.asyncInvocationExecutor().submit(new Callable<Response>()
472 return doSubmit(false, null, new AsyncClientHttpEngine.ResultExtractor<Response>()
515473 {
516474 @Override
517 public Response call() throws Exception
518 {
519 return invoke();
475 public Response extractResult(ClientResponse response)
476 {
477 return response;
520478 }
521479 });
522480 }
523
524481
525482 @Override
526483 public <T> Future<T> submit(final Class<T> responseType)
527484 {
528 return client.asyncInvocationExecutor().submit(new Callable<T>()
485 return doSubmit(false, null, new AsyncClientHttpEngine.ResultExtractor<T>()
486 {
487 @Override
488 public T extractResult(ClientResponse response)
489 {
490 if (Response.class.equals(responseType))
491 return (T) response;
492 return ClientInvocation.extractResult(new GenericType<T>(responseType), response, null);
493 }
494 });
495 }
496
497 @Override
498 public <T> Future<T> submit(final GenericType<T> responseType)
499 {
500 return doSubmit(false, null, new AsyncClientHttpEngine.ResultExtractor<T>()
501 {
502 @Override
503 public T extractResult(ClientResponse response)
504 {
505 if (responseType.getRawType().equals(Response.class))
506 return (T) response;
507 return ClientInvocation.extractResult(responseType, response, null);
508 }
509 });
510 }
511
512 @SuppressWarnings(
513 {"rawtypes", "unchecked"})
514 @Override
515 public <T> Future<T> submit(final InvocationCallback<T> callback)
516 {
517 GenericType<T> genericType = (GenericType<T>) new GenericType<Object>()
518 {
519 };
520 Type[] typeInfo = Types.getActualTypeArgumentsOfAnInterface(callback.getClass(), InvocationCallback.class);
521 if (typeInfo != null)
522 {
523 genericType = new GenericType(typeInfo[0]);
524 }
525
526 final GenericType<T> responseType = genericType;
527 return doSubmit(true, callback, new AsyncClientHttpEngine.ResultExtractor<T>()
528 {
529 @Override
530 public T extractResult(ClientResponse response)
531 {
532 if (responseType.getRawType().equals(Response.class))
533 return (T) response;
534 return ClientInvocation.extractResult(responseType, response, null);
535 }
536 });
537 }
538
539 @Override
540 public Invocation property(String name, Object value)
541 {
542 configuration.property(name, value);
543 return this;
544 }
545
546 // internals
547
548 private Providers pushProvidersContext()
549 {
550 Providers current = ResteasyProviderFactory.getContextData(Providers.class);
551 ResteasyProviderFactory.pushContext(Providers.class, configuration);
552 return current;
553 }
554
555 private void popProvidersContext(Providers current)
556 {
557 ResteasyProviderFactory.popContextData(Providers.class);
558 if (current != null)
559 ResteasyProviderFactory.pushContext(Providers.class, current);
560 }
561
562 private ClientResponse filterRequest(ClientRequestContextImpl requestContext)
563 {
564 ClientRequestFilter[] requestFilters = getRequestFilters();
565 ClientResponse aborted = null;
566 if (requestFilters != null && requestFilters.length > 0)
567 {
568 for (ClientRequestFilter filter : requestFilters)
569 {
570 try
571 {
572 filter.filter(requestContext);
573 if (requestContext.getAbortedWithResponse() != null)
574 {
575 aborted = new AbortedResponse(configuration, requestContext.getAbortedWithResponse());
576 break;
577 }
578 }
579 catch (ProcessingException e)
580 {
581 throw e;
582 }
583 catch (Throwable e)
584 {
585 throw new ProcessingException(e);
586 }
587 }
588 }
589 return aborted;
590 }
591
592 private ClientResponse filterResponse(ClientRequestContextImpl requestContext, ClientResponse response)
593 {
594 response.setProperties(configuration.getMutableProperties());
595
596 ClientResponseFilter[] responseFilters = getResponseFilters();
597 if (responseFilters != null && responseFilters.length > 0)
598 {
599 ClientResponseContextImpl responseContext = new ClientResponseContextImpl(response);
600 for (ClientResponseFilter filter : responseFilters)
601 {
602 try
603 {
604 filter.filter(requestContext, responseContext);
605 }
606 catch (ResponseProcessingException e)
607 {
608 throw e;
609 }
610 catch (Throwable e)
611 {
612 throw new ResponseProcessingException(response, e);
613 }
614 }
615 }
616 Map<ResponseExceptionMapper, Integer> mappers = new HashMap<>();
617 Set<Object> instances = configuration.getInstances();
618 for (Object instance : instances) {
619 if(instance instanceof ResponseExceptionMapper) {
620 ResponseExceptionMapper candiate = (ResponseExceptionMapper) instance;
621 if (candiate.handles(response.getStatus(), response.getHeaders())) {
622 mappers.put(candiate, candiate.getPriority());
623 }
624 }
625 }
626
627 if(mappers.size()>0) {
628 Map<Optional<Throwable>, Integer> errors = new HashMap<>();
629
630 mappers.forEach( (m, i) -> {
631 Optional<Throwable> t = Optional.ofNullable(m.toThrowable(response));
632 errors.put(t, i);
633 });
634
635 Optional<Throwable> prioritised = Optional.empty();
636 for (Optional<Throwable> throwable : errors.keySet()) {
637 if(throwable.isPresent()) {
638 if(!prioritised.isPresent())
639 prioritised = throwable;
640 else if(errors.get(throwable)<errors.get(prioritised))
641 prioritised = throwable;
642
643 }
644 }
645
646 if(prioritised.isPresent()) // strange rule from the spec
647 throw (WebApplicationException) prioritised.get();
648 }
649
650 return response;
651 }
652
653 private <T> Future<T> doSubmit(boolean buffered, InvocationCallback<T> callback,
654 AsyncClientHttpEngine.ResultExtractor<T> extractor)
655 {
656 ClientHttpEngine httpEngine = client.httpEngine();
657 if (httpEngine instanceof AsyncClientHttpEngine)
658 {
659 return asyncSubmit((AsyncClientHttpEngine) httpEngine, buffered, callback, extractor);
660 }
661 else
662 {
663 // never buffered, but always blocks in a thread
664 return executorSubmit(client.asyncInvocationExecutor(), callback, extractor);
665 }
666 }
667
668 private <T> Future<T> asyncSubmit(AsyncClientHttpEngine asyncHttpEngine, boolean buffered,
669 InvocationCallback<T> callback, final AsyncClientHttpEngine.ResultExtractor<T> extractor)
670 {
671 final ClientRequestContextImpl requestContext = new ClientRequestContextImpl(this);
672 Providers current = pushProvidersContext();
673 try
674 {
675 ClientResponse aborted = filterRequest(requestContext);
676 if (aborted != null)
677 {
678 // spec requires that aborted response go through filter/interceptor chains.
679 aborted = filterResponse(requestContext, aborted);
680 T result = extractor.extractResult(aborted);
681 callCompletedNoThrow(callback, result);
682 return new CompletedFuture<T>(result, null);
683 }
684 }
685 catch (Exception ex)
686 {
687 callFailedNoThrow(callback, ex);
688 return new CompletedFuture<T>(null, new ExecutionException(ex));
689 }
690 finally
691 {
692 popProvidersContext(current);
693 }
694
695 return asyncHttpEngine.submit(this, buffered, callback, new AsyncClientHttpEngine.ResultExtractor<T>()
696 {
697
698 @Override
699 public T extractResult(ClientResponse response)
700 {
701 Providers current = pushProvidersContext();
702 try
703 {
704 return extractor.extractResult(filterResponse(requestContext, response));
705 }
706 finally
707 {
708 popProvidersContext(current);
709 }
710 }
711 });
712 }
713
714 private <T> Future<T> executorSubmit(ExecutorService executor, final InvocationCallback<T> callback,
715 final AsyncClientHttpEngine.ResultExtractor<T> extractor)
716 {
717 return executor.submit(new Callable<T>()
529718 {
530719 @Override
531720 public T call() throws Exception
532721 {
533 return invoke(responseType);
722 // ensure the future and the callback see the same result
723 T result = null;
724 ClientResponse response = null;
725 try
726 {
727 response = invoke(); // does filtering too
728 result = extractor.extractResult(response);
729 callCompletedNoThrow(callback, result);
730 return result;
731 }
732 catch (Exception e)
733 {
734 callFailedNoThrow(callback, e);
735 throw e;
736 }
737 finally
738 {
739 if (response != null && callback != null)
740 response.close();
741 }
534742 }
535743 });
536744 }
537745
538 @Override
539 public <T> Future<T> submit(final GenericType<T> responseType)
540 {
541 return client.asyncInvocationExecutor().submit(new Callable<T>()
542 {
543 @Override
544 public T call() throws Exception
545 {
546 return invoke(responseType);
547 }
548 });
549 }
550
551 @SuppressWarnings({ "rawtypes", "unchecked" })
552 @Override
553 public <T> Future<T> submit(final InvocationCallback<T> callback)
554 {
555 GenericType<T> genericType = (GenericType<T>)new GenericType<Object>() {};
556 Type[] typeInfo = Types.getActualTypeArgumentsOfAnInterface(callback.getClass(), InvocationCallback.class);
557 if (typeInfo != null)
558 {
559 genericType = new GenericType(typeInfo[0]);
560 }
561
562 final GenericType<T> responseType = genericType;
563 return client.asyncInvocationExecutor().submit(new Callable<T>()
564 {
565 @Override
566 public T call() throws Exception
567 {
568 T result = null;
569 try {
570 result = invoke(responseType);
571 }
572 catch (Exception e) {
573 callback.failed(e);
574 throw e;
575 }
576 try {
577 callback.completed(result);
578 return result;
579 }
580 finally {
581 if (result != null && result instanceof Response)
582 {
583 ((Response)result).close();
584 }
585 }
586 }
587 });
588
589 }
590
591 @Override
592 public Invocation property(String name, Object value)
593 {
594 configuration.property(name, value);
595 return this;
746 private <T> void callCompletedNoThrow(InvocationCallback<T> callback, T result)
747 {
748 if (callback != null)
749 {
750 try
751 {
752 callback.completed(result);
753 }
754 catch (Exception e)
755 {
756 //logger.error("ignoring exception in InvocationCallback", e);
757 }
758 }
759 }
760
761 private <T> void callFailedNoThrow(InvocationCallback<T> callback, Exception exception)
762 {
763 if (callback != null)
764 {
765 try
766 {
767 callback.failed(exception);
768 }
769 catch (Exception e)
770 {
771 //logger.error("ignoring exception in InvocationCallback", e);
772 }
773 }
774 }
775
776 private static class CompletedFuture<T> implements Future<T>
777 {
778
779 private final T result;
780
781 private final ExecutionException ex;
782
783 public CompletedFuture(T result, ExecutionException ex)
784 {
785 this.ex = ex;
786 this.result = result;
787 }
788
789 @Override
790 public boolean cancel(boolean mayInterruptIfRunning)
791 {
792 return false;
793 }
794
795 @Override
796 public boolean isCancelled()
797 {
798 return false;
799 }
800
801 @Override
802 public boolean isDone()
803 {
804 return true;
805 }
806
807 @Override
808 public T get() throws InterruptedException, ExecutionException
809 {
810 if (ex != null)
811 throw ex;
812 return result;
813 }
814
815 @Override
816 public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
817 {
818 return get();
819 }
596820 }
597821 }
+0
-320
resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocationBuilder.java less more
0 package org.jboss.resteasy.client.jaxrs.internal;
1
2 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
3
4 import javax.ws.rs.HttpMethod;
5 import javax.ws.rs.client.AsyncInvoker;
6 import javax.ws.rs.client.Entity;
7 import javax.ws.rs.client.Invocation;
8 import javax.ws.rs.core.CacheControl;
9 import javax.ws.rs.core.Cookie;
10 import javax.ws.rs.core.GenericType;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.MultivaluedMap;
13 import javax.ws.rs.core.Response;
14 import java.net.URI;
15 import java.util.Locale;
16
17 /**
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 */
21 public class ClientInvocationBuilder implements Invocation.Builder
22 {
23 private final ClientInvocation invocation;
24
25 public ClientInvocationBuilder(ResteasyClient client, URI uri, ClientConfiguration configuration)
26 {
27 invocation = new ClientInvocation(client, uri, new ClientRequestHeaders(configuration), configuration);
28 }
29
30 public ClientRequestHeaders getHeaders()
31 {
32 return invocation.headers;
33 }
34
35 @Override
36 public Invocation.Builder accept(String... mediaTypes)
37 {
38 getHeaders().accept(mediaTypes);
39 return this;
40 }
41
42 @Override
43 public Invocation.Builder accept(MediaType... mediaTypes)
44 {
45 getHeaders().accept(mediaTypes);
46 return this;
47 }
48
49 @Override
50 public Invocation.Builder acceptLanguage(Locale... locales)
51 {
52 getHeaders().acceptLanguage(locales);
53 return this;
54 }
55
56 @Override
57 public Invocation.Builder acceptLanguage(String... locales)
58 {
59 getHeaders().acceptLanguage(locales);
60 return this;
61 }
62
63 @Override
64 public Invocation.Builder acceptEncoding(String... encodings)
65 {
66 getHeaders().acceptEncoding(encodings);
67 return this;
68 }
69
70 @Override
71 public Invocation.Builder cookie(Cookie cookie)
72 {
73 if (!(Cookie.class.equals(cookie.getClass())))
74 {
75 cookie = new Cookie(cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getVersion());
76 }
77 getHeaders().cookie(cookie);
78 return this;
79 }
80
81 @Override
82 public Invocation.Builder cookie(String name, String value)
83 {
84 getHeaders().cookie(new Cookie(name, value));
85 return this;
86 }
87
88 @Override
89 public Invocation.Builder cacheControl(CacheControl cacheControl)
90 {
91 getHeaders().cacheControl(cacheControl);
92 return this;
93 }
94
95 @Override
96 public Invocation.Builder header(String name, Object value)
97 {
98 getHeaders().header(name, value);
99 return this;
100 }
101
102 @Override
103 public Invocation.Builder headers(MultivaluedMap<String, Object> headers)
104 {
105 getHeaders().setHeaders(headers);
106 return this;
107 }
108
109 @Override
110 public Invocation build(String method)
111 {
112 return build(method, null);
113 }
114
115 @Override
116 public Invocation build(String method, Entity<?> entity)
117 {
118 invocation.setMethod(method);
119 invocation.setEntity(entity);
120 return new ClientInvocation(this.invocation);
121 }
122
123 @Override
124 public Invocation buildGet()
125 {
126 return build(HttpMethod.GET);
127 }
128
129 @Override
130 public Invocation buildDelete()
131 {
132 return build(HttpMethod.DELETE);
133 }
134
135 @Override
136 public Invocation buildPost(Entity<?> entity)
137 {
138 return build(HttpMethod.POST, entity);
139 }
140
141 @Override
142 public Invocation buildPut(Entity<?> entity)
143 {
144 return build(HttpMethod.PUT, entity);
145 }
146
147 @Override
148 public AsyncInvoker async()
149 {
150 return new AsynchronousInvoke(new ClientInvocation(this.invocation));
151 }
152
153 @Override
154 public Response get()
155 {
156 return buildGet().invoke();
157 }
158
159 @Override
160 public <T> T get(Class<T> responseType)
161 {
162 return buildGet().invoke(responseType);
163 }
164
165 @Override
166 public <T> T get(GenericType<T> responseType)
167 {
168 return buildGet().invoke(responseType);
169 }
170
171 @Override
172 public Response put(Entity<?> entity)
173 {
174 return buildPut(entity).invoke();
175 }
176
177 @Override
178 public <T> T put(Entity<?> entity, Class<T> responseType)
179 {
180 return buildPut(entity).invoke(responseType);
181 }
182
183 @Override
184 public <T> T put(Entity<?> entity, GenericType<T> responseType)
185 {
186 return buildPut(entity).invoke(responseType);
187 }
188
189 @Override
190 public Response post(Entity<?> entity)
191 {
192 return buildPost(entity).invoke();
193 }
194
195 @Override
196 public <T> T post(Entity<?> entity, Class<T> responseType)
197 {
198 return buildPost(entity).invoke(responseType);
199 }
200
201 @Override
202 public <T> T post(Entity<?> entity, GenericType<T> responseType)
203 {
204 return buildPost(entity).invoke(responseType);
205 }
206
207 @Override
208 public Response delete()
209 {
210 return buildDelete().invoke();
211 }
212
213 @Override
214 public <T> T delete(Class<T> responseType)
215 {
216 return buildDelete().invoke(responseType);
217 }
218
219 @Override
220 public <T> T delete(GenericType<T> responseType)
221 {
222 return buildDelete().invoke(responseType);
223 }
224
225 @Override
226 public Response head()
227 {
228 return build(HttpMethod.HEAD).invoke();
229 }
230
231 @Override
232 public Response options()
233 {
234 return build(HttpMethod.OPTIONS).invoke();
235 }
236
237 @Override
238 public <T> T options(Class<T> responseType)
239 {
240 return build(HttpMethod.OPTIONS).invoke(responseType);
241 }
242
243 @Override
244 public <T> T options(GenericType<T> responseType)
245 {
246 return build(HttpMethod.OPTIONS).invoke(responseType);
247 }
248
249 @Override
250 public Response trace()
251 {
252 return build("TRACE").invoke();
253 }
254
255 @Override
256 public <T> T trace(Class<T> responseType)
257 {
258 return build("TRACE").invoke(responseType);
259 }
260
261 @Override
262 public <T> T trace(GenericType<T> responseType)
263 {
264 return build("TRACE").invoke(responseType);
265 }
266
267 @Override
268 public Response method(String name)
269 {
270 return build(name).invoke();
271 }
272
273 @Override
274 public <T> T method(String name, Class<T> responseType)
275 {
276 return build(name).invoke(responseType);
277 }
278
279 @Override
280 public <T> T method(String name, GenericType<T> responseType)
281 {
282 return build(name).invoke(responseType);
283 }
284
285 @Override
286 public Response method(String name, Entity<?> entity)
287 {
288 return build(name, entity).invoke();
289 }
290
291 @Override
292 public <T> T method(String name, Entity<?> entity, Class<T> responseType)
293 {
294 return build(name, entity).invoke(responseType);
295 }
296
297 @Override
298 public <T> T method(String name, Entity<?> entity, GenericType<T> responseType)
299 {
300 return build(name, entity).invoke(responseType);
301 }
302
303 @Override
304 public Invocation.Builder property(String name, Object value)
305 {
306 invocation.property(name, value);
307 return this;
308 }
309
310 public boolean isChunked()
311 {
312 return invocation.isChunked();
313 }
314
315 public void setChunked(boolean chunked)
316 {
317 invocation.setChunked(chunked);
318 }
319 }
0 package org.jboss.resteasy.client.jaxrs.internal;
1
2 import javax.ws.rs.client.Invocation;
3
4 public interface ClientInvocationBuilderInterface extends Invocation.Builder
5 {
6 ClientRequestHeaders getHeaders();
7 void setChunked(boolean chunked);
8 public ClientInvocation getInvocation();
9 }
22 import org.jboss.resteasy.client.jaxrs.i18n.Messages;
33 import org.jboss.resteasy.core.Headers;
44 import org.jboss.resteasy.core.ProvidersContextRetainer;
5 import org.jboss.resteasy.core.interception.jaxrs.ClientReaderInterceptorContext;
5 import org.jboss.resteasy.core.interception.ClientReaderInterceptorContext;
6 import org.jboss.resteasy.plugins.providers.sse.EventInput;
67 import org.jboss.resteasy.specimpl.BuiltResponse;
78 import org.jboss.resteasy.spi.HeaderValueProcessor;
89 import org.jboss.resteasy.spi.MarshalledEntity;
3940 protected Map<String, Object> properties;
4041 protected ClientConfiguration configuration;
4142 protected byte[] bufferedEntity;
43 protected boolean streamFullyRead;
4244
4345 protected ClientResponse(ClientConfiguration configuration)
4446 {
6971 }
7072
7173 @Override
72 public Object getEntity()
74 public synchronized Object getEntity()
7375 {
7476 abortIfClosed();
75 return super.getEntity();
77 Object entity = super.getEntity();
78 if (entity != null)
79 {
80 return entity;
81 }
82 //Check if the entity was previously fully consumed
83 if (streamFullyRead && bufferedEntity == null)
84 {
85 throw new IllegalStateException();
86 }
87 return getEntityStream();
88 }
89
90 @Override
91 public Class<?> getEntityClass()
92 {
93 Class<?> classs = super.getEntityClass();
94 if (classs != null)
95 {
96 return classs;
97 }
98 Object entity = null;
99 try
100 {
101 entity = getEntity();
102 }
103 catch (Exception e)
104 {
105 }
106 return entity != null ? entity.getClass() : null;
76107 }
77108
78109 @Override
142173 this.response = response;
143174 }
144175
176 public int read() throws IOException
177 {
178 return checkEOF(super.read());
179 }
180
181 public int read(byte b[]) throws IOException
182 {
183 return checkEOF(super.read(b));
184 }
185
186 public int read(byte b[], int off, int len) throws IOException
187 {
188 return checkEOF(super.read(b, off, len));
189 }
190
191 private int checkEOF(int v)
192 {
193 if (v < 0)
194 {
195 response.streamFullyRead = true;
196 }
197 return v;
198 }
199
145200 @Override
146201 public void close() throws IOException {
147202 super.close();
200255 {
201256 try
202257 {
203 close();
258 if (!EventInput.class.isInstance(entity))
259 {
260 close();
261 }
204262 }
205263 catch (Exception ignored)
206264 {
316374 if (bufferedEntity != null) return true;
317375 if (entity != null) return false;
318376 if (metadata.getFirst(HttpHeaderNames.CONTENT_TYPE) == null) return false;
377 InputStream is = getInputStream();
378 if (is == null) return false;
319379 try
320380 {
321 bufferedEntity = ReadFromStream.readFromStream(1024, getInputStream());
381 bufferedEntity = ReadFromStream.readFromStream(1024, is);
322382 }
323383 catch (IOException e)
324384 {
44 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
55 import org.jboss.resteasy.client.jaxrs.i18n.Messages;
66 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
7 import org.jboss.resteasy.spi.ResteasyProviderFactory;
78
89 import javax.ws.rs.client.Invocation;
910 import javax.ws.rs.core.Configuration;
104105 public URI getUri()
105106 {
106107 client.abortIfClosed();
107 return uriBuilder.build();
108 return uriBuilder.clone().build();
108109 }
109110
110111 @Override
155156 if (name == null) throw new NullPointerException(Messages.MESSAGES.nameWasNull());
156157 if (value == null) throw new NullPointerException(Messages.MESSAGES.valueWasNull());
157158 String val = configuration.toString(value);
158 UriBuilder copy = uriBuilder.clone().resolveTemplate(name, val);
159 UriBuilder copy = uriBuilder.resolveTemplate(name, val);
159160 ClientWebTarget target = new ClientWebTarget(client, copy, configuration);
160161 return target;
161162 }
173174 String val = configuration.toString(entry.getValue());
174175 vals.put(entry.getKey(), val);
175176 }
176 UriBuilder copy = uriBuilder.clone().resolveTemplates(vals);
177 UriBuilder copy = uriBuilder.resolveTemplates(vals);
177178 ClientWebTarget target = new ClientWebTarget(client, copy, configuration);
178179 return target;
179180 }
185186 if (name == null) throw new NullPointerException(Messages.MESSAGES.nameWasNull());
186187 if (value == null) throw new NullPointerException(Messages.MESSAGES.valueWasNull());
187188 String val = configuration.toString(value);
188 UriBuilder copy = uriBuilder.clone().resolveTemplate(name, val, encodeSlashInPath);
189 UriBuilder copy = uriBuilder.resolveTemplate(name, val, encodeSlashInPath);
189190 ClientWebTarget target = new ClientWebTarget(client, copy, configuration);
190191 return target;
191192 }
197198 if (name == null) throw new NullPointerException(Messages.MESSAGES.nameWasNull());
198199 if (value == null) throw new NullPointerException(Messages.MESSAGES.valueWasNull());
199200 String val = configuration.toString(value);
200 UriBuilder copy = uriBuilder.clone().resolveTemplateFromEncoded(name, val);
201 UriBuilder copy = uriBuilder.resolveTemplateFromEncoded(name, val);
201202 ClientWebTarget target = new ClientWebTarget(client, copy, configuration);
202203 return target;
203204 }
215216 String val = configuration.toString(entry.getValue());
216217 vals.put(entry.getKey(), val);
217218 }
218 UriBuilder copy = uriBuilder.clone().resolveTemplatesFromEncoded(vals) ;
219 UriBuilder copy = uriBuilder.resolveTemplatesFromEncoded(vals) ;
219220 ClientWebTarget target = new ClientWebTarget(client, copy, configuration);
220221 return target;
221222 }
233234 String val = configuration.toString(entry.getValue());
234235 vals.put(entry.getKey(), val);
235236 }
236 UriBuilder copy = uriBuilder.clone().resolveTemplates(vals, encodeSlashInPath) ;
237 UriBuilder copy = uriBuilder.resolveTemplates(vals, encodeSlashInPath) ;
237238 ClientWebTarget target = new ClientWebTarget(client, copy, configuration);
238239 return target;
239240 }
251252 else
252253 {
253254 String[] stringValues = toStringValues(values);
254 copy.matrixParam(name, stringValues);
255 copy = uriBuilder.clone().matrixParam(name, stringValues);
255256 }
256257 return new ClientWebTarget(client, copy, configuration);
257258 }
279280 else
280281 {
281282 String[] stringValues = toStringValues(values);
282 copy.queryParam(name, stringValues);
283 copy = uriBuilder.clone().queryParam(name, stringValues);
283284 }
284285 return new ClientWebTarget(client, copy, configuration);
285286 }
338339 }
339340 return new ClientWebTarget(client, copy, configuration);
340341 }
342
343 private ClientInvocationBuilderInterface newInvocationBuilder(ResteasyClient client, URI uri, ClientConfiguration configuration)
344 {
345 try {
346 Class<?> clazz = Class.forName("org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder");
347 return (ClientInvocationBuilderInterface)clazz.getConstructor(ResteasyClient.class, URI.class, ClientConfiguration.class).newInstance(client, uri, configuration);
348 } catch (Exception e) {
349 throw new RuntimeException(e);
350 }
351 }
341352
342353 @Override
343354 public Invocation.Builder request()
344355 {
345356 client.abortIfClosed();
346 ClientInvocationBuilder builder = new ClientInvocationBuilder(client, uriBuilder.build(), configuration);
357 ClientInvocationBuilderInterface builder = newInvocationBuilder(client, uriBuilder.build(), configuration);
347358 builder.setChunked(chunked);
348359 return builder;
349360 }
352363 public Invocation.Builder request(String... acceptedResponseTypes)
353364 {
354365 client.abortIfClosed();
355 ClientInvocationBuilder builder = new ClientInvocationBuilder(client, uriBuilder.build(), configuration);
366 ClientInvocationBuilderInterface builder = newInvocationBuilder(client, uriBuilder.build(), configuration);
356367 builder.getHeaders().accept(acceptedResponseTypes);
357368 builder.setChunked(chunked);
358369 return builder;
362373 public Invocation.Builder request(MediaType... acceptedResponseTypes)
363374 {
364375 client.abortIfClosed();
365 ClientInvocationBuilder builder = new ClientInvocationBuilder(client, uriBuilder.build(), configuration);
376 ClientInvocationBuilderInterface builder = newInvocationBuilder(client, uriBuilder.build(), configuration);
366377 builder.getHeaders().accept(acceptedResponseTypes);
367378 builder.setChunked(chunked);
368379 return builder;
447458 this.chunked = chunked;
448459 return this;
449460 }
450 }
461 }
33 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
44 import org.jboss.resteasy.client.jaxrs.internal.ClientConfiguration;
55 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
6 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder;
7 import org.jboss.resteasy.client.jaxrs.internal.ClientRequestHeaders;
6 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilderInterface;
87 import org.jboss.resteasy.client.jaxrs.internal.ClientResponse;
98 import org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.ClientContext;
109 import org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.DefaultEntityExtractorFactory;
1918 import javax.ws.rs.client.WebTarget;
2019 import javax.ws.rs.container.DynamicFeature;
2120 import javax.ws.rs.container.ResourceInfo;
22 import javax.ws.rs.core.Configuration;
2321 import javax.ws.rs.core.MediaType;
24
2522 import java.lang.reflect.Method;
2623
2724 /**
3330 protected String httpMethod;
3431 protected Method method;
3532 protected Class<?> declaring;
36 protected MediaType[] accepts;
33 protected MediaType accepts;
3734 protected Object[] processors;
3835 protected ResteasyWebTarget webTarget;
3936 protected boolean followRedirects;
8380 this.extractor = entityExtractorFactory.createExtractor(method);
8481 }
8582
86 public MediaType[] getAccepts()
83 public MediaType getAccepts()
8784 {
8885 return accepts;
8986 }
108105
109106 protected ClientInvocation createRequest(Object[] args)
110107 {
111 WebTarget target = this.webTarget;
108 WebTarget target = this.webTarget;
112109 for (int i = 0; i < processors.length; i++)
113110 {
114111 if (processors != null && processors[i] instanceof WebTargetProcessor)
119116 }
120117 }
121118
122 ClientConfiguration parentConfiguration=(ClientConfiguration) target.getConfiguration();
123 ClientInvocation clientInvocation = new ClientInvocation(this.webTarget.getResteasyClient(), target.getUri(),
124 new ClientRequestHeaders(parentConfiguration), parentConfiguration);
119 ClientInvocationBuilderInterface builder = null;
125120 if (accepts != null)
126121 {
127 clientInvocation.getHeaders().accept(accepts);
122 builder = (ClientInvocationBuilderInterface)target.request(accepts);
128123 }
124 else
125 {
126 builder = (ClientInvocationBuilderInterface)target.request();
127 }
128
129129 for (int i = 0; i < processors.length; i++)
130130 {
131131 if (processors != null && processors[i] instanceof InvocationProcessor)
132132 {
133133 InvocationProcessor processor = (InvocationProcessor)processors[i];
134 processor.process(clientInvocation, args[i]);
134 processor.process(builder, args[i]);
135135
136136 }
137137 }
138 clientInvocation.setMethod(httpMethod);
139 return clientInvocation;
138 return (ClientInvocation)builder.build(httpMethod);
140139 }
141140
142141 public String getHttpMethod()
+0
-13
resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/ClientInvokerModifier.java less more
0 package org.jboss.resteasy.client.jaxrs.internal.proxy;
1
2 /**
3 * used to modify all of the ClientInvokers of a given ResteasyClientProxy. @see
4 * ResteasyClientProxy.applyClientInvokerModifier
5 *
6 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
7 * @version $Revision: 1 $
8 */
9 public interface ClientInvokerModifier
10 {
11 void modify(ClientInvoker invoker);
12 }
00 package org.jboss.resteasy.client.jaxrs.internal.proxy;
1
2 import org.jboss.resteasy.client.core.ClientInvoker;
3 import org.jboss.resteasy.client.core.ClientInvokerModifier;
14
25 import java.util.Collection;
36
33 import org.jboss.resteasy.client.jaxrs.ProxyConfig;
44 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
55
6 import javax.ws.rs.MatrixParam;
76 import javax.ws.rs.Path;
87 import javax.ws.rs.PathParam;
98 import javax.ws.rs.client.WebTarget;
1716 final Class<?> iface;
1817 final Method method;
1918 final ResteasyWebTarget parent;
20 Annotation[] jaxParams;
21 boolean hasJaxParams;
19 String[] pathParams;
20 boolean hasPathParams;
2221
2322 public SubResourceInvoker(ResteasyWebTarget parent, Method method, ProxyConfig config)
2423 {
2524 this.config = config;
2625 this.method = method;
2726 this.iface = method.getReturnType();
28 jaxParams = new Annotation[method.getParameterTypes().length];
29 for (int i = 0; i < jaxParams.length; i++)
27 pathParams = new String[method.getParameterTypes().length];
28 for (int i = 0; i < pathParams.length; i++)
3029 {
3130 Annotation[] paramAnnotations = method.getParameterAnnotations()[i];
3231 for (Annotation annotation : paramAnnotations)
3332 {
34 if (annotation instanceof PathParam || annotation instanceof MatrixParam)
33 if (annotation instanceof PathParam)
3534 {
36 jaxParams[i] = annotation;
37 hasJaxParams = true;
35 String name = ((PathParam) annotation).value();
36 pathParams[i] = name;
37 hasPathParams = true;
3838 break;
3939 }
4040 }
5151 public Object invoke(Object[] args)
5252 {
5353 WebTarget target = parent;
54 if (hasJaxParams)
54 if (hasPathParams)
5555 {
56 HashMap<String, Object> pathParams = new HashMap<String, Object>();
57 for (int i = 0; i < jaxParams.length; i++)
56 HashMap<String, Object> params = new HashMap<String, Object>();
57 for (int i = 0; i < pathParams.length; i++)
5858 {
59 if (jaxParams[i] instanceof PathParam)
59 if (pathParams[i] != null)
6060 {
61 pathParams.put(((PathParam) jaxParams[i]).value(), args[i]);
62 }
63 else if (jaxParams[i] instanceof MatrixParam)
64 {
65 target = target.matrixParam(((MatrixParam) jaxParams[i]).value(), args[i]);
61 params.put(pathParams[i], args[i]);
6662 }
6763 }
68 if (!pathParams.isEmpty())
69 {
70 target = target.resolveTemplates(pathParams);
71 }
64 target = parent.resolveTemplates(params);
7265 }
7366 return ProxyBuilder.proxy(iface, target, config);
7467 }
00 package org.jboss.resteasy.client.jaxrs.internal.proxy.processors;
11
22 import org.jboss.resteasy.client.jaxrs.internal.ClientConfiguration;
3 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
3 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilderInterface;
44 import org.jboss.resteasy.spi.LoggableFailure;
55
66 import javax.ws.rs.client.WebTarget;
208208 }
209209
210210 @Override
211 public void process(ClientInvocation invocation, Object param)
211 public void process(ClientInvocationBuilderInterface invocation, Object param)
212212 {
213213 process(new Process() {
214214 @Override
215215 public Object process(Object target, Object value, Object processor)
216216 {
217 processParam((ClientInvocation)target, value, processor);
217 processParam((ClientInvocationBuilderInterface)target, value, processor);
218218 return target;
219219 }
220220 }, invocation, param);
270270 return target;
271271 }
272272
273 private void processParam(ClientInvocation invocation, Object val, Object proc)
273 private void processParam(ClientInvocationBuilderInterface invocation, Object val, Object proc)
274274 {
275275 if (proc instanceof InvocationProcessor)
276276 {
00 package org.jboss.resteasy.client.jaxrs.internal.proxy.processors;
11
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilderInterface;
33
44 /**
55 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
77 */
88 public interface InvocationProcessor
99 {
10 void process(ClientInvocation invocation, Object param);
10 void process(ClientInvocationBuilderInterface invocation, Object param);
1111 }
2121 import javax.ws.rs.core.MediaType;
2222
2323 import org.jboss.resteasy.annotations.Form;
24 import org.jboss.resteasy.annotations.ClientURI;
24 import org.jboss.resteasy.client.ClientURI;
2525 import org.jboss.resteasy.client.jaxrs.i18n.Messages;
2626 import org.jboss.resteasy.client.jaxrs.internal.ClientConfiguration;
2727 import org.jboss.resteasy.client.jaxrs.internal.proxy.processors.invocation.CookieParamProcessor;
135135 processor = new CookieParamProcessor(null);
136136 }
137137 // this is for HATEAOS clients
138 //look for old (resteasy-legacy) annotation too for runtime backward compatibility
139 else if (FindAnnotation.findAnnotation(annotations, ClientURI.class.getName(), "org.jboss.resteasy.client.ClientURI") != null)
138 else if (FindAnnotation.findAnnotation(annotations, ClientURI.class) != null)
140139 {
141140 processor = new URIParamProcessor();
142141 }
00 package org.jboss.resteasy.client.jaxrs.internal.proxy.processors.invocation;
11
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilderInterface;
33 import org.jboss.resteasy.client.jaxrs.internal.proxy.processors.AbstractCollectionProcessor;
44 import org.jboss.resteasy.client.jaxrs.internal.proxy.processors.InvocationProcessor;
55
77 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
88 * @version $Revision: 1 $
99 */
10 public abstract class AbstractInvocationCollectionProcessor extends AbstractCollectionProcessor<ClientInvocation> implements InvocationProcessor
10 public abstract class AbstractInvocationCollectionProcessor extends AbstractCollectionProcessor<ClientInvocationBuilderInterface> implements InvocationProcessor
1111 {
1212 public AbstractInvocationCollectionProcessor(String paramName)
1313 {
1515 }
1616
1717 @Override
18 public void process(ClientInvocation invocation, Object param)
18 public void process(ClientInvocationBuilderInterface invocation, Object param)
1919 {
2020 buildIt(invocation, param);
2121 }
00 package org.jboss.resteasy.client.jaxrs.internal.proxy.processors.invocation;
11
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilderInterface;
33 import org.jboss.resteasy.client.jaxrs.internal.proxy.processors.InvocationProcessor;
44
55 import javax.ws.rs.core.Cookie;
2323 }
2424
2525 @Override
26 public void process(ClientInvocation invocation, Object object)
26 public void process(ClientInvocationBuilderInterface request, Object object)
2727 {
2828 if (object == null) return; // don't set a null value
2929 if (object instanceof Cookie)
3030 {
3131 Cookie cookie = (Cookie) object;
32 invocation.getHeaders().cookie(cookie);
32 request.cookie(cookie);
3333 }
3434 else
3535 {
36 invocation.getHeaders().cookie(new Cookie(cookieName, invocation.getClientConfiguration().toString(object)));
36 request.cookie(new Cookie(cookieName, request.getInvocation().getClientConfiguration().toString(object)));
3737 }
3838 }
3939 }
00 package org.jboss.resteasy.client.jaxrs.internal.proxy.processors.invocation;
11
22 import org.jboss.resteasy.client.jaxrs.i18n.Messages;
3 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
3 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilderInterface;
44
55 import javax.ws.rs.client.Entity;
66 import javax.ws.rs.core.Form;
1818 }
1919
2020 @Override
21 protected ClientInvocation apply(ClientInvocation invocation, Object object)
21 protected ClientInvocationBuilderInterface apply(ClientInvocationBuilderInterface target, Object object)
2222 {
2323 Form form = null;
24 Object entity = invocation.getEntity();
24 Object entity = target.getInvocation().getEntity();
2525 if (entity != null)
2626 {
2727 if (entity instanceof Form)
3636 else
3737 {
3838 form = new Form();
39 invocation.setEntity(Entity.form(form));
39 target.getInvocation().setEntity(Entity.form(form));
4040 }
41 String value = invocation.getClientConfiguration().toString(object);
41 String value = target.getInvocation().getClientConfiguration().toString(object);
4242 form.param(paramName, value);
43 return invocation;
43 return target;
4444 }
4545
4646 }
00 package org.jboss.resteasy.client.jaxrs.internal.proxy.processors.invocation;
11
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilderInterface;
33
44 /**
55 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
1414 }
1515
1616 @Override
17 protected ClientInvocation apply(ClientInvocation invocation, Object object)
17 protected ClientInvocationBuilderInterface apply(ClientInvocationBuilderInterface target, Object object)
1818 {
19 invocation.getHeaders().header(paramName, object);
20 return invocation;
19 return (ClientInvocationBuilderInterface)target.header(paramName, object);
2120 }
2221
2322 }
00 package org.jboss.resteasy.client.jaxrs.internal.proxy.processors.invocation;
11
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilderInterface;
34 import org.jboss.resteasy.client.jaxrs.internal.proxy.processors.InvocationProcessor;
45
56 import javax.ws.rs.client.Entity;
1415 */
1516 public class MessageBodyParameterProcessor implements InvocationProcessor
1617 {
17 private Class<?> type;
18 private Class type;
1819 private MediaType mediaType;
1920 private Type genericType;
2021 private Annotation[] annotations;
2122
22 public MessageBodyParameterProcessor(MediaType mediaType, Class<?> type, Type genericType, Annotation[] annotations)
23 public MessageBodyParameterProcessor(MediaType mediaType, Class type, Type genericType, Annotation[] annotations)
2324 {
2425 this.type = type;
2526 this.mediaType = mediaType;
2930
3031 @SuppressWarnings("unchecked")
3132 @Override
32 public void process(ClientInvocation invocation, Object param)
33 public void process(ClientInvocationBuilderInterface invocation, Object param)
3334 {
34 invocation.setEntity(Entity.entity(param == null? null : new GenericEntity<Object>(param, genericType), mediaType, annotations));
35 invocation.getInvocation().setEntity(Entity.entity(param == null? null : new GenericEntity<Object>(param, genericType), mediaType, annotations));
3536 }
3637
37 public Class<?> getType()
38 public void build(ClientRequest request, Object object)
39 {
40 request.body(mediaType, object, type, genericType, annotations);
41 }
42
43 public Class getType()
3844 {
3945 return type;
4046 }
4450 return mediaType;
4551 }
4652
47 }
53 }
00 package org.jboss.resteasy.client.jaxrs.internal.proxy.processors.invocation;
11
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
2 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilderInterface;
33 import org.jboss.resteasy.client.jaxrs.internal.proxy.processors.InvocationProcessor;
44
55 import java.net.URI;
1616 {
1717
1818 @Override
19 public void process(ClientInvocation invocation, Object param)
19 public void process(ClientInvocationBuilderInterface invocation, Object param)
2020 {
2121 URI uri = getUri(param);
2222
2323 if (uri != null)
2424 {
25 invocation.setUri(uri);
25 invocation.getInvocation().setUri(uri);
2626 }
2727 }
2828
0 package org.jboss.resteasy.client.microprofile;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MultivaluedMap;
4 import javax.ws.rs.core.Response;
5
6 import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper;
7
8 /**
9 * Created by hbraun on 17.01.18.
10 */
11 public class DefaultResponseExceptionMapper implements ResponseExceptionMapper {
12
13
14 @Override
15 public Throwable toThrowable(Response response) {
16 return new WebApplicationException("Unkown error, status code " + response.getStatus(), response);
17 }
18
19 @Override
20 public boolean handles(int status, MultivaluedMap headers) {
21 return status>=400;
22 }
23
24 @Override
25 public int getPriority() {
26 return Integer.MAX_VALUE;
27 }
28 }
0 package org.jboss.resteasy.client.microprofile;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Method;
4 import java.lang.reflect.Parameter;
5 import java.net.URI;
6 import java.net.URISyntaxException;
7 import java.net.URL;
8 import java.util.HashMap;
9 import java.util.HashSet;
10 import java.util.Map;
11 import java.util.Set;
12
13 import javax.ws.rs.HttpMethod;
14 import javax.ws.rs.Path;
15 import javax.ws.rs.PathParam;
16 import javax.ws.rs.core.Configuration;
17 import javax.ws.rs.core.MediaType;
18 import javax.ws.rs.core.UriBuilder;
19
20 import org.eclipse.microprofile.rest.client.RestClientBuilder;
21 import org.eclipse.microprofile.rest.client.RestClientDefinitionException;
22 import org.eclipse.microprofile.rest.client.annotation.RegisterProvider;
23 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
24 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
25 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
26
27 /**
28 * Created by hbraun on 15.01.18.
29 */
30 class MicroprofileClientBuilder implements RestClientBuilder {
31
32 public MicroprofileClientBuilder() {
33 this.builderDelegate = new ResteasyClientBuilder();
34 }
35
36 private final static String DEFAULT_MAPPER_PROP = "microprofile.rest.client.disable.default.mapper";
37
38 @Override
39 public RestClientBuilder baseUrl(URL url) {
40 try {
41 this.baseURI = url.toURI();
42 return this;
43 } catch (URISyntaxException e) {
44 throw new RuntimeException(e.getMessage());
45 }
46 }
47
48 @Override
49 public <T> T build(Class<T> aClass) throws IllegalStateException, RestClientDefinitionException {
50
51 // Interface validity
52 verifyInterface(aClass);
53
54 // Provider annotations
55 RegisterProvider[] providers = aClass.getAnnotationsByType(RegisterProvider.class);
56
57 for (RegisterProvider provider : providers) {
58 this.builderDelegate.register(provider.value(), provider.priority());
59 }
60
61 // Default exception mapper
62 boolean defaultMapperDisabled = false;
63 Object defaultMapperProp = this.builderDelegate.getConfiguration().getProperty(DEFAULT_MAPPER_PROP);
64 if(defaultMapperProp!=null && defaultMapperProp.equals(Boolean.TRUE)) {
65 defaultMapperDisabled = true;
66 }
67
68 if(!defaultMapperDisabled) {
69 this.builderDelegate.register(DefaultResponseExceptionMapper.class);
70 }
71
72 ResteasyClient client = this.builderDelegate.build();
73 return client
74 .target(this.baseURI)
75 .proxyBuilder(aClass)
76 .defaultConsumes(MediaType.TEXT_PLAIN)
77 .defaultProduces(MediaType.TEXT_PLAIN)
78 .build();
79 }
80
81 private <T> void verifyInterface(Class<T> typeDef) {
82
83 Method[] methods = typeDef.getMethods();
84
85 // multiple verbs
86 for (Method method : methods) {
87 boolean hasHttpMethod = false;
88 for (Annotation annotation : method.getAnnotations()) {
89 boolean isHttpMethod = (annotation.annotationType().getAnnotation(HttpMethod.class) != null);
90 if(!hasHttpMethod && isHttpMethod) {
91 hasHttpMethod = true;
92 } else if(hasHttpMethod && isHttpMethod) {
93 throw new RestClientDefinitionException("Ambiguous @Httpmethod defintion on type " + typeDef);
94 }
95 }
96 }
97
98 // invalid parameter
99 Path classPathAnno = typeDef.getAnnotation(Path.class);
100
101 final Set<String> classLevelVariables = new HashSet<>();
102 ResteasyUriBuilder classTemplate = null;
103 if (classPathAnno != null) {
104 classTemplate = (ResteasyUriBuilder)UriBuilder.fromUri(classPathAnno.value());
105 classLevelVariables.addAll(classTemplate.getPathParamNamesInDeclarationOrder());
106 }
107 ResteasyUriBuilder template;
108 for (Method method : methods) {
109
110 Path methodPathAnno = method.getAnnotation(Path.class);
111 if (methodPathAnno != null) {
112 template = classPathAnno == null ? (ResteasyUriBuilder)UriBuilder.fromUri(methodPathAnno.value())
113 : (ResteasyUriBuilder)UriBuilder.fromUri(classPathAnno.value() + "/" + methodPathAnno.value());
114 } else {
115 template = classTemplate;
116 }
117 if (template == null) {
118 continue;
119 }
120
121 // it's not executed, so this can be anything - but a hostname needs to present
122 template.host("localhost");
123
124 Set<String> allVariables = new HashSet<>(template.getPathParamNamesInDeclarationOrder());
125 Map<String, Object> paramMap = new HashMap<>();
126 for (Parameter p : method.getParameters()) {
127 PathParam pathParam = p.getAnnotation(PathParam.class);
128 if (pathParam != null) {
129 paramMap.put(pathParam.value(), "foobar");
130 }
131 }
132
133 if(allVariables.size()!=paramMap.size()) {
134 throw new RestClientDefinitionException("Parameters and variables don't match on "+ typeDef +"::"+method.getName());
135 }
136
137 try {
138 template.resolveTemplates(paramMap, false).build();
139 } catch (IllegalArgumentException ex) {
140 throw new RestClientDefinitionException("Parameter names don't match variable names on "+ typeDef +"::"+method.getName(), ex);
141 }
142
143 }
144 }
145
146
147 @Override
148 public Configuration getConfiguration() {
149 return this.builderDelegate.getConfiguration();
150 }
151
152 @Override
153 public RestClientBuilder property(String name, Object value) {
154 this.builderDelegate.property(name, value);
155 return this;
156 }
157
158 @Override
159 public RestClientBuilder register(Class<?> aClass) {
160 this.builderDelegate.register(aClass);
161 return this;
162 }
163
164 @Override
165 public RestClientBuilder register(Class<?> aClass, int i) {
166 this.builderDelegate.register(aClass, i);
167 return this;
168 }
169
170 @Override
171 public RestClientBuilder register(Class<?> aClass, Class<?>[] classes) {
172 this.builderDelegate.register(aClass, classes);
173 return this;
174 }
175
176 @Override
177 public RestClientBuilder register(Class<?> aClass, Map<Class<?>, Integer> map) {
178 this.builderDelegate.register(aClass, map);
179 return this;
180 }
181
182 @Override
183 public RestClientBuilder register(Object o) {
184 this.builderDelegate.register(o);
185 return this;
186 }
187
188 @Override
189 public RestClientBuilder register(Object o, int i) {
190 this.builderDelegate.register(o, i);
191 return this;
192 }
193
194 @Override
195 public RestClientBuilder register(Object o, Class<?>[] classes) {
196 this.builderDelegate.register(o, classes);
197 return this;
198 }
199
200 @Override
201 public RestClientBuilder register(Object o, Map<Class<?>, Integer> map) {
202 this.builderDelegate.register(o, map);
203 return this;
204 }
205
206 private final ResteasyClientBuilder builderDelegate;
207
208 private URI baseURI;
209
210 }
0 package org.jboss.resteasy.client.microprofile;
1
2 import org.eclipse.microprofile.rest.client.RestClientBuilder;
3 import org.eclipse.microprofile.rest.client.spi.RestClientBuilderResolver;
4
5 /**
6 * Created by hbraun on 15.01.18.
7 */
8 public class MicroprofileClientBuilderResolver extends RestClientBuilderResolver {
9 @Override
10 public RestClientBuilder newBuilder() {
11 return new MicroprofileClientBuilder();
12 }
13 }
14
+0
-117
resteasy-client/src/main/java/org/jboss/resteasy/test/TestPortProvider.java less more
0 package org.jboss.resteasy.test;
1
2 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
3 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
4 import org.jboss.resteasy.util.PortProvider;
5
6 import java.net.MalformedURLException;
7 import java.net.URI;
8 import java.net.URL;
9
10 import javax.ws.rs.client.ClientBuilder;
11
12 /**
13 * Test utility class
14 *
15 * @author <a href="justin@justinedelson.com">Justin Edelson</a>
16 * @version $Revision$
17 */
18 public class TestPortProvider
19 {
20 /**
21 * Creates a ResteasyWebTarget using base request path.
22 */
23 public static ResteasyWebTarget createTarget(String path)
24 {
25 return (ResteasyWebTarget) ClientBuilder.newClient().target(generateURL(path));
26 }
27
28 /**
29 * Create a Resteasy client proxy with an empty base request path.
30 *
31 * @param clazz the client interface class
32 * @return the proxy object
33 */
34 public static <T> T createProxy(Class<T> clazz)
35 {
36 return createProxy(clazz, generateBaseUrl());
37 }
38
39 /**
40 * Create a Resteasy client proxy.
41 *
42 * @param clazz the client interface class
43 * @return the proxy object
44 * @path the base request path
45 */
46 public static <T> T createProxy(Class<T> clazz, String url)
47 {
48 ResteasyWebTarget target = (ResteasyWebTarget) ResteasyClientBuilder.newClient().target(url);
49 return target.proxy(clazz);
50 }
51
52 /**
53 * Create a URI for the provided path, using the configured port
54 *
55 * @param path the request path
56 * @return a full URI
57 */
58 public static URI createURI(String path)
59 {
60 return URI.create(generateURL(path));
61 }
62
63 /**
64 * Create a URL for the provided path, using the configured port
65 *
66 * @param path the request path
67 * @return a full URL
68 */
69 public static URL createURL(String path) throws MalformedURLException
70 {
71 return new URL(generateURL(path));
72 }
73
74 /**
75 * Generate a base URL incorporating the configured port.
76 *
77 * @return a full URL
78 */
79 public static String generateBaseUrl()
80 {
81 return generateURL("");
82 }
83
84 /**
85 * Generate a URL incorporating the configured port.
86 *
87 * @param path the path
88 * @return a full URL
89 */
90 public static String generateURL(String path)
91 {
92 return String.format("http://%s:%d%s", getHost(), getPort(), path);
93 }
94
95 /**
96 * Look up the configured port number, first checking an environment variable (RESTEASY_PORT),
97 * then a system property (org.jboss.resteasy.port), and finally the default port (8081).
98 *
99 * @return the port number specified in either the environment or system properties
100 */
101 public static int getPort()
102 {
103 return PortProvider.getPort();
104 }
105
106 /**
107 * Look up the configured hostname, first checking an environment variable (RESTEASY_HOST),
108 * then a system property (org.jboss.resteasy.host), and finally the default hostname (localhost).
109 *
110 * @return the host specified in either the environment or system properties
111 */
112 public static String getHost()
113 {
114 return PortProvider.getHost();
115 }
116 }
0 package org.jboss.resteasy.client.jaxrs.internal;
1
2 import org.jboss.resteasy.core.ThreadLocalResteasyProviderFactory;
3 import org.jboss.resteasy.spi.HeaderValueProcessor;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
6
7 import javax.ws.rs.RuntimeType;
8 import javax.ws.rs.client.ClientRequestFilter;
9 import javax.ws.rs.client.ClientResponseFilter;
10 import javax.ws.rs.container.DynamicFeature;
11 import javax.ws.rs.core.Configurable;
12 import javax.ws.rs.core.Configuration;
13 import javax.ws.rs.core.Feature;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.ext.ContextResolver;
16 import javax.ws.rs.ext.ExceptionMapper;
17 import javax.ws.rs.ext.MessageBodyReader;
18 import javax.ws.rs.ext.MessageBodyWriter;
19 import javax.ws.rs.ext.Providers;
20 import javax.ws.rs.ext.ReaderInterceptor;
21 import javax.ws.rs.ext.WriterInterceptor;
22 import java.lang.annotation.Annotation;
23 import java.lang.reflect.AccessibleObject;
24 import java.lang.reflect.Type;
25 import java.util.Collection;
26 import java.util.Map;
27 import java.util.Set;
28
29 /**
30 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
31 * @version $Revision: 1 $
32 */
33 public class ClientConfiguration implements Configuration, Configurable<ClientConfiguration>, Providers, HeaderValueProcessor
34 {
35 protected ResteasyProviderFactory providerFactory;
36
37 public ClientConfiguration(ResteasyProviderFactory factory)
38 {
39 if (factory instanceof ThreadLocalResteasyProviderFactory)
40 {
41 factory = ((ThreadLocalResteasyProviderFactory)factory).getDelegate();
42 }
43 this.providerFactory = new LocalResteasyProviderFactory(factory);
44 }
45
46 public ClientConfiguration(ClientConfiguration parent)
47 {
48 this(parent.getProviderFactory());
49 setProperties(parent.getProperties());
50 }
51
52 public void setProperties(Map<String, Object> newProps)
53 {
54 providerFactory.setProperties(newProps);
55 }
56
57 protected ResteasyProviderFactory getProviderFactory()
58 {
59 return providerFactory;
60 }
61
62 public Map<String, Object> getMutableProperties()
63 {
64 return providerFactory.getMutableProperties();
65 }
66
67 /**
68 * Convert an object to a header string. First try StringConverter, then HeaderDelegate, then object.toString()
69 *
70 * @param object
71 * @return
72 */
73 public String toHeaderString(Object object)
74 {
75 if (object instanceof String) return (String)object;
76 return providerFactory.toHeaderString(object);
77 }
78
79 public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
80 {
81 MessageBodyWriter<T> writer = providerFactory.getClientMessageBodyWriter(type, genericType, annotations, mediaType);
82 if (writer!=null)
83 LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName());
84 return writer;
85 }
86
87 public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
88 {
89 MessageBodyReader<T> reader = providerFactory.getClientMessageBodyReader(type, genericType, annotations, mediaType);
90 if (reader!=null)
91 LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName());
92 return reader;
93 }
94
95 public WriterInterceptor[] getWriterInterceptors(Class declaring, AccessibleObject target)
96 {
97 return providerFactory.getClientWriterInterceptorRegistry().postMatch(declaring, target);
98 }
99
100 public ReaderInterceptor[] getReaderInterceptors(Class declaring, AccessibleObject target)
101 {
102 return providerFactory.getClientReaderInterceptorRegistry().postMatch(declaring, target);
103 }
104
105 public ClientRequestFilter[] getRequestFilters(Class declaring, AccessibleObject target)
106 {
107 return providerFactory.getClientRequestFilterRegistry().postMatch(declaring, target);
108 }
109
110 public ClientResponseFilter[] getResponseFilters(Class declaring, AccessibleObject target)
111 {
112 return providerFactory.getClientResponseFilters().postMatch(declaring, target);
113 }
114
115 public Set<DynamicFeature> getDynamicFeatures()
116 {
117 return providerFactory.getClientDynamicFeatures();
118 }
119
120 public String toString(Object object)
121 {
122 return providerFactory.toString(object, object.getClass(), null, null);
123 }
124
125
126
127
128 // interface implementation
129
130 // Providers
131
132 @Override
133 public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type)
134 {
135 return providerFactory.getExceptionMapper(type);
136 }
137
138 @Override
139 public <T> ContextResolver<T> getContextResolver(Class<T> contextType, MediaType mediaType)
140 {
141 return providerFactory.getContextResolver(contextType, mediaType);
142 }
143
144 // Configuration
145
146 @Override
147 public Map<String, Object> getProperties()
148 {
149 return providerFactory.getProperties();
150 }
151
152 @Override
153 public Object getProperty(String name)
154 {
155 return providerFactory.getProperty(name);
156 }
157
158 @Override
159 public Set<Class<?>> getClasses()
160 {
161 return providerFactory.getProviderClasses();
162 }
163
164 @Override
165 public Set<Object> getInstances()
166 {
167 return providerFactory.getProviderInstances();
168 }
169
170 @Override
171 public ClientConfiguration register(Class<?> providerClass)
172 {
173 providerFactory.register(providerClass);
174 return this;
175 }
176
177 @Override
178 public ClientConfiguration register(Object provider)
179 {
180 providerFactory.register(provider);
181 return this;
182 }
183
184 @Override
185 public ClientConfiguration register(Class<?> providerClass, int priority)
186 {
187 providerFactory.register(providerClass, priority);
188 return this;
189 }
190
191 @Override
192 public ClientConfiguration register(Object provider, int Priority)
193 {
194 providerFactory.register(provider, Priority);
195 return this;
196 }
197
198 @Override
199 public ClientConfiguration property(String name, Object value)
200 {
201 providerFactory.property(name, value);
202 return this;
203 }
204
205 @Override
206 public Configuration getConfiguration()
207 {
208 return this;
209 }
210
211 @Override
212 public ClientConfiguration register(Class<?> componentClass, Class<?>... contracts)
213 {
214 providerFactory.register(componentClass, contracts);
215 return this;
216 }
217
218 @Override
219 public ClientConfiguration register(Class<?> componentClass, Map<Class<?>, Integer> contracts)
220 {
221 providerFactory.register(componentClass, contracts);
222 return this;
223 }
224
225 @Override
226 public ClientConfiguration register(Object component, Class<?>... contracts)
227 {
228 providerFactory.register(component, contracts);
229 return this;
230 }
231
232 @Override
233 public ClientConfiguration register(Object component, Map<Class<?>, Integer> contracts)
234 {
235 providerFactory.register(component, contracts);
236 return this;
237 }
238
239 @Override
240 public RuntimeType getRuntimeType()
241 {
242 return RuntimeType.CLIENT;
243 }
244
245 @Override
246 public Collection<String> getPropertyNames()
247 {
248 return providerFactory.getProperties().keySet();
249 }
250
251 @Override
252 public boolean isEnabled(Feature feature)
253 {
254 return providerFactory.isEnabled(feature);
255 }
256
257 @Override
258 public boolean isEnabled(Class<? extends Feature> featureClass)
259 {
260 return providerFactory.isEnabled(featureClass);
261 }
262
263 @Override
264 public boolean isRegistered(Object component)
265 {
266 return providerFactory.isRegistered(component);
267 }
268
269 @Override
270 public boolean isRegistered(Class<?> componentClass)
271 {
272 return providerFactory.isRegistered(componentClass);
273 }
274
275 @Override
276 public Map<Class<?>, Integer> getContracts(Class<?> componentClass)
277 {
278 return providerFactory.getContracts(componentClass);
279 }
280 }
0 package org.jboss.resteasy.client.jaxrs.internal;
1
2 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
3 import org.jboss.resteasy.client.jaxrs.i18n.Messages;
4
5 import javax.ws.rs.HttpMethod;
6 import javax.ws.rs.client.AsyncInvoker;
7 import javax.ws.rs.client.Entity;
8 import javax.ws.rs.client.Invocation;
9 import javax.ws.rs.core.CacheControl;
10 import javax.ws.rs.core.Cookie;
11 import javax.ws.rs.core.GenericType;
12 import javax.ws.rs.core.MediaType;
13 import javax.ws.rs.core.MultivaluedMap;
14 import javax.ws.rs.core.Response;
15
16 import java.net.URI;
17 import java.util.Locale;
18
19 /**
20 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
21 * @author <a href="mailto:alessio.soldano@jboss.com">Alessio Soldano</a>
22 * @version $Revision: 1 $
23 */
24 public class ClientInvocationBuilder implements ClientInvocationBuilderInterface
25 {
26 protected ClientInvocation invocation;
27
28 public ClientInvocationBuilder(ResteasyClient client, URI uri, ClientConfiguration configuration)
29 {
30 invocation = new ClientInvocation(client, uri, new ClientRequestHeaders(configuration), configuration);
31 }
32
33 public ClientInvocation getInvocation()
34 {
35 return invocation;
36 }
37
38 public ClientRequestHeaders getHeaders()
39 {
40 return invocation.headers;
41 }
42
43 @Override
44 public Invocation.Builder accept(String... mediaTypes)
45 {
46 getHeaders().accept(mediaTypes);
47 return this;
48 }
49
50 @Override
51 public Invocation.Builder accept(MediaType... mediaTypes)
52 {
53 getHeaders().accept(mediaTypes);
54 return this;
55 }
56
57 @Override
58 public Invocation.Builder acceptLanguage(Locale... locales)
59 {
60 getHeaders().acceptLanguage(locales);
61 return this;
62 }
63
64 @Override
65 public Invocation.Builder acceptLanguage(String... locales)
66 {
67 getHeaders().acceptLanguage(locales);
68 return this;
69 }
70
71 @Override
72 public Invocation.Builder acceptEncoding(String... encodings)
73 {
74 getHeaders().acceptEncoding(encodings);
75 return this;
76 }
77
78 @Override
79 public Invocation.Builder cookie(Cookie cookie)
80 {
81 if (!(Cookie.class.equals(cookie.getClass())))
82 {
83 cookie = new Cookie(cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getVersion());
84 }
85 getHeaders().cookie(cookie);
86 return this;
87 }
88
89 @Override
90 public Invocation.Builder cookie(String name, String value)
91 {
92 getHeaders().cookie(new Cookie(name, value));
93 return this;
94 }
95
96 @Override
97 public Invocation.Builder cacheControl(CacheControl cacheControl)
98 {
99 getHeaders().cacheControl(cacheControl);
100 return this;
101 }
102
103 @Override
104 public Invocation.Builder header(String name, Object value)
105 {
106 getHeaders().header(name, value);
107 return this;
108 }
109
110 @Override
111 public Invocation.Builder headers(MultivaluedMap<String, Object> headers)
112 {
113 getHeaders().setHeaders(headers);
114 return this;
115 }
116
117 @Override
118 public Invocation build(String method)
119 {
120 invocation.setMethod(method);
121 return invocation;
122 }
123
124 @Override
125 public Invocation build(String method, Entity<?> entity)
126 {
127 invocation.setMethod(method);
128 invocation.setEntity(entity);
129 return invocation;
130 }
131
132 @Override
133 public Invocation buildGet()
134 {
135 return build(HttpMethod.GET);
136 }
137
138 @Override
139 public Invocation buildDelete()
140 {
141 return build(HttpMethod.DELETE);
142 }
143
144 @Override
145 public Invocation buildPost(Entity<?> entity)
146 {
147 return build(HttpMethod.POST, entity);
148 }
149
150 @Override
151 public Invocation buildPut(Entity<?> entity)
152 {
153 return build(HttpMethod.PUT, entity);
154 }
155
156 @Override
157 public AsyncInvoker async()
158 {
159 return new AsynchronousInvoke(invocation);
160 }
161
162 @Override
163 public Response get()
164 {
165 return buildGet().invoke();
166 }
167
168 @Override
169 public <T> T get(Class<T> responseType)
170 {
171 return buildGet().invoke(responseType);
172 }
173
174 @Override
175 public <T> T get(GenericType<T> responseType)
176 {
177 return buildGet().invoke(responseType);
178 }
179
180 @Override
181 public Response put(Entity<?> entity)
182 {
183 return buildPut(entity).invoke();
184 }
185
186 @Override
187 public <T> T put(Entity<?> entity, Class<T> responseType)
188 {
189 return buildPut(entity).invoke(responseType);
190 }
191
192 @Override
193 public <T> T put(Entity<?> entity, GenericType<T> responseType)
194 {
195 return buildPut(entity).invoke(responseType);
196 }
197
198 @Override
199 public Response post(Entity<?> entity)
200 {
201 return buildPost(entity).invoke();
202 }
203
204 @Override
205 public <T> T post(Entity<?> entity, Class<T> responseType)
206 {
207 return buildPost(entity).invoke(responseType);
208 }
209
210 @Override
211 public <T> T post(Entity<?> entity, GenericType<T> responseType)
212 {
213 return buildPost(entity).invoke(responseType);
214 }
215
216 @Override
217 public Response delete()
218 {
219 return buildDelete().invoke();
220 }
221
222 @Override
223 public <T> T delete(Class<T> responseType)
224 {
225 return buildDelete().invoke(responseType);
226 }
227
228 @Override
229 public <T> T delete(GenericType<T> responseType)
230 {
231 return buildDelete().invoke(responseType);
232 }
233
234 @Override
235 public Response head()
236 {
237 return build(HttpMethod.HEAD).invoke();
238 }
239
240 @Override
241 public Response options()
242 {
243 return build(HttpMethod.OPTIONS).invoke();
244 }
245
246 @Override
247 public <T> T options(Class<T> responseType)
248 {
249 return build(HttpMethod.OPTIONS).invoke(responseType);
250 }
251
252 @Override
253 public <T> T options(GenericType<T> responseType)
254 {
255 return build(HttpMethod.OPTIONS).invoke(responseType);
256 }
257
258 @Override
259 public Response trace()
260 {
261 return build("TRACE").invoke();
262 }
263
264 @Override
265 public <T> T trace(Class<T> responseType)
266 {
267 return build("TRACE").invoke(responseType);
268 }
269
270 @Override
271 public <T> T trace(GenericType<T> responseType)
272 {
273 return build("TRACE").invoke(responseType);
274 }
275
276 @Override
277 public Response method(String name)
278 {
279 return build(name).invoke();
280 }
281
282 @Override
283 public <T> T method(String name, Class<T> responseType)
284 {
285 return build(name).invoke(responseType);
286 }
287
288 @Override
289 public <T> T method(String name, GenericType<T> responseType)
290 {
291 return build(name).invoke(responseType);
292 }
293
294 @Override
295 public Response method(String name, Entity<?> entity)
296 {
297 return build(name, entity).invoke();
298 }
299
300 @Override
301 public <T> T method(String name, Entity<?> entity, Class<T> responseType)
302 {
303 return build(name, entity).invoke(responseType);
304 }
305
306 @Override
307 public <T> T method(String name, Entity<?> entity, GenericType<T> responseType)
308 {
309 return build(name, entity).invoke(responseType);
310 }
311
312 @Override
313 public Invocation.Builder property(String name, Object value)
314 {
315 invocation.property(name, value);
316 return this;
317 }
318
319 public boolean isChunked()
320 {
321 return invocation.isChunked();
322 }
323
324 public void setChunked(boolean chunked)
325 {
326 invocation.setChunked(chunked);
327 }
328
329 public Response patch(Entity<?> entity)
330 {
331 return build("PATCH", entity).invoke();
332 }
333
334 public <T> T patch(Entity<?> entity, Class<T> responseType)
335 {
336 return build("PATCH", entity).invoke(responseType);
337 }
338
339 public <T> T patch(Entity<?> entity, GenericType<T> responseType)
340 {
341 return build("PATCH", entity).invoke(responseType);
342 }
343
344 }
0 package org.jboss.resteasy.client.jaxrs.internal;
1
2 import org.jboss.resteasy.core.ThreadLocalResteasyProviderFactory;
3 import org.jboss.resteasy.spi.HeaderValueProcessor;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
6
7 import javax.ws.rs.RuntimeType;
8 import javax.ws.rs.client.ClientRequestFilter;
9 import javax.ws.rs.client.ClientResponseFilter;
10 import javax.ws.rs.client.RxInvoker;
11 import javax.ws.rs.client.RxInvokerProvider;
12 import javax.ws.rs.container.DynamicFeature;
13 import javax.ws.rs.core.Configurable;
14 import javax.ws.rs.core.Configuration;
15 import javax.ws.rs.core.Feature;
16 import javax.ws.rs.core.MediaType;
17 import javax.ws.rs.ext.ContextResolver;
18 import javax.ws.rs.ext.ExceptionMapper;
19 import javax.ws.rs.ext.MessageBodyReader;
20 import javax.ws.rs.ext.MessageBodyWriter;
21 import javax.ws.rs.ext.Providers;
22 import javax.ws.rs.ext.ReaderInterceptor;
23 import javax.ws.rs.ext.WriterInterceptor;
24 import java.lang.annotation.Annotation;
25 import java.lang.reflect.AccessibleObject;
26 import java.lang.reflect.Type;
27 import java.util.Collection;
28 import java.util.Map;
29 import java.util.Set;
30 import java.util.Map.Entry;
31
32 /**
33 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
34 * @version $Revision: 1 $
35 */
36 public class ClientConfiguration implements Configuration, Configurable<ClientConfiguration>, Providers, HeaderValueProcessor
37 {
38 protected ResteasyProviderFactory providerFactory;
39
40 public ClientConfiguration(ResteasyProviderFactory factory)
41 {
42 if (factory instanceof ThreadLocalResteasyProviderFactory)
43 {
44 factory = ((ThreadLocalResteasyProviderFactory)factory).getDelegate();
45 }
46 this.providerFactory = new LocalResteasyProviderFactory(factory);
47 }
48
49 public ClientConfiguration(ClientConfiguration parent)
50 {
51 this(parent.getProviderFactory());
52 setProperties(parent.getProperties());
53 }
54
55 public void setProperties(Map<String, Object> newProps)
56 {
57 providerFactory.setProperties(newProps);
58 }
59
60 protected ResteasyProviderFactory getProviderFactory()
61 {
62 return providerFactory;
63 }
64
65 public Map<String, Object> getMutableProperties()
66 {
67 return providerFactory.getMutableProperties();
68 }
69
70 /**
71 * Convert an object to a header string. First try StringConverter, then HeaderDelegate, then object.toString()
72 *
73 * @param object
74 * @return
75 */
76 public String toHeaderString(Object object)
77 {
78 if (object instanceof String) return (String)object;
79 return providerFactory.toHeaderString(object);
80 }
81
82 public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
83 {
84 MessageBodyWriter<T> writer = providerFactory.getClientMessageBodyWriter(type, genericType, annotations, mediaType);
85 if (writer!=null)
86 LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName());
87 return writer;
88 }
89
90 public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
91 {
92 MessageBodyReader<T> reader = providerFactory.getClientMessageBodyReader(type, genericType, annotations, mediaType);
93 if (reader!=null)
94 LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName());
95 return reader;
96 }
97
98 public WriterInterceptor[] getWriterInterceptors(Class declaring, AccessibleObject target)
99 {
100 return providerFactory.getClientWriterInterceptorRegistry().postMatch(declaring, target);
101 }
102
103 public ReaderInterceptor[] getReaderInterceptors(Class declaring, AccessibleObject target)
104 {
105 return providerFactory.getClientReaderInterceptorRegistry().postMatch(declaring, target);
106 }
107
108 public ClientRequestFilter[] getRequestFilters(Class declaring, AccessibleObject target)
109 {
110 return providerFactory.getClientRequestFilterRegistry().postMatch(declaring, target);
111 }
112
113 public ClientResponseFilter[] getResponseFilters(Class declaring, AccessibleObject target)
114 {
115 return providerFactory.getClientResponseFilters().postMatch(declaring, target);
116 }
117
118 public Set<DynamicFeature> getDynamicFeatures()
119 {
120 return providerFactory.getClientDynamicFeatures();
121 }
122
123 public String toString(Object object)
124 {
125 return providerFactory.toString(object, object.getClass(), null, null);
126 }
127
128
129
130
131 // interface implementation
132
133 // Providers
134
135 @Override
136 public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type)
137 {
138 return providerFactory.getExceptionMapper(type);
139 }
140
141 @Override
142 public <T> ContextResolver<T> getContextResolver(Class<T> contextType, MediaType mediaType)
143 {
144 return providerFactory.getContextResolver(contextType, mediaType);
145 }
146
147 // Configuration
148
149 @Override
150 public Map<String, Object> getProperties()
151 {
152 return providerFactory.getProperties();
153 }
154
155 @Override
156 public Object getProperty(String name)
157 {
158 return providerFactory.getProperty(name);
159 }
160
161 @Override
162 public Set<Class<?>> getClasses()
163 {
164 return providerFactory.getProviderClasses();
165 }
166
167 @Override
168 public Set<Object> getInstances()
169 {
170 return providerFactory.getProviderInstances();
171 }
172
173 @Override
174 public ClientConfiguration register(Class<?> providerClass)
175 {
176 providerFactory.register(providerClass);
177 return this;
178 }
179
180 @Override
181 public ClientConfiguration register(Object provider)
182 {
183 providerFactory.register(provider);
184 return this;
185 }
186
187 @Override
188 public ClientConfiguration register(Class<?> providerClass, int priority)
189 {
190 providerFactory.register(providerClass, priority);
191 return this;
192 }
193
194 @Override
195 public ClientConfiguration register(Object provider, int Priority)
196 {
197 providerFactory.register(provider, Priority);
198 return this;
199 }
200
201 @Override
202 public ClientConfiguration property(String name, Object value)
203 {
204 providerFactory.property(name, value);
205 return this;
206 }
207
208 @Override
209 public Configuration getConfiguration()
210 {
211 return this;
212 }
213
214 @Override
215 public ClientConfiguration register(Class<?> componentClass, Class<?>... contracts)
216 {
217 providerFactory.register(componentClass, contracts);
218 return this;
219 }
220
221 @Override
222 public ClientConfiguration register(Class<?> componentClass, Map<Class<?>, Integer> contracts)
223 {
224 providerFactory.register(componentClass, contracts);
225 return this;
226 }
227
228 @Override
229 public ClientConfiguration register(Object component, Class<?>... contracts)
230 {
231 providerFactory.register(component, contracts);
232 return this;
233 }
234
235 @Override
236 public ClientConfiguration register(Object component, Map<Class<?>, Integer> contracts)
237 {
238 providerFactory.register(component, contracts);
239 return this;
240 }
241
242 @Override
243 public RuntimeType getRuntimeType()
244 {
245 return RuntimeType.CLIENT;
246 }
247
248 @Override
249 public Collection<String> getPropertyNames()
250 {
251 return providerFactory.getProperties().keySet();
252 }
253
254 @Override
255 public boolean isEnabled(Feature feature)
256 {
257 return providerFactory.isEnabled(feature);
258 }
259
260 @Override
261 public boolean isEnabled(Class<? extends Feature> featureClass)
262 {
263 return providerFactory.isEnabled(featureClass);
264 }
265
266 @Override
267 public boolean isRegistered(Object component)
268 {
269 return providerFactory.isRegistered(component);
270 }
271
272 @Override
273 public boolean isRegistered(Class<?> componentClass)
274 {
275 return providerFactory.isRegistered(componentClass);
276 }
277
278 @Override
279 public Map<Class<?>, Integer> getContracts(Class<?> componentClass)
280 {
281 return providerFactory.getContracts(componentClass);
282 }
283
284 public <I extends RxInvoker<?>> RxInvokerProvider<I> getRxInvokerProvider(Class<I> clazz)
285 {
286 Map<Class<?>, Map<Class<?>, Integer>> classContracts = providerFactory.getClassContracts();
287 for (Entry<Class<?>, Map<Class<?>, Integer>> entry : classContracts.entrySet()) {
288 if (entry.getValue().containsKey(RxInvokerProvider.class)) {
289 RxInvokerProvider<?> rip = (RxInvokerProvider<?>)providerFactory.createProviderInstance(entry.getKey());
290 if (rip.isProviderFor(clazz)) {
291 return (RxInvokerProvider<I>)rip;
292 }
293 }
294 }
295 return null;
296 }
297 }
0 package org.jboss.resteasy.client.jaxrs.internal;
1
2 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
3 import org.jboss.resteasy.client.jaxrs.i18n.Messages;
4
5 import javax.ws.rs.HttpMethod;
6 import javax.ws.rs.client.AsyncInvoker;
7 import javax.ws.rs.client.CompletionStageRxInvoker;
8 import javax.ws.rs.client.Entity;
9 import javax.ws.rs.client.Invocation;
10 import javax.ws.rs.client.RxInvoker;
11 import javax.ws.rs.client.RxInvokerProvider;
12 import javax.ws.rs.core.CacheControl;
13 import javax.ws.rs.core.Cookie;
14 import javax.ws.rs.core.GenericType;
15 import javax.ws.rs.core.MediaType;
16 import javax.ws.rs.core.MultivaluedMap;
17 import javax.ws.rs.core.Response;
18
19 import java.net.URI;
20 import java.util.Locale;
21
22 /**
23 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
24 * @author <a href="mailto:alessio.soldano@jboss.com">Alessio Soldano</a>
25 * @version $Revision: 1 $
26 */
27 public class ClientInvocationBuilder implements ClientInvocationBuilderInterface
28 {
29 protected ClientInvocation invocation;
30
31 public ClientInvocationBuilder(ResteasyClient client, URI uri, ClientConfiguration configuration)
32 {
33 invocation = new ClientInvocation(client, uri, new ClientRequestHeaders(configuration), configuration);
34 }
35
36 public ClientInvocation getInvocation()
37 {
38 return invocation;
39 }
40
41 public ClientRequestHeaders getHeaders()
42 {
43 return invocation.headers;
44 }
45
46 @Override
47 public Invocation.Builder accept(String... mediaTypes)
48 {
49 getHeaders().accept(mediaTypes);
50 return this;
51 }
52
53 @Override
54 public Invocation.Builder accept(MediaType... mediaTypes)
55 {
56 getHeaders().accept(mediaTypes);
57 return this;
58 }
59
60 @Override
61 public Invocation.Builder acceptLanguage(Locale... locales)
62 {
63 getHeaders().acceptLanguage(locales);
64 return this;
65 }
66
67 @Override
68 public Invocation.Builder acceptLanguage(String... locales)
69 {
70 getHeaders().acceptLanguage(locales);
71 return this;
72 }
73
74 @Override
75 public Invocation.Builder acceptEncoding(String... encodings)
76 {
77 getHeaders().acceptEncoding(encodings);
78 return this;
79 }
80
81 @Override
82 public Invocation.Builder cookie(Cookie cookie)
83 {
84 if (!(Cookie.class.equals(cookie.getClass())))
85 {
86 cookie = new Cookie(cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getVersion());
87 }
88 getHeaders().cookie(cookie);
89 return this;
90 }
91
92 @Override
93 public Invocation.Builder cookie(String name, String value)
94 {
95 getHeaders().cookie(new Cookie(name, value));
96 return this;
97 }
98
99 @Override
100 public Invocation.Builder cacheControl(CacheControl cacheControl)
101 {
102 getHeaders().cacheControl(cacheControl);
103 return this;
104 }
105
106 @Override
107 public Invocation.Builder header(String name, Object value)
108 {
109 getHeaders().header(name, value);
110 return this;
111 }
112
113 @Override
114 public Invocation.Builder headers(MultivaluedMap<String, Object> headers)
115 {
116 getHeaders().setHeaders(headers);
117 return this;
118 }
119
120 @Override
121 public Invocation build(String method)
122 {
123 invocation.setMethod(method);
124 return invocation;
125 }
126
127 @Override
128 public Invocation build(String method, Entity<?> entity)
129 {
130 invocation.setMethod(method);
131 invocation.setEntity(entity);
132 return invocation;
133 }
134
135 @Override
136 public Invocation buildGet()
137 {
138 return build(HttpMethod.GET);
139 }
140
141 @Override
142 public Invocation buildDelete()
143 {
144 return build(HttpMethod.DELETE);
145 }
146
147 @Override
148 public Invocation buildPost(Entity<?> entity)
149 {
150 return build(HttpMethod.POST, entity);
151 }
152
153 @Override
154 public Invocation buildPut(Entity<?> entity)
155 {
156 return build(HttpMethod.PUT, entity);
157 }
158
159 @Override
160 public AsyncInvoker async()
161 {
162 return new AsynchronousInvoke(invocation);
163 }
164
165 @Override
166 public Response get()
167 {
168 return buildGet().invoke();
169 }
170
171 @Override
172 public <T> T get(Class<T> responseType)
173 {
174 return buildGet().invoke(responseType);
175 }
176
177 @Override
178 public <T> T get(GenericType<T> responseType)
179 {
180 return buildGet().invoke(responseType);
181 }
182
183 @Override
184 public Response put(Entity<?> entity)
185 {
186 return buildPut(entity).invoke();
187 }
188
189 @Override
190 public <T> T put(Entity<?> entity, Class<T> responseType)
191 {
192 return buildPut(entity).invoke(responseType);
193 }
194
195 @Override
196 public <T> T put(Entity<?> entity, GenericType<T> responseType)
197 {
198 return buildPut(entity).invoke(responseType);
199 }
200
201 @Override
202 public Response post(Entity<?> entity)
203 {
204 return buildPost(entity).invoke();
205 }
206
207 @Override
208 public <T> T post(Entity<?> entity, Class<T> responseType)
209 {
210 return buildPost(entity).invoke(responseType);
211 }
212
213 @Override
214 public <T> T post(Entity<?> entity, GenericType<T> responseType)
215 {
216 return buildPost(entity).invoke(responseType);
217 }
218
219 @Override
220 public Response delete()
221 {
222 return buildDelete().invoke();
223 }
224
225 @Override
226 public <T> T delete(Class<T> responseType)
227 {
228 return buildDelete().invoke(responseType);
229 }
230
231 @Override
232 public <T> T delete(GenericType<T> responseType)
233 {
234 return buildDelete().invoke(responseType);
235 }
236
237 @Override
238 public Response head()
239 {
240 return build(HttpMethod.HEAD).invoke();
241 }
242
243 @Override
244 public Response options()
245 {
246 return build(HttpMethod.OPTIONS).invoke();
247 }
248
249 @Override
250 public <T> T options(Class<T> responseType)
251 {
252 return build(HttpMethod.OPTIONS).invoke(responseType);
253 }
254
255 @Override
256 public <T> T options(GenericType<T> responseType)
257 {
258 return build(HttpMethod.OPTIONS).invoke(responseType);
259 }
260
261 @Override
262 public Response trace()
263 {
264 return build("TRACE").invoke();
265 }
266
267 @Override
268 public <T> T trace(Class<T> responseType)
269 {
270 return build("TRACE").invoke(responseType);
271 }
272
273 @Override
274 public <T> T trace(GenericType<T> responseType)
275 {
276 return build("TRACE").invoke(responseType);
277 }
278
279 @Override
280 public Response method(String name)
281 {
282 return build(name).invoke();
283 }
284
285 @Override
286 public <T> T method(String name, Class<T> responseType)
287 {
288 return build(name).invoke(responseType);
289 }
290
291 @Override
292 public <T> T method(String name, GenericType<T> responseType)
293 {
294 return build(name).invoke(responseType);
295 }
296
297 @Override
298 public Response method(String name, Entity<?> entity)
299 {
300 return build(name, entity).invoke();
301 }
302
303 @Override
304 public <T> T method(String name, Entity<?> entity, Class<T> responseType)
305 {
306 return build(name, entity).invoke(responseType);
307 }
308
309 @Override
310 public <T> T method(String name, Entity<?> entity, GenericType<T> responseType)
311 {
312 return build(name, entity).invoke(responseType);
313 }
314
315 @Override
316 public Invocation.Builder property(String name, Object value)
317 {
318 invocation.property(name, value);
319 return this;
320 }
321
322 public boolean isChunked()
323 {
324 return invocation.isChunked();
325 }
326
327 public void setChunked(boolean chunked)
328 {
329 invocation.setChunked(chunked);
330 }
331
332
333 @Override
334 public CompletionStageRxInvoker rx()
335 {
336 return new CompletionStageRxInvokerImpl(this, invocation.getClient().asyncInvocationExecutor());
337 }
338
339 @Override
340 public <T extends RxInvoker> T rx(Class<T> clazz)
341 {
342 RxInvokerProvider<T> provider = invocation.getClientConfiguration().getRxInvokerProvider(clazz);
343 if (provider == null) {
344 throw new IllegalStateException(Messages.MESSAGES.unableToInstantiate(clazz));
345 }
346 return provider.getRxInvoker(this, invocation.getClient().asyncInvocationExecutor());
347 }
348
349 public Response patch(Entity<?> entity)
350 {
351 return build(HttpMethod.PATCH, entity).invoke();
352 }
353
354 public <T> T patch(Entity<?> entity, Class<T> responseType)
355 {
356 return build(HttpMethod.PATCH, entity).invoke(responseType);
357 }
358
359 public <T> T patch(Entity<?> entity, GenericType<T> responseType)
360 {
361 return build(HttpMethod.PATCH, entity).invoke(responseType);
362 }
363
364 }
0 package org.jboss.resteasy.client.jaxrs.internal;
1
2 import java.util.concurrent.CompletableFuture;
3 import java.util.concurrent.CompletionStage;
4 import java.util.concurrent.ExecutorService;
5
6 import javax.ws.rs.HttpMethod;
7 import javax.ws.rs.client.CompletionStageRxInvoker;
8 import javax.ws.rs.client.Entity;
9 import javax.ws.rs.client.SyncInvoker;
10 import javax.ws.rs.core.GenericType;
11 import javax.ws.rs.core.Response;
12
13 /**
14 *
15 * @author <a href="mailto:ron.sigal@jboss.com">Ron Sigal</a>
16 * @author <a href="mailto:alessio.soldano@jboss.com">Alessio Soldano</a>
17 * @date March 9, 2016
18 */
19 public class CompletionStageRxInvokerImpl implements CompletionStageRxInvoker
20 {
21 private final SyncInvoker builder;
22
23 private final ExecutorService executor;
24
25 public CompletionStageRxInvokerImpl(SyncInvoker builder)
26 {
27 this(builder, null);
28 }
29
30 public CompletionStageRxInvokerImpl(SyncInvoker builder, ExecutorService executor)
31 {
32 this.builder = builder;
33 this.executor = executor;
34 }
35
36 @Override
37 public CompletionStage<Response> get()
38 {
39 if (executor == null)
40 {
41 return CompletableFuture.supplyAsync(() -> builder.get());
42 }
43 else
44 {
45 return CompletableFuture.supplyAsync(() -> builder.get(), executor);
46 }
47
48 }
49
50 @Override
51 public <T> CompletionStage<T> get(Class<T> responseType)
52 {
53 if (executor == null)
54 {
55 return CompletableFuture.supplyAsync(() -> builder.get(responseType));
56 }
57 else
58 {
59 return CompletableFuture.supplyAsync(() -> builder.get(responseType), executor);
60 }
61 }
62
63 @Override
64 public <T> CompletionStage<T> get(GenericType<T> responseType)
65 {
66 if (executor == null)
67 {
68 return CompletableFuture.supplyAsync(() -> builder.get(responseType));
69 }
70 else
71 {
72 return CompletableFuture.supplyAsync(() -> builder.get(responseType), executor);
73 }
74 }
75
76 @Override
77 public CompletionStage<Response> put(Entity<?> entity)
78 {
79 if (executor == null)
80 {
81 return CompletableFuture.supplyAsync(() -> builder.put(entity));
82 }
83 else
84 {
85 return CompletableFuture.supplyAsync(() -> builder.put(entity), executor);
86 }
87 }
88
89 @Override
90 public <T> CompletionStage<T> put(Entity<?> entity, Class<T> clazz)
91 {
92 if (executor == null)
93 {
94 return CompletableFuture.supplyAsync(() -> builder.put(entity, clazz));
95 }
96 else
97 {
98 return CompletableFuture.supplyAsync(() -> builder.put(entity, clazz), executor);
99 }
100 }
101
102 @Override
103 public <T> CompletionStage<T> put(Entity<?> entity, GenericType<T> type)
104 {
105 if (executor == null)
106 {
107 return CompletableFuture.supplyAsync(() -> builder.put(entity, type));
108 }
109 else
110 {
111 return CompletableFuture.supplyAsync(() -> builder.put(entity, type), executor);
112 }
113 }
114
115 @Override
116 public CompletionStage<Response> post(Entity<?> entity)
117 {
118 if (executor == null)
119 {
120 return CompletableFuture.supplyAsync(() -> builder.post(entity));
121 }
122 else
123 {
124 return CompletableFuture.supplyAsync(() -> builder.post(entity), executor);
125 }
126 }
127
128 @Override
129 public <T> CompletionStage<T> post(Entity<?> entity, Class<T> clazz)
130 {
131 if (executor == null)
132 {
133 return CompletableFuture.supplyAsync(() -> builder.post(entity, clazz));
134 }
135 else
136 {
137 return CompletableFuture.supplyAsync(() -> builder.post(entity, clazz), executor);
138 }
139 }
140
141 @Override
142 public <T> CompletionStage<T> post(Entity<?> entity, GenericType<T> type)
143 {
144 if (executor == null)
145 {
146 return CompletableFuture.supplyAsync(() -> builder.post(entity, type));
147 }
148 else
149 {
150 return CompletableFuture.supplyAsync(() -> builder.post(entity, type), executor);
151 }
152 }
153
154 @Override
155 public CompletionStage<Response> delete()
156 {
157 if (executor == null)
158 {
159 return CompletableFuture.supplyAsync(() -> builder.delete());
160 }
161 else
162 {
163 return CompletableFuture.supplyAsync(() -> builder.delete(), executor);
164 }
165 }
166
167 @Override
168 public <T> CompletionStage<T> delete(Class<T> responseType)
169 {
170 if (executor == null)
171 {
172 return CompletableFuture.supplyAsync(() -> builder.delete(responseType));
173 }
174 else
175 {
176 return CompletableFuture.supplyAsync(() -> builder.delete(responseType), executor);
177 }
178 }
179
180 @Override
181 public <T> CompletionStage<T> delete(GenericType<T> responseType)
182 {
183 if (executor == null)
184 {
185 return CompletableFuture.supplyAsync(() -> builder.delete(responseType));
186 }
187 else
188 {
189 return CompletableFuture.supplyAsync(() -> builder.delete(responseType), executor);
190 }
191 }
192
193 @Override
194 public CompletionStage<Response> head()
195 {
196 if (executor == null)
197 {
198 return CompletableFuture.supplyAsync(() -> builder.head());
199 }
200 else
201 {
202 return CompletableFuture.supplyAsync(() -> builder.head(), executor);
203 }
204 }
205
206 @Override
207 public CompletionStage<Response> options()
208 {
209 if (executor == null)
210 {
211 return CompletableFuture.supplyAsync(() -> builder.options());
212 }
213 else
214 {
215 return CompletableFuture.supplyAsync(() -> builder.options(), executor);
216 }
217 }
218
219 @Override
220 public <T> CompletionStage<T> options(Class<T> responseType)
221 {
222 if (executor == null)
223 {
224 return CompletableFuture.supplyAsync(() -> builder.options(responseType));
225 }
226 {
227 return CompletableFuture.supplyAsync(() -> builder.options(responseType), executor);
228 }
229 }
230
231 @Override
232 public <T> CompletionStage<T> options(GenericType<T> responseType)
233 {
234 if (executor == null)
235 {
236 return CompletableFuture.supplyAsync(() -> builder.options(responseType));
237 }
238 else
239 {
240 return CompletableFuture.supplyAsync(() -> builder.options(responseType), executor);
241 }
242 }
243
244 @Override
245 public CompletionStage<Response> trace()
246 {
247 if (executor == null)
248 {
249 return CompletableFuture.supplyAsync(() -> builder.trace());
250 }
251 else
252 {
253 return CompletableFuture.supplyAsync(() -> builder.trace(), executor);
254 }
255 }
256
257 @Override
258 public <T> CompletionStage<T> trace(Class<T> responseType)
259 {
260 if (executor == null)
261 {
262 return CompletableFuture.supplyAsync(() -> builder.trace(responseType));
263 }
264 else
265 {
266 return CompletableFuture.supplyAsync(() -> builder.trace(responseType), executor);
267 }
268 }
269
270 @Override
271 public <T> CompletionStage<T> trace(GenericType<T> responseType)
272 {
273 if (executor == null)
274 {
275 return CompletableFuture.supplyAsync(() -> builder.trace(responseType));
276 }
277 else
278 {
279 return CompletableFuture.supplyAsync(() -> builder.trace(responseType), executor);
280 }
281 }
282
283 @Override
284 public CompletionStage<Response> method(String name)
285 {
286 if (executor == null)
287 {
288 return CompletableFuture.supplyAsync(() -> builder.method(name));
289 }
290 else
291 {
292 return CompletableFuture.supplyAsync(() -> builder.method(name), executor);
293 }
294 }
295
296 @Override
297 public <T> CompletionStage<T> method(String name, Class<T> responseType)
298 {
299 if (executor == null)
300 {
301 return CompletableFuture.supplyAsync(() -> builder.method(name, responseType));
302 }
303 else
304 {
305 return CompletableFuture.supplyAsync(() -> builder.method(name, responseType), executor);
306 }
307 }
308
309 @Override
310 public <T> CompletionStage<T> method(String name, GenericType<T> responseType)
311 {
312 if (executor == null)
313 {
314 return CompletableFuture.supplyAsync(() -> builder.method(name, responseType));
315 }
316 else
317 {
318 return CompletableFuture.supplyAsync(() -> builder.method(name, responseType), executor);
319 }
320 }
321
322 @Override
323 public CompletionStage<Response> method(String name, Entity<?> entity)
324 {
325 if (executor == null)
326 {
327 return CompletableFuture.supplyAsync(() -> builder.method(name, entity));
328 }
329 {
330 return CompletableFuture.supplyAsync(() -> builder.method(name, entity), executor);
331 }
332 }
333
334 @Override
335 public <T> CompletionStage<T> method(String name, Entity<?> entity, Class<T> responseType)
336 {
337 if (executor == null)
338 {
339 return CompletableFuture.supplyAsync(() -> builder.method(name, entity, responseType));
340 }
341 else
342 {
343 return CompletableFuture.supplyAsync(() -> builder.method(name, entity, responseType), executor);
344 }
345 }
346
347 @Override
348 public <T> CompletionStage<T> method(String name, Entity<?> entity, GenericType<T> responseType)
349 {
350 if (executor == null)
351 {
352 return CompletableFuture.supplyAsync(() -> builder.method(name, entity, responseType));
353 }
354 else
355 {
356 return CompletableFuture.supplyAsync(() -> builder.method(name, entity, responseType), executor);
357 }
358 }
359
360 public ExecutorService getExecutor()
361 {
362 return executor;
363 }
364
365 public CompletionStage<Response> patch(Entity<?> entity)
366 {
367 if (executor == null)
368 {
369 return CompletableFuture.supplyAsync(() -> builder.method(HttpMethod.PATCH, entity));
370 }
371 else
372 {
373 return CompletableFuture.supplyAsync(() -> builder.method(HttpMethod.PATCH, entity), executor);
374 }
375 }
376
377 public <T> CompletionStage<T> patch(Entity<?> entity, Class<T> responseType)
378 {
379 if (executor == null)
380 {
381 return CompletableFuture.supplyAsync(() -> builder.method(HttpMethod.PATCH, entity, responseType));
382 }
383 else
384 {
385 return CompletableFuture.supplyAsync(() -> builder.method(HttpMethod.PATCH, entity, responseType), executor);
386 }
387 }
388
389 public <T> CompletionStage<T> patch(Entity<?> entity, GenericType<T> responseType)
390 {
391 if (executor == null)
392 {
393 return CompletableFuture.supplyAsync(() -> builder.method(HttpMethod.PATCH, entity, responseType));
394 }
395 else
396 {
397 return CompletableFuture.supplyAsync(() -> builder.method(HttpMethod.PATCH, entity, responseType), executor);
398 }
399 }
400
401 }
0 package org.jboss.resteasy.plugins.providers.sse.client;
1
2 import java.util.Date;
3 import java.util.List;
4 import java.util.concurrent.CopyOnWriteArrayList;
5 import java.util.concurrent.CountDownLatch;
6 import java.util.concurrent.Executors;
7 import java.util.concurrent.ScheduledExecutorService;
8 import java.util.concurrent.ThreadFactory;
9 import java.util.concurrent.TimeUnit;
10 import java.util.concurrent.atomic.AtomicInteger;
11 import java.util.concurrent.atomic.AtomicReference;
12 import java.util.function.Consumer;
13
14 import javax.ws.rs.ServiceUnavailableException;
15 import javax.ws.rs.client.Invocation;
16 import javax.ws.rs.client.WebTarget;
17 import javax.ws.rs.core.MediaType;
18 import javax.ws.rs.sse.InboundSseEvent;
19 import javax.ws.rs.sse.SseEventSource;
20
21 import org.apache.http.HttpHeaders;
22 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
23 import org.jboss.resteasy.plugins.providers.sse.SseConstants;
24 import org.jboss.resteasy.plugins.providers.sse.SseEventInputImpl;
25 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
26
27 public class SseEventSourceImpl implements SseEventSource
28 {
29 public static final long RECONNECT_DEFAULT = 500;
30
31 private final WebTarget target;
32
33 private static final long CLOSE_WAIT = 30;
34
35 private final long reconnectDelay;
36
37 private final boolean disableKeepAlive;
38
39 private final ScheduledExecutorService executor;
40
41 private enum State {
42 PENDING, OPEN, CLOSED
43 }
44
45 private final AtomicReference<State> state = new AtomicReference<>(State.PENDING);
46
47 private final List<Consumer<InboundSseEvent>> onEventConsumers = new CopyOnWriteArrayList<>();
48
49 private final List<Consumer<Throwable>> onErrorConsumers = new CopyOnWriteArrayList<>();
50
51 private final List<Runnable> onCompleteConsumers = new CopyOnWriteArrayList<>();
52
53 protected static class SourceBuilder extends Builder
54 {
55 private WebTarget target = null;
56
57 private long reconnect = RECONNECT_DEFAULT;
58
59 private String name = null;
60
61 private boolean disableKeepAlive = false;
62
63 public SourceBuilder()
64 {
65 //NOOP
66 }
67
68 public Builder named(String name)
69 {
70 this.name = name;
71 return this;
72 }
73
74 public SseEventSource build()
75 {
76 return new SseEventSourceImpl(target, name, reconnect, disableKeepAlive, false);
77 }
78
79 @Override
80 public Builder target(WebTarget target)
81 {
82 if (target == null)
83 {
84 throw new NullPointerException();
85 }
86 this.target = target;
87 return this;
88 }
89
90 @Override
91 public Builder reconnectingEvery(long delay, TimeUnit unit)
92 {
93 reconnect = unit.toMillis(delay);
94 return this;
95 }
96 }
97
98 public SseEventSourceImpl(final WebTarget target)
99 {
100 this(target, true);
101 }
102
103 public SseEventSourceImpl(final WebTarget target, final boolean open)
104 {
105 this(target, null, RECONNECT_DEFAULT, false, open);
106 }
107
108 private SseEventSourceImpl(final WebTarget target, String name, long reconnectDelay, final boolean disableKeepAlive,
109 final boolean open)
110 {
111 if (target == null)
112 {
113 throw new IllegalArgumentException(Messages.MESSAGES.webTargetIsNotSetForEventSource());
114 }
115 this.target = target;
116 this.reconnectDelay = reconnectDelay;
117 this.disableKeepAlive = disableKeepAlive;
118
119 if (name == null)
120 {
121 name = String.format("sse-event-source(%s)", target.getUri());
122 }
123 ScheduledExecutorService scheduledExecutor = null;
124 if (target instanceof ResteasyWebTarget)
125 {
126 scheduledExecutor = ((ResteasyWebTarget) target).getResteasyClient().getScheduledExecutor();
127 }
128 this.executor = scheduledExecutor != null ? scheduledExecutor : Executors
129 .newSingleThreadScheduledExecutor(new DaemonThreadFactory());
130 if (open)
131 {
132 open();
133 }
134 }
135
136 private static class DaemonThreadFactory implements ThreadFactory
137 {
138 private static final AtomicInteger poolNumber = new AtomicInteger(1);
139
140 private final ThreadGroup group;
141
142 private final AtomicInteger threadNumber = new AtomicInteger(1);
143
144 private final String namePrefix;
145
146 DaemonThreadFactory()
147 {
148 SecurityManager s = System.getSecurityManager();
149 group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
150 namePrefix = "resteasy-sse-eventsource" + poolNumber.getAndIncrement() + "-thread-";
151 }
152
153 public Thread newThread(Runnable r)
154 {
155 Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
156 t.setDaemon(true);
157 return t;
158 }
159 }
160
161 @Override
162 public void open()
163 {
164 open(null);
165 }
166
167 public void open(String lastEventId)
168 {
169 if (!state.compareAndSet(State.PENDING, State.OPEN))
170 {
171 throw new IllegalStateException(Messages.MESSAGES.eventSourceIsNotReadyForOpen());
172 }
173 EventHandler handler = new EventHandler(reconnectDelay, lastEventId);
174 executor.submit(handler);
175 handler.awaitConnected();
176 }
177
178 @Override
179 public boolean isOpen()
180 {
181 return state.get() == State.OPEN;
182 }
183
184 @Override
185 public void close()
186 {
187 this.close(CLOSE_WAIT, TimeUnit.SECONDS);
188 }
189
190 @Override
191 public void register(Consumer<InboundSseEvent> onEvent)
192 {
193 if (onEvent == null)
194 {
195 throw new IllegalArgumentException();
196 }
197 onEventConsumers.add(onEvent);
198 }
199
200 @Override
201 public void register(Consumer<InboundSseEvent> onEvent, Consumer<Throwable> onError)
202 {
203 if (onEvent == null)
204 {
205 throw new IllegalArgumentException();
206 }
207 if (onError == null)
208 {
209 throw new IllegalArgumentException();
210 }
211 onEventConsumers.add(onEvent);
212 onErrorConsumers.add(onError);
213 }
214
215 @Override
216 public void register(Consumer<InboundSseEvent> onEvent, Consumer<Throwable> onError, Runnable onComplete)
217 {
218 if (onEvent == null)
219 {
220 throw new IllegalArgumentException();
221 }
222 if (onError == null)
223 {
224 throw new IllegalArgumentException();
225 }
226 if (onComplete == null)
227 {
228 throw new IllegalArgumentException();
229 }
230 onEventConsumers.add(onEvent);
231 onErrorConsumers.add(onError);
232 onCompleteConsumers.add(onComplete);
233 }
234
235 @Override
236 public boolean close(final long timeout, final TimeUnit unit)
237 {
238 if (state.getAndSet(State.CLOSED) != State.CLOSED)
239 {
240 ResteasyWebTarget resteasyWebTarget = (ResteasyWebTarget) target;
241 //close httpEngine to close connection
242 resteasyWebTarget.getResteasyClient().httpEngine().close();
243 executor.shutdownNow();
244 }
245 try
246 {
247 if (!executor.awaitTermination(timeout, unit))
248 {
249 return false;
250 }
251 }
252 catch (InterruptedException e)
253 {
254 onErrorConsumers.forEach(consumer -> {
255 consumer.accept(e);
256 });
257 Thread.currentThread().interrupt();
258 return false;
259 }
260
261 return true;
262 }
263
264 private class EventHandler implements Runnable
265 {
266
267 private final CountDownLatch connectedLatch;
268
269 private String lastEventId;
270
271 private long reconnectDelay;
272
273 public EventHandler(final long reconnectDelay, final String lastEventId)
274 {
275 this.connectedLatch = new CountDownLatch(1);
276 this.reconnectDelay = reconnectDelay;
277 this.lastEventId = lastEventId;
278 }
279
280 private EventHandler(final EventHandler anotherHandler)
281 {
282 this.connectedLatch = anotherHandler.connectedLatch;
283 this.reconnectDelay = anotherHandler.reconnectDelay;
284 this.lastEventId = anotherHandler.lastEventId;
285 }
286
287 @Override
288 public void run()
289 {
290 SseEventInputImpl eventInput = null;
291 try
292 {
293 final Invocation.Builder request = buildRequest();
294 if (state.get() == State.OPEN)
295 {
296 eventInput = request.get(SseEventInputImpl.class);
297 }
298 }
299 catch (ServiceUnavailableException ex)
300 {
301 if (ex.hasRetryAfter())
302 {
303 Date requestTime = new Date();
304 reconnectDelay = ex.getRetryTime(requestTime).getTime() - requestTime.getTime();
305 }
306 onErrorConsumers.forEach(consumer -> {
307 consumer.accept(ex);
308 });
309 }
310 catch (Throwable e)
311 {
312 onErrorConsumers.forEach(consumer -> {
313 consumer.accept(e);
314 });
315 state.set(State.CLOSED);
316 }
317 finally
318 {
319 if (connectedLatch != null)
320 {
321 connectedLatch.countDown();
322 }
323 }
324 while (!Thread.currentThread().isInterrupted() && state.get() == State.OPEN)
325 {
326 if (eventInput == null || eventInput.isClosed())
327 {
328 reconnect(reconnectDelay);
329 break;
330 }
331 else
332 {
333 InboundSseEvent event = eventInput.read();
334 if (event != null)
335 {
336 onEvent(event);
337 onEventConsumers.forEach(consumer -> {
338 consumer.accept(event);
339 });
340 }
341 }
342 }
343 }
344
345 public void awaitConnected()
346 {
347 try
348 {
349 connectedLatch.await(30, TimeUnit.SECONDS);
350 }
351 catch (InterruptedException ex)
352 {
353 Thread.currentThread().interrupt();
354 }
355
356 }
357
358 private void onEvent(final InboundSseEvent event)
359 {
360 if (event == null)
361 {
362 return;
363 }
364 if (event.getId() != null)
365 {
366 lastEventId = event.getId();
367 }
368 if (event.isReconnectDelaySet())
369 {
370 reconnectDelay = event.getReconnectDelay();
371 }
372 }
373
374 private Invocation.Builder buildRequest()
375 {
376 final Invocation.Builder request = target.request(MediaType.SERVER_SENT_EVENTS_TYPE);
377 if (lastEventId != null && !lastEventId.isEmpty())
378 {
379 request.header(SseConstants.LAST_EVENT_ID_HEADER, lastEventId);
380 }
381 if (disableKeepAlive)
382 {
383 request.header(HttpHeaders.CONNECTION, "close");
384 }
385 return request;
386 }
387
388 private void reconnect(final long delay)
389 {
390 if (state.get() != State.OPEN)
391 {
392 return;
393 }
394
395 EventHandler processor = new EventHandler(this);
396 if (delay > 0)
397 {
398 executor.schedule(processor, delay, TimeUnit.MILLISECONDS);
399 }
400 else
401 {
402 executor.submit(processor);
403 }
404 }
405 }
406
407 }
0 org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl$SourceBuilder
33 <parent>
44 <groupId>org.jboss</groupId>
55 <artifactId>jboss-parent</artifactId>
6 <version>21</version>
6 <version>25</version>
77 <relativePath/>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
1010 <groupId>org.jboss.resteasy</groupId>
1111 <artifactId>resteasy-dependencies</artifactId>
12 <version>3.1.4.Final</version>
12 <version>3.5.0.Final</version>
1313 <packaging>pom</packaging>
1414 <name>RESTEasy dependencies BOM</name>
1515 <description>RESTEasy dependencies BOM</description>
1818 <dep.arquillian-bom.version>1.1.11.Final</dep.arquillian-bom.version>
1919 <dep.arquillian-wildfly.version>8.2.1.Final</dep.arquillian-wildfly.version>
2020 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
21 <version.com.fasterxml.classmate>1.3.3</version.com.fasterxml.classmate>
22 <version.com.fasterxml.jackson>2.8.9</version.com.fasterxml.jackson>
21 <version.com.fasterxml.classmate>1.3.4</version.com.fasterxml.classmate>
22 <version.com.fasterxml.jackson>2.9.4</version.com.fasterxml.jackson>
2323 <version.com.google.inject.guice>4.1.0</version.com.google.inject.guice>
2424 <version.com.io7m.xom>1.2.10</version.com.io7m.xom>
2525 <version.com.sun.mail>1.5.6</version.com.sun.mail>
26 <version.com.sun.xml.bind.jaxb-impl>2.2.7</version.com.sun.xml.bind.jaxb-impl>
26 <version.com.sun.xml.bind.jaxb>2.3.0</version.com.sun.xml.bind.jaxb>
2727 <version.com.sun.xml.fastinfoset>1.2.13</version.com.sun.xml.fastinfoset>
2828 <version.commons-io.commons-io>2.5</version.commons-io.commons-io>
2929 <version.hamcrest>1.3</version.hamcrest>
3030 <version.io.netty.netty>3.10.6.Final</version.io.netty.netty>
31 <version.io.netty.netty4>4.1.8.Final</version.io.netty.netty4>
32 <version.io.vertx>3.4.1</version.io.vertx>
33 <version.io.undertow>1.3.25.Final</version.io.undertow>
31 <version.io.netty.netty4>4.1.16.Final</version.io.netty.netty4>
32 <version.io.vertx>3.4.2</version.io.vertx>
33 <version.io.undertow>1.4.18.Final</version.io.undertow>
3434 <version.javax.activation>1.1.1</version.javax.activation>
3535 <version.javax.enterprise.cdi-api>1.2</version.javax.enterprise.cdi-api>
36 <version.javax.json.bind-api>1.0</version.javax.json.bind-api>
37 <version.javax.ws.rs20-api>1.0.0.Final</version.javax.ws.rs20-api>
38 <version.javax.ws.rs-api>1.0.0.Final</version.javax.ws.rs-api>
3639 <version.junit>4.12</version.junit>
37 <version.log4j>2.6.2</version.log4j>
40 <version.log4j>2.9.1</version.log4j>
3841 <version.net.jcip.jcip-annotations>1.0</version.net.jcip.jcip-annotations>
39 <version.org.apache.httpcomponents.httpclient>4.5.2</version.org.apache.httpcomponents.httpclient>
42 <version.org.apache.httpcomponents.httpclient>4.5.4</version.org.apache.httpcomponents.httpclient>
4043 <version.org.apache.httpcomponents.httpcore>4.4.5</version.org.apache.httpcomponents.httpcore>
44 <version.org.apache.httpcomponents.httpasyncclient>4.1.3</version.org.apache.httpcomponents.httpasyncclient>
4145 <version.org.apache.james.apache-mime4j>0.6</version.org.apache.james.apache-mime4j>
4246 <version.org.apache.maven>3.3.9</version.org.apache.maven> <!-- Used to download aether-provider -->
43 <version.org.bouncycastle>1.55</version.org.bouncycastle>
47 <version.org.bouncycastle>1.56</version.org.bouncycastle>
4448 <version.org.codehaus.jackson>1.9.13</version.org.codehaus.jackson>
4549 <version.org.codehaus.jettison>1.3.8</version.org.codehaus.jettison>
4650 <version.org.eclipse.aether>1.1.0</version.org.eclipse.aether>
47 <version.org.eclipse.jetty>9.2.13.v20150730</version.org.eclipse.jetty>
51 <version.org.eclipse.jetty>9.4.7.v20170914</version.org.eclipse.jetty>
52 <version.org.eclipse.yasson>1.0</version.org.eclipse.yasson>
4853 <version.org.glassfish.javax.el>3.0.1-b08</version.org.glassfish.javax.el>
54 <version.org.glassfish.javax.json>1.1</version.org.glassfish.javax.json>
4955 <version.org.hibernate.hibernate-validator>5.2.4.Final</version.org.hibernate.hibernate-validator>
5056 <version.org.hibernate.javax.persistence.hibernate-jpa-2.1-api>1.0.0.Final</version.org.hibernate.javax.persistence.hibernate-jpa-2.1-api>
51 <version.org.infinispan>8.2.6.Final</version.org.infinispan>
57 <version.org.infinispan>8.2.8.Final</version.org.infinispan>
5258 <version.org.jacoco>0.7.9</version.org.jacoco>
5359 <version.org.javassist>3.20.0-GA</version.org.javassist>
54 <version.org.jboss.logging.jboss-logging>3.3.0.Final</version.org.jboss.logging.jboss-logging>
55 <version.org.jboss.logging.jboss-logging-annotations>2.0.1.Final</version.org.jboss.logging.jboss-logging-annotations>
60 <version.org.jboss.logging.jboss-logging>3.3.1.Final</version.org.jboss.logging.jboss-logging>
61 <version.org.jboss.logging.jboss-logging-annotations>2.1.0.Final</version.org.jboss.logging.jboss-logging-annotations>
5662 <version.org.jboss.spec.javax.annotation.jboss-annotations-api_1.2_spec>1.0.0.Final</version.org.jboss.spec.javax.annotation.jboss-annotations-api_1.2_spec>
5763 <version.org.jboss.spec.javax.el.jboss-el-api_3.0_spec>1.0.7.Final</version.org.jboss.spec.javax.el.jboss-el-api_3.0_spec>
5864 <version.org.jboss.spec.javax.ejb.jboss-ejb-api_3.2_spec>1.0.0.Final</version.org.jboss.spec.javax.ejb.jboss-ejb-api_3.2_spec>
5965 <version.org.jboss.spec.javax.jms.jboss-jms-api_2.0_spec>1.0.0.Final</version.org.jboss.spec.javax.jms.jboss-jms-api_2.0_spec>
66 <version.org.jboss.spec.javax.xml.bind-api_2.3_spec>1.0.0.Final</version.org.jboss.spec.javax.xml.bind-api_2.3_spec>
6067 <version.org.jboss.spec.javax.servlet.jboss-servlet-api_3.1_spec>1.0.0.Final</version.org.jboss.spec.javax.servlet.jboss-servlet-api_3.1_spec>
61 <version.org.jboss.spec.javax.ws.jboss-jaxrs-api_2.0_spec>1.0.1.Beta1</version.org.jboss.spec.javax.ws.jboss-jaxrs-api_2.0_spec>
6268 <version.org.jboss.shrinkwrap.resolver>2.2.4</version.org.jboss.shrinkwrap.resolver>
63 <version.org.slf4j>1.7.7</version.org.slf4j>
64 <version.org.wildfly.core.wildfly-cli>2.1.0.Final</version.org.wildfly.core.wildfly-cli>
65 <version.org.wildfly.extras.creaper>1.5.0</version.org.wildfly.extras.creaper>
66 <version.org.wildfly.wildfly-arquillian-container-managed>2.0.0.Final</version.org.wildfly.wildfly-arquillian-container-managed>
67 <version.org.wildfly.wildfly-arquillian-container-remote>2.0.0.Final</version.org.wildfly.wildfly-arquillian-container-remote>
69 <version.microprofile.restclient>1.0</version.microprofile.restclient>
70 <version.microprofile.config>1.1</version.microprofile.config>
71 <version.org.slf4j>1.7.22</version.org.slf4j>
72 <version.org.wildfly.core.wildfly-cli>3.0.6.Final</version.org.wildfly.core.wildfly-cli>
73 <version.org.wildfly.extras.creaper>1.6.1</version.org.wildfly.extras.creaper>
74 <version.org.wildfly.wildfly-arquillian-container-managed>2.1.0.Final</version.org.wildfly.wildfly-arquillian-container-managed>
75 <version.org.wildfly.wildfly-arquillian-container-remote>2.1.0.Final</version.org.wildfly.wildfly-arquillian-container-remote>
6876 <version.org.wildfly-security>10.0.0.Final</version.org.wildfly-security>
69 <version.org.wildfly.security.wildfly-elytron>1.1.0.Beta16</version.org.wildfly.security.wildfly-elytron>
70 <version.org.yaml.snakeyaml>1.17</version.org.yaml.snakeyaml>
77 <version.org.wildfly.security.wildfly-elytron>1.1.5.Final</version.org.wildfly.security.wildfly-elytron>
78 <version.org.yaml.snakeyaml>1.19</version.org.yaml.snakeyaml>
7179 <version.javax.validation-api>1.1.0.Final</version.javax.validation-api>
72 <version.weld>2.4.0.Final</version.weld>
80 <version.weld>2.4.3.Final</version.weld>
81 <version.json.patch>1.3</version.json.patch>
7382 <!-- override version from jboss-parent -->
7483 <version.surefire.plugin>2.18.1</version.surefire.plugin>
84 <version.org.reactivestreams>1.0.1</version.org.reactivestreams>
7585 </properties>
7686
7787 <distributionManagement>
165175 </dependency>
166176
167177 <dependency>
178 <groupId>org.jboss.spec.javax.xml.bind</groupId>
179 <artifactId>jboss-jaxb-api_2.3_spec</artifactId>
180 <version>${version.org.jboss.spec.javax.xml.bind-api_2.3_spec}</version>
181 </dependency>
182
183 <dependency>
184 <groupId>org.jboss.spec.javax.ws.rs</groupId>
185 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
186 <version>${version.javax.ws.rs-api}</version>
187 </dependency>
188
189 <dependency>
168190 <groupId>org.jboss.spec.javax.ws.rs</groupId>
169191 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
170 <version>${version.org.jboss.spec.javax.ws.jboss-jaxrs-api_2.0_spec}</version>
192 <version>${version.javax.ws.rs20-api}</version>
171193 </dependency>
172194
173195 <dependency>
179201
180202 <dependency>
181203 <groupId>com.sun.xml.bind</groupId>
204 <artifactId>jaxb-core</artifactId>
205 <version>${version.com.sun.xml.bind.jaxb}</version>
206 </dependency>
207 <dependency>
208 <groupId>com.sun.xml.bind</groupId>
182209 <artifactId>jaxb-impl</artifactId>
183 <version>${version.com.sun.xml.bind.jaxb-impl}</version>
210 <version>${version.com.sun.xml.bind.jaxb}</version>
184211 </dependency>
185212 <dependency>
186213 <groupId>com.sun.mail</groupId>
230257 <artifactId>httpcore</artifactId>
231258 <version>${version.org.apache.httpcomponents.httpcore}</version>
232259 </dependency>
260 <!-- OPTIONAL dependency to apache HttpAsyncClient.
261 To use it in own projects one needs to manually add a dependency to httpcomponents-asyncclient,
262 and configure ApacheHttpAsyncClient4Engine -->
263 <dependency>
264 <groupId>org.apache.httpcomponents</groupId>
265 <artifactId>httpasyncclient</artifactId>
266 <version>${version.org.apache.httpcomponents.httpasyncclient}</version>
267 <exclusions> <!-- avoid changing these transitive dependency-versions -->
268 <exclusion>
269 <groupId>org.apache.httpcomponents</groupId>
270 <artifactId>httpcore</artifactId>
271 </exclusion>
272 <exclusion>
273 <groupId>org.apache.httpcomponents</groupId>
274 <artifactId>httpclient</artifactId>
275 </exclusion>
276 <exclusion>
277 <groupId>commons-logging</groupId>
278 <artifactId>commons-logging</artifactId>
279 </exclusion>
280 </exclusions>
281 </dependency>
233282 <dependency>
234283 <groupId>net.jcip</groupId>
235284 <artifactId>jcip-annotations</artifactId>
306355 <scope>provided</scope>
307356 </dependency>
308357 <dependency>
309 <groupId>javax.json</groupId>
310 <artifactId>javax.json-api</artifactId>
311 <version>1.0</version>
358 <groupId>javax.json.bind</groupId>
359 <artifactId>javax.json.bind-api</artifactId>
360 <version>${version.javax.json.bind-api}</version>
361 </dependency>
362 <dependency> <!-- json-b ri -->
363 <groupId>org.eclipse</groupId>
364 <artifactId>yasson</artifactId>
365 <version>${version.org.eclipse.yasson}</version>
312366 </dependency>
313367 <dependency>
314368 <groupId>org.glassfish</groupId>
315369 <artifactId>javax.json</artifactId>
316 <version>1.0.3</version>
370 <version>${version.org.glassfish.javax.json}</version>
317371 </dependency>
318372 <dependency>
319373 <groupId>org.jboss.spec.javax.servlet</groupId>
338392 <version>${version.com.google.inject.guice}</version>
339393 </dependency>
340394 <!-- Needed by org.jboss.resteasy.utils.PermissionUtil -->
341 <dependency>
342 <groupId>com.io7m.xom</groupId>
343 <artifactId>xom</artifactId>
344 <version>${version.com.io7m.xom}</version>
345 <exclusions>
395 <dependency>
396 <groupId>com.io7m.xom</groupId>
397 <artifactId>xom</artifactId>
398 <version>${version.com.io7m.xom}</version>
399 <exclusions>
346400 <exclusion>
347401 <groupId>xml-apis</groupId>
348 <artifactId>xml-apis</artifactId>
402 <artifactId>xml-apis</artifactId>
349403 </exclusion>
350404 </exclusions>
351405 </dependency>
462516 <groupId>org.glassfish</groupId>
463517 <artifactId>javax.el</artifactId>
464518 <version>${version.org.glassfish.javax.el}</version>
519 </dependency>
520
521 <!-- Microprofile related -->
522 <dependency>
523 <groupId>org.eclipse.microprofile.rest.client</groupId>
524 <artifactId>microprofile-rest-client-api</artifactId>
525 <version>${version.microprofile.restclient}</version>
526 </dependency>
527
528 <dependency>
529 <groupId>org.eclipse.microprofile.config</groupId>
530 <artifactId>microprofile-config-api</artifactId>
531 <version>${version.microprofile.config}</version>
465532 </dependency>
466533
467534 <!-- testsuite dependencies -->
650717 <artifactId>wildfly-arquillian-container-remote</artifactId>
651718 <version>${version.org.wildfly.wildfly-arquillian-container-remote}</version>
652719 </dependency>
720 <dependency>
721 <groupId>com.github.fge</groupId>
722 <artifactId>json-patch</artifactId>
723 <version>${version.json.patch}</version>
724 </dependency>
725 <dependency>
726 <groupId>org.reactivestreams</groupId>
727 <artifactId>reactive-streams</artifactId>
728 <version>${version.org.reactivestreams}</version>
729 </dependency>
653730 </dependencies>
654731 </dependencyManagement>
655732 </project>
55 <parent>
66 <artifactId>resteasy-jaxrs-all</artifactId>
77 <groupId>org.jboss.resteasy</groupId>
8 <version>3.1.4.Final</version>
8 <version>3.5.0.Final</version>
99 <relativePath>../pom.xml</relativePath>
1010 </parent>
1111 <artifactId>resteasy-guice</artifactId>
11
22 import com.google.inject.Binder;
33 import com.google.inject.Module;
4 import org.jboss.resteasy.client.ClientExecutor;
5 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
6 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
7 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
48
59 import javax.ws.rs.core.Response;
610 import javax.ws.rs.core.UriBuilder;
711 import javax.ws.rs.core.Variant;
812 import javax.ws.rs.ext.RuntimeDelegate;
913
10 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
11 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
12
1314 public class JaxrsModule implements Module
1415 {
1516
1617 public void configure(final Binder binder)
1718 {
19 binder.bind(ClientExecutor.class).to(ApacheHttpClient4Executor.class);
1820 binder.bind(ClientHttpEngine.class).to(ApacheHttpClient4Engine.class);
1921 binder.bind(RuntimeDelegate.class).toInstance(RuntimeDelegate.getInstance());
2022 binder.bind(Response.ResponseBuilder.class).toProvider(ResponseBuilderProvider.class);
6060 };
6161 final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
6262 processor.processInjector(Guice.createInjector(module));
63 final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
63 final TestResource resource = TestPortProvider.createProxy(TestResource.class);
6464 Assert.assertEquals("method", resource.getName());
6565 dispatcher.getRegistry().removeRegistrations(MethodTestResource.class);
6666 }
7878 };
7979 final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
8080 processor.processInjector(Guice.createInjector(module));
81 final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
81 final TestResource resource = TestPortProvider.createProxy(TestResource.class);
8282 Assert.assertEquals("field", resource.getName());
8383 dispatcher.getRegistry().removeRegistrations(FieldTestResource.class);
8484 }
113113 };
114114 final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
115115 processor.processInjector(Guice.createInjector(module));
116 final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
116 final TestResource resource = TestPortProvider.createProxy(TestResource.class);
117117 Assert.assertEquals("constructor", resource.getName());
118118 dispatcher.getRegistry().removeRegistrations(ConstructorTestResource.class);
119119 }
5454 };
5555 final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
5656 processor.processInjector(Guice.createInjector(module));
57 final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
57 final TestResource resource = TestPortProvider.createProxy(TestResource.class);
5858 Assert.assertEquals("exception", resource.getName());
5959 dispatcher.getRegistry().removeRegistrations(TestResource.class);
6060 }
8989 }
9090 }
9191 }
92
5151 };
5252 final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
5353 processor.processInjector(Guice.createInjector(module));
54 final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
54 final TestResource resource = TestPortProvider.createProxy(TestResource.class);
5555 Assert.assertEquals("name", resource.getName());
5656 dispatcher.getRegistry().removeRegistrations(TestResource.class);
5757 }
7070 };
7171 final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
7272 processor.processInjector(Guice.createInjector(module));
73 final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
73 final TestResource resource = TestPortProvider.createProxy(TestResource.class);
7474 Assert.assertEquals("injected-name", resource.getName());
7575 dispatcher.getRegistry().removeRegistrations(TestResource.class);
7676 }
108108 }
109109 }
110110 }
111
5757 };
5858 final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
5959 processor.processInjector(Guice.createInjector(module, new JaxrsModule()));
60 final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
60 final TestResource resource = TestPortProvider.createProxy(TestResource.class);
6161 Assert.assertEquals("ok", resource.getName());
6262 dispatcher.getRegistry().removeRegistrations(TestResource.class);
6363 }
9999 }
100100 }
101101 }
102
6060 };
6161 final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
6262 processor.processInjector(Guice.createInjector(module, new RequestScopeModule()));
63 final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
63 final TestResource resource = TestPortProvider.createProxy(TestResource.class);
6464 Assert.assertEquals("ok", resource.getName());
6565 dispatcher.getRegistry().removeRegistrations(TestResource.class);
6666 }
113113 scoped.toString(); // Fails on this line without fix.
114114 }
115115 }
116
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-jaxrs</artifactId>
1010 <name>RESTEasy JAX-RS Implementation</name>
1111 <description/>
1212 <packaging>jar</packaging>
13
13
1414 <properties>
1515 <version.xerces.xercesImpl>2.9.1</version.xerces.xercesImpl>
1616 </properties>
17
17
1818 <dependencies>
1919 <dependency>
2020 <groupId>org.jboss.spec.javax.ws.rs</groupId>
21 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
21 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
2222 </dependency>
2323
2424 <dependency>
2727 </dependency>
2828
2929 <dependency>
30 <groupId>org.jboss.resteasy</groupId>
31 <artifactId>resteasy-jaxrs-services</artifactId>
32 <version>${project.version}</version>
30 <groupId>org.reactivestreams</groupId>
31 <artifactId>reactive-streams</artifactId>
32 </dependency>
33
34 <dependency>
35 <groupId>javax.validation</groupId>
36 <artifactId>validation-api</artifactId>
3337 </dependency>
3438
3539 <dependency>
7074 <groupId>org.apache.httpcomponents</groupId>
7175 <artifactId>httpclient</artifactId>
7276 </dependency>
73
77
7478 <dependency>
7579 <groupId>commons-io</groupId>
7680 <artifactId>commons-io</artifactId>
101105 <artifactId>javax.el</artifactId>
102106 <scope>test</scope>
103107 </dependency>
104
108 <dependency>
109 <groupId>javax.json.bind</groupId>
110 <artifactId>javax.json.bind-api</artifactId>
111 </dependency>
105112 <dependency>
106113 <groupId>org.jboss.logging</groupId>
107114 <artifactId>jboss-logging</artifactId>
113120 <dependency>
114121 <groupId>org.jboss.logging</groupId>
115122 <artifactId>jboss-logging-processor</artifactId>
123 </dependency>
124
125 <dependency>
126 <groupId>org.eclipse.microprofile.rest.client</groupId>
127 <artifactId>microprofile-rest-client-api</artifactId>
128 </dependency>
129
130 <dependency>
131 <groupId>org.eclipse.microprofile.config</groupId>
132 <artifactId>microprofile-config-api</artifactId>
116133 </dependency>
117134 </dependencies>
118135
120137 <plugins>
121138 <plugin>
122139 <groupId>com.atlassian.maven.plugins</groupId>
123 <artifactId>maven-clover2-plugin</artifactId>
140 <artifactId>clover-maven-plugin</artifactId>
124141 </plugin>
125142 </plugins>
126143 </build>
127144 <profiles>
145 <profile>
146 <id>jaxrs20</id>
147 <activation>
148 <property>
149 <name>jaxrs20</name>
150 </property>
151 </activation>
152 <dependencies>
153 <dependency>
154 <groupId>org.jboss.spec.javax.ws.rs</groupId>
155 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
156 </dependency>
157 </dependencies>
158 <build>
159 <directory>target/jaxrs20</directory>
160 <plugins>
161 <plugin>
162 <groupId>org.codehaus.mojo</groupId>
163 <artifactId>build-helper-maven-plugin</artifactId>
164 <version>3.0.0</version>
165 <executions>
166 <execution>
167 <id>add-jaxrs20-resources</id>
168 <phase>generate-resources</phase>
169 <goals>
170 <goal>add-resource</goal>
171 </goals>
172 <inherited>false</inherited>
173 <configuration>
174 <resources>
175 <resource>
176 <directory>${basedir}/src/main/resources-jaxrs20/</directory>
177 <excludes>
178 <exclude>**/junk/**</exclude>
179 </excludes>
180 </resource>
181 </resources>
182 </configuration>
183 </execution>
184 </executions>
185 </plugin>
186 <plugin>
187 <groupId>org.apache.maven.plugins</groupId>
188 <artifactId>maven-jar-plugin</artifactId>
189 <configuration>
190 <classifier>jaxrs20</classifier>
191 </configuration>
192 </plugin>
193 <plugin>
194 <groupId>org.apache.maven.plugins</groupId>
195 <artifactId>maven-source-plugin</artifactId>
196 <configuration>
197 <classifier>jaxrs20-sources</classifier>
198 </configuration>
199 </plugin>
200 </plugins>
201 </build>
202 </profile>
203 <profile>
204 <id>jaxrs21</id>
205 <activation>
206 <property>
207 <name>!jaxrs20</name>
208 </property>
209 </activation>
210 <dependencies>
211 <dependency>
212 <groupId>org.jboss.spec.javax.ws.rs</groupId>
213 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
214 </dependency>
215 </dependencies>
216 <build>
217 <plugins>
218 <plugin>
219 <groupId>org.codehaus.mojo</groupId>
220 <artifactId>build-helper-maven-plugin</artifactId>
221 <version>3.0.0</version>
222 <executions>
223 <execution>
224 <id>add-jaxrs21-resources</id>
225 <phase>generate-resources</phase>
226 <goals>
227 <goal>add-resource</goal>
228 </goals>
229 <inherited>false</inherited>
230 <configuration>
231 <resources>
232 <resource>
233 <directory>${basedir}/src/main/resources-jaxrs21/</directory>
234 <excludes>
235 <exclude>**/junk/**</exclude>
236 </excludes>
237 </resource>
238 </resources>
239 </configuration>
240 </execution>
241 </executions>
242 </plugin>
243 </plugins>
244 </build>
245 </profile>
128246 <profile>
129247 <!-- exclude integrations tests which are known to fail -->
130248 <id>exclude-known-tests-failures</id>
222340 </build>
223341 </profile>
224342 </profiles>
225
343
226344 </project>
0 package org.jboss.resteasy.annotations;
1
2 import org.jboss.resteasy.client.EntityTypeFactory;
3 import org.jboss.resteasy.client.core.VoidEntityTypeFactory;
4
5 import java.lang.annotation.ElementType;
6 import java.lang.annotation.Retention;
7 import java.lang.annotation.RetentionPolicy;
8 import java.lang.annotation.Target;
9
10 /**
11 * This is an annotation that you can add to a RESTEasy client interface that
12 * has a return type of Response.
13 * <p/>
14 * <p/>
15 * You have two options:
16 * <ol>
17 * <li>use the entityType property to set a Class that will always be returned
18 * <li>use the entityTypeFactory to determine which Class to use based on a
19 * factory that determines which class to use based on logic that uses the
20 * headers and status of the result.
21 * </ol>
22 * <p/>
23 * Note: if you want to use generic types, you can't use this annotation. You'll
24 * have to either use ClientResponse as part of your interface, or cast the
25 * resulting Response object as a ClientResponse.
26 *
27 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
28 * @version $Revision: 1 $
29 */
30
31 @Target({ElementType.METHOD})
32 @Retention(RetentionPolicy.RUNTIME)
33 @SuppressWarnings("unchecked")
34 @Deprecated
35 public @interface ClientResponseType
36 {
37 Class entityType() default Void.class;
38
39 Class<? extends EntityTypeFactory> entityTypeFactory() default VoidEntityTypeFactory.class;
40 }
+0
-24
resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/ClientURI.java less more
0 package org.jboss.resteasy.annotations;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Used to annotate a predefined URL (as opposed to a @PAthParam /@QueryParam)
9 * in a Proxied client.<br>
10 * <p/>
11 * For Example:
12 * <p/>
13 *
14 * @author <a href="mailto:sduskis@gmail.com">Solomon</a>
15 * @version $Revision: 1 $
16 * @GET MyDTO getDTO(@ClientURI String uri);
17 */
18 @Target({ElementType.PARAMETER})
19 @Retention(RetentionPolicy.RUNTIME)
20 public @interface ClientURI
21 {
22
23 }
99 *
1010 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
1111 * @version $Revision: 1 $
12 * @see org.jboss.resteasy.spi.DecoratorProcessor
12 * @see org.jboss.resteasy.spi.interception.DecoratorProcessor
1313 * @see org.jboss.resteasy.annotations.Decorator
1414 */
1515 @Target({ElementType.TYPE})
00 package org.jboss.resteasy.annotations;
11
2 import org.jboss.resteasy.spi.DecoratorProcessor;
2 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
33
44 import java.lang.annotation.ElementType;
55 import java.lang.annotation.Retention;
1111 *
1212 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
1313 * @version $Revision: 1 $
14 * @see org.jboss.resteasy.spi.DecoratorProcessor
14 * @see org.jboss.resteasy.spi.interception.DecoratorProcessor
1515 * @see org.jboss.resteasy.annotations.DecorateTypes
1616 */
1717 @Target({ElementType.ANNOTATION_TYPE})
0 package org.jboss.resteasy.annotations;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Use on async streams to push them to the client as they become available
9 * over the OutputStream, rather than collected into collections.
10 */
11 @Target({ElementType.TYPE, ElementType.METHOD})
12 @Retention(RetentionPolicy.RUNTIME)
13 public @interface Stream
14 {
15 }
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Identifies an interceptor as a client-side interceptor
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 @Target({ElementType.TYPE})
14 @Retention(RetentionPolicy.RUNTIME)
15 public @interface ClientInterceptor
16 {
17 }
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * This interceptor is an Content-Encoding decoder. It is used with MessageBodyWriter interceptors.
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 @Target({ElementType.TYPE})
14 @Retention(RetentionPolicy.RUNTIME)
15 @Precedence("DECODER")
16 public @interface DecoderPrecedence
17 {
18 public static final String PRECEDENCE_STRING = "DECODER";
19 }
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * This interceptor is an Content-Encoding encoder. It is used with MessageBodyWriter interceptors.
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 @Target({ElementType.TYPE})
14 @Retention(RetentionPolicy.RUNTIME)
15 @Precedence("ENCODER")
16 public @interface EncoderPrecedence
17 {
18 public static final String PRECEDENCE_STRING = "ENCODER";
19 }
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * HeaderDecoratorPrecedence interceptors should always come first as they decorate a response (on the server), or an
9 * outgoing request (on the client) with special, user-defined, headers. These headers may trigger behavior in other interceptors.
10 *
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @version $Revision: 1 $
13 */
14 @Target({ElementType.TYPE})
15 @Retention(RetentionPolicy.RUNTIME)
16 @Precedence("HEADER_DECORATOR")
17 public @interface HeaderDecoratorPrecedence
18 {
19 public static final String PRECEDENCE_STRING = "HEADER_DECORATOR";
20 }
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 */
11 @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
12 @Retention(RetentionPolicy.RUNTIME)
13 public @interface Precedence
14 {
15 String value();
16 }
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Should be placed on a PreProcessInterceptor.
9 * This annotation specifies ordering of interceptors.
10 * Will run after SecurityPrecedence. These types of interceptors may redirect the request.
11 *
12 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
13 * @version $Revision: 1 $
14 */
15 @Target({ElementType.TYPE, ElementType.METHOD})
16 @Retention(RetentionPolicy.RUNTIME)
17 @Precedence("REDIRECT")
18 public @interface RedirectPrecedence
19 {
20 public static final String PRECEDENCE_STRING = "REDIRECT";
21 }
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Should be placed on a PreProcessInterceptor.
9 * This annotation specifies ordering of interceptors.
10 * Security-based interceptors should always come first. They may look at headers, but they don't read the input
11 * stream.
12 *
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 */
16 @Target({ElementType.TYPE})
17 @Retention(RetentionPolicy.RUNTIME)
18 @Precedence("SECURITY")
19 public @interface SecurityPrecedence
20 {
21 public static final String PRECEDENCE_STRING = "SECURITY";
22 }
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Identifies an interceptor as a server-side interceptor
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 @Target({ElementType.TYPE})
14 @Retention(RetentionPolicy.RUNTIME)
15 public @interface ServerInterceptor
16 {
17 }
0 package org.jboss.resteasy.api.validation;
1
2 import java.io.BufferedReader;
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
7 import java.io.Serializable;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.Set;
14
15 import javax.validation.ConstraintViolation;
16 import javax.validation.ConstraintViolationException;
17 import javax.ws.rs.core.MediaType;
18
19 import org.jboss.resteasy.api.validation.ConstraintType.Type;
20 import org.jboss.resteasy.plugins.providers.validation.ConstraintTypeUtil11;
21 import org.jboss.resteasy.plugins.providers.validation.ViolationsContainer;
22 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
23 import org.jboss.resteasy.spi.ResteasyConfiguration;
24 import org.jboss.resteasy.spi.ResteasyProviderFactory;
25
26 /**
27 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
28 * @version $Revision: 1.1 $
29 *
30 * Copyright Mar 6, 2012
31 *
32 * @TODO Need to work on representation of exceptions
33 * @TODO Add javadoc.
34 */
35 public class ResteasyViolationException extends ConstraintViolationException
36 {
37 private static final long serialVersionUID = 2623733139912277260L;
38 public static final String SUPPRESS_VIOLATION_PATH = "resteasy.validation.suppress.path";
39
40 private List<CloneableMediaType> accept;
41 private Exception exception;
42
43 private List<ResteasyConstraintViolation> fieldViolations;
44 private List<ResteasyConstraintViolation> propertyViolations;
45 private List<ResteasyConstraintViolation> classViolations;
46 private List<ResteasyConstraintViolation> parameterViolations;
47 private List<ResteasyConstraintViolation> returnValueViolations;
48
49 private List<ResteasyConstraintViolation> allViolations;
50 private List<List<ResteasyConstraintViolation>> violationLists;
51
52 transient private ConstraintTypeUtil11 util = new ConstraintTypeUtil11();
53 private boolean suppressPath;
54
55 /**
56 * New constructor
57 * @param constraintViolations
58 */
59 public ResteasyViolationException(Set<? extends ConstraintViolation<?>> constraintViolations)
60 {
61 super(constraintViolations);
62 checkSuppressPath();
63 accept = new ArrayList<CloneableMediaType>();
64 accept.add(CloneableMediaType.TEXT_PLAIN_TYPE);
65 }
66
67 /**
68 * New constructor
69 *
70 * @param constraintViolations
71 * @param accept
72 */
73 public ResteasyViolationException(Set<? extends ConstraintViolation<?>> constraintViolations, List<MediaType> accept)
74 {
75 super(constraintViolations);
76 checkSuppressPath();
77 this.accept = toCloneableMediaTypeList(accept);
78 }
79
80 /**
81 * New constructor
82 *
83 * @param container
84 */
85 public ResteasyViolationException(SimpleViolationsContainer container)
86 {
87 this(container.getViolations());
88 setException(container.getException());
89 }
90
91 /**
92 * New constructor
93 *
94 * @param container
95 * @param accept
96 */
97
98 public ResteasyViolationException(SimpleViolationsContainer container, List<MediaType> accept)
99 {
100 this(container.getViolations(), accept);
101 setException(container.getException());
102 }
103
104 public ResteasyViolationException(ViolationsContainer<?> container)
105 {
106 super(null);
107 convertToStrings(container);
108 setException(container.getException());
109 accept = new ArrayList<CloneableMediaType>();
110 accept.add(CloneableMediaType.TEXT_PLAIN_TYPE);
111 }
112
113 public ResteasyViolationException(ViolationsContainer<?> container, List<MediaType> accept)
114 {
115 super(null);
116 convertToStrings(container);
117 setException(container.getException());
118 this.accept = toCloneableMediaTypeList(accept);
119 }
120
121 public ResteasyViolationException(String stringRep)
122 {
123 super(null);
124 checkSuppressPath();
125 convertFromString(stringRep);
126 }
127
128 public List<MediaType> getAccept()
129 {
130 return toMediaTypeList(accept);
131 }
132
133 public void setAccept(List<MediaType> accept)
134 {
135 this.accept = toCloneableMediaTypeList(accept);
136 }
137
138 public Exception getException()
139 {
140 return exception;
141 }
142
143 public void setException(Exception exception)
144 {
145 this.exception = exception;
146 initCause(exception);
147 }
148
149 public List<ResteasyConstraintViolation> getViolations()
150 {
151 convertViolations();
152 if (allViolations == null)
153 {
154 allViolations = new ArrayList<ResteasyConstraintViolation>();
155 allViolations.addAll(fieldViolations);
156 allViolations.addAll(propertyViolations);
157 allViolations.addAll(classViolations);
158 allViolations.addAll(parameterViolations);
159 allViolations.addAll(returnValueViolations);
160 }
161 return allViolations;
162 }
163
164 public List<ResteasyConstraintViolation> getFieldViolations()
165 {
166 convertViolations();
167 return fieldViolations;
168 }
169
170 public List<ResteasyConstraintViolation> getPropertyViolations()
171 {
172 convertViolations();
173 return propertyViolations;
174 }
175
176 public List<ResteasyConstraintViolation> getClassViolations()
177 {
178 convertViolations();
179 return classViolations;
180 }
181
182 public List<ResteasyConstraintViolation> getParameterViolations()
183 {
184 convertViolations();
185 return parameterViolations;
186 }
187
188 public List<ResteasyConstraintViolation> getReturnValueViolations()
189 {
190 convertViolations();
191 return returnValueViolations;
192 }
193
194 public int size()
195 {
196 return getViolations().size();
197 }
198
199 public List<List<ResteasyConstraintViolation>> getViolationLists()
200 {
201 convertViolations();
202 return violationLists;
203 }
204
205 public String toString()
206 {
207 convertViolations();
208 StringBuffer sb = new StringBuffer();
209 for (Iterator<List<ResteasyConstraintViolation>> it = violationLists.iterator(); it.hasNext(); )
210 {
211 List<ResteasyConstraintViolation> violations = it.next();
212 for (Iterator<ResteasyConstraintViolation> it2 = violations.iterator(); it2.hasNext(); )
213 {
214 sb.append(it2.next().toString()).append('\r');
215 }
216 }
217 return sb.toString();
218 }
219
220 protected void convertToStrings(ViolationsContainer<?> container)
221 {
222 if (violationLists != null)
223 {
224 return;
225 }
226 violationLists = new ArrayList<List<ResteasyConstraintViolation>>();
227 fieldViolations = container.getFieldViolations();
228 propertyViolations = container.getPropertyViolations();
229 classViolations = container.getClassViolations();
230 parameterViolations = container.getParameterViolations();
231 returnValueViolations = container.getReturnValueViolations();
232
233 violationLists.add(fieldViolations);
234 violationLists.add(propertyViolations);
235 violationLists.add(classViolations);
236 violationLists.add(parameterViolations);
237 violationLists.add(returnValueViolations);
238 }
239
240 protected void convertFromString(String stringRep)
241 {
242 convertViolations();
243 InputStream is = new ByteArrayInputStream(stringRep.getBytes());
244 BufferedReader br = new BufferedReader(new InputStreamReader(is));
245 String line;
246 try
247 {
248 line = br.readLine();
249 while (line != null )
250 {
251 ConstraintType.Type type = ConstraintType.Type.valueOf(line.substring(1, line.length() - 1));
252 line = br.readLine();
253 String path = line.substring(1, line.length() - 1);
254 line = br.readLine();
255 String message = line.substring(1, line.length() - 1);
256 line = br.readLine();
257 String value = line.substring(1, line.length() - 1);
258 ResteasyConstraintViolation rcv = new ResteasyConstraintViolation(type, path, message, value);
259
260 switch (type)
261 {
262 case FIELD:
263 fieldViolations.add(rcv);
264 break;
265
266 case PROPERTY:
267 propertyViolations.add(rcv);
268 break;
269
270 case CLASS:
271 classViolations.add(rcv);
272 break;
273
274 case PARAMETER:
275 parameterViolations.add(rcv);
276 break;
277
278 case RETURN_VALUE:
279 returnValueViolations.add(rcv);
280 break;
281
282 default:
283 throw new RuntimeException(Messages.MESSAGES.unexpectedViolationType(type));
284 }
285 line = br.readLine(); // consume ending '\r'
286 line = br.readLine();
287 }
288 }
289 catch (IOException e)
290 {
291 throw new RuntimeException(Messages.MESSAGES.unableToParseException());
292 }
293
294 violationLists = new ArrayList<List<ResteasyConstraintViolation>>();
295 violationLists.add(fieldViolations);
296 violationLists.add(propertyViolations);
297 violationLists.add(classViolations);
298 violationLists.add(parameterViolations);
299 violationLists.add(returnValueViolations);
300 }
301
302 protected int getField(int start, String line)
303 {
304 int beginning = line.indexOf('[', start);
305 if (beginning == -1)
306 {
307 throw new RuntimeException(Messages.MESSAGES.exceptionHasInvalidFormat(line));
308 }
309 int index = beginning;
310 int bracketCount = 1;
311 while (++index < line.length())
312 {
313 char c = line.charAt(index);
314 if (c == '[')
315 {
316 bracketCount++;
317 }
318 else if (c == ']')
319 {
320 bracketCount--;
321 }
322 if (bracketCount == 0)
323 {
324 break;
325 }
326 }
327 if (bracketCount != 0)
328 {
329 throw new RuntimeException(Messages.MESSAGES.exceptionHasInvalidFormat(line));
330 }
331 return index;
332 }
333
334 protected void checkSuppressPath()
335 {
336 ResteasyConfiguration context = ResteasyProviderFactory.getContextData(ResteasyConfiguration.class);
337 if (context != null)
338 {
339 String s = context.getParameter(SUPPRESS_VIOLATION_PATH);
340 if (s != null)
341 {
342 suppressPath = Boolean.parseBoolean(s);
343 }
344 }
345 }
346
347 protected void convertViolations()
348 {
349 if (violationLists != null)
350 {
351 return;
352 }
353
354 fieldViolations = new ArrayList<ResteasyConstraintViolation>();
355 propertyViolations = new ArrayList<ResteasyConstraintViolation>();
356 classViolations = new ArrayList<ResteasyConstraintViolation>();
357 parameterViolations = new ArrayList<ResteasyConstraintViolation>();
358 returnValueViolations = new ArrayList<ResteasyConstraintViolation>();
359
360 if (getConstraintViolations() != null)
361 {
362 for (Iterator<ConstraintViolation<?>> it = getConstraintViolations().iterator(); it.hasNext(); )
363 {
364 ResteasyConstraintViolation rcv = convertViolation(it.next());
365 switch (rcv.getConstraintType())
366 {
367 case FIELD:
368 fieldViolations.add(rcv);
369 break;
370
371 case PROPERTY:
372 propertyViolations.add(rcv);
373 break;
374
375 case CLASS:
376 classViolations.add(rcv);
377 break;
378
379 case PARAMETER:
380 parameterViolations.add(rcv);
381 break;
382
383 case RETURN_VALUE:
384 returnValueViolations.add(rcv);
385 break;
386
387 default:
388 throw new RuntimeException(Messages.MESSAGES.unexpectedViolationType(rcv.getConstraintType()));
389 }
390 }
391 }
392
393 violationLists = new ArrayList<List<ResteasyConstraintViolation>>();
394 violationLists.add(fieldViolations);
395 violationLists.add(propertyViolations);
396 violationLists.add(classViolations);
397 violationLists.add(parameterViolations);
398 violationLists.add(returnValueViolations);
399 }
400
401 protected ResteasyConstraintViolation convertViolation(ConstraintViolation<?> violation)
402 {
403 Type ct = util.getConstraintType(violation);
404 String path = (suppressPath ? "*" : violation.getPropertyPath().toString());
405 return new ResteasyConstraintViolation(ct, path, violation.getMessage(), convertArrayToString(violation.getInvalidValue()));
406 }
407
408 static protected String convertArrayToString(Object o)
409 {
410 String result = null;
411 if (o instanceof Object[])
412 {
413 Object[] array = Object[].class.cast(o);
414 StringBuffer sb = new StringBuffer("[").append(convertArrayToString(array[0]));
415 for (int i = 1; i < array.length; i++)
416 {
417 sb.append(", ").append(convertArrayToString(array[i]));
418 }
419 sb.append("]");
420 result = sb.toString();
421 }
422 else
423 {
424 result = (o == null ? "" : o.toString());
425 }
426 return result;
427 }
428
429 /**
430 * It seems that EJB3 wants to clone ResteasyViolationException,
431 * and MediaType is not serializable.
432 *
433 */
434 static class CloneableMediaType implements Serializable
435 {
436 public static final CloneableMediaType TEXT_PLAIN_TYPE = new CloneableMediaType("plain", "text");
437 private static final long serialVersionUID = 9179565449557464429L;
438 private String type;
439 private String subtype;
440 private Map<String, String> parameters;
441
442 public CloneableMediaType(MediaType mediaType)
443 {
444 type = mediaType.getType();
445 subtype = mediaType.getSubtype();
446 parameters = new HashMap<String, String>(mediaType.getParameters());
447 }
448
449 public CloneableMediaType(String type, String subtype)
450 {
451 this.type = type;
452 this.subtype = subtype;
453 }
454
455 public MediaType toMediaType()
456 {
457 return new MediaType(type, subtype, parameters);
458 }
459 }
460
461 static protected List<CloneableMediaType> toCloneableMediaTypeList(List<MediaType> list)
462 {
463 List<CloneableMediaType> cloneableList = new ArrayList<CloneableMediaType>();
464 for (Iterator<MediaType> it = list.iterator(); it.hasNext(); )
465 {
466 cloneableList.add(new CloneableMediaType(it.next()));
467 }
468 return cloneableList;
469 }
470
471 static protected List<MediaType> toMediaTypeList(List<CloneableMediaType> cloneableList)
472 {
473 List<MediaType> list = new ArrayList<MediaType>();
474 for (Iterator<CloneableMediaType> it = cloneableList.iterator(); it.hasNext(); )
475 {
476 CloneableMediaType cmt = it.next();
477 list.add(new MediaType(cmt.type, cmt.subtype, cmt.parameters));
478 }
479 return list;
480 }
481 }
0 package org.jboss.resteasy.api.validation;
1
2 import java.util.Iterator;
3 import java.util.List;
4
5 import javax.validation.ConstraintDeclarationException;
6 import javax.validation.ConstraintDefinitionException;
7 import javax.validation.GroupDefinitionException;
8 import javax.validation.ValidationException;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.Response;
11 import javax.ws.rs.core.Response.ResponseBuilder;
12 import javax.ws.rs.core.Response.Status;
13 import javax.ws.rs.ext.ExceptionMapper;
14 import javax.ws.rs.ext.Provider;
15
16
17 /**
18 *
19 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
20 * @version $Revision: 1.1 $
21 *
22 * Created Mar 31, 2012
23 */
24 @Provider
25 public class ResteasyViolationExceptionMapper implements ExceptionMapper<ValidationException>
26 {
27 public Response toResponse(ValidationException exception)
28 {
29 if (exception instanceof ConstraintDefinitionException)
30 {
31 return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
32 }
33 if (exception instanceof ConstraintDeclarationException)
34 {
35 return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
36 }
37 if (exception instanceof GroupDefinitionException)
38 {
39 return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
40 }
41 if (exception instanceof ResteasyViolationException)
42 {
43 ResteasyViolationException resteasyViolationException = ResteasyViolationException.class.cast(exception);
44 Exception e = resteasyViolationException.getException();
45 if (e != null)
46 {
47 return buildResponse(unwrapException(e), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
48 }
49 else if (resteasyViolationException.getReturnValueViolations().size() == 0)
50 {
51 return buildViolationReportResponse(resteasyViolationException, Status.BAD_REQUEST);
52 }
53 else
54 {
55 return buildViolationReportResponse(resteasyViolationException, Status.INTERNAL_SERVER_ERROR);
56 }
57 }
58 return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
59 }
60
61 protected Response buildResponse(Object entity, String mediaType, Status status)
62 {
63 ResponseBuilder builder = Response.status(status).entity(entity);
64 builder.type(MediaType.TEXT_PLAIN);
65 builder.header(Validation.VALIDATION_HEADER, "true");
66 return builder.build();
67 }
68
69 protected Response buildViolationReportResponse(ResteasyViolationException exception, Status status)
70 {
71 ResponseBuilder builder = Response.status(status);
72 builder.header(Validation.VALIDATION_HEADER, "true");
73
74 // Check standard media types.
75 MediaType mediaType = getAcceptMediaType(exception.getAccept());
76 if (mediaType != null)
77 {
78 builder.type(mediaType);
79 builder.entity(new ViolationReport(exception));
80 return builder.build();
81 }
82
83 // Default media type.
84 builder.type(MediaType.TEXT_PLAIN);
85 builder.entity(exception.toString());
86 return builder.build();
87 }
88
89
90 protected String unwrapException(Throwable t)
91 {
92 StringBuffer sb = new StringBuffer();
93 doUnwrapException(sb, t);
94 return sb.toString();
95 }
96
97 private void doUnwrapException(StringBuffer sb, Throwable t)
98 {
99 if (t == null)
100 {
101 return;
102 }
103 sb.append(t.toString());
104 if (t.getCause() != null && t != t.getCause())
105 {
106 sb.append('[');
107 doUnwrapException(sb, t.getCause());
108 sb.append(']');
109 }
110 }
111
112 private MediaType getAcceptMediaType (List<MediaType> accept)
113 {
114 Iterator<MediaType> it = accept.iterator();
115 while (it.hasNext())
116 {
117 MediaType mt = it.next();
118 if (MediaType.APPLICATION_XML_TYPE.getType().equals(mt.getType()) && MediaType.APPLICATION_XML_TYPE.getSubtype().equals(mt.getSubtype()))
119 {
120 return MediaType.APPLICATION_XML_TYPE;
121 }
122 if (MediaType.APPLICATION_JSON_TYPE.getType().equals(mt.getType()) && MediaType.APPLICATION_JSON_TYPE.getSubtype().equals(mt.getSubtype()))
123 {
124 return MediaType.APPLICATION_JSON_TYPE;
125 }
126 }
127 return null;
128 }
129 }
0 package org.jboss.resteasy.api.validation;
1
2 import java.io.Serializable;
3 import java.util.HashSet;
4 import java.util.Set;
5
6 import javax.validation.ConstraintViolation;
7
8 public class SimpleViolationsContainer implements Serializable
9 {
10 private static final long serialVersionUID = -7895854137980651540L;
11
12 private Set<ConstraintViolation<Object>> violations = new HashSet<ConstraintViolation<Object>>();
13 private Exception exception;
14 private Object target;
15 private boolean fieldsValidated;
16
17 public SimpleViolationsContainer(Object target)
18 {
19 this.target = target;
20 }
21
22 public SimpleViolationsContainer(Set<ConstraintViolation<Object>> cvs)
23 {
24 violations.addAll(cvs);
25 }
26
27 public void addViolations(Set<ConstraintViolation<Object>> cvs)
28 {
29 violations.addAll(cvs);
30 }
31
32 public int size()
33 {
34 return violations.size();
35 }
36
37 public Exception getException()
38 {
39 return exception;
40 }
41
42 public void setException(Exception exception)
43 {
44 this.exception = exception;
45 }
46
47 public Object getTarget()
48 {
49 return target;
50 }
51
52 public void setTarget(Object target)
53 {
54 this.target = target;
55 }
56
57 public Set<ConstraintViolation<Object>> getViolations()
58 {
59 return violations;
60 }
61
62 public boolean isFieldsValidated()
63 {
64 return fieldsValidated;
65 }
66
67 public void setFieldsValidated(boolean fieldsValidated)
68 {
69 this.fieldsValidated = fieldsValidated;
70 }
71 }
0 package org.jboss.resteasy.api.validation;
1
2 import java.util.ArrayList;
3
4 import javax.xml.bind.annotation.XmlAccessType;
5 import javax.xml.bind.annotation.XmlAccessorType;
6 import javax.xml.bind.annotation.XmlRootElement;
7
8 /**
9 *
10 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
11 * @version $Revision: 1.1 $
12 *
13 * Copyright July 27, 2013
14 */
15 @XmlRootElement(name="violationReport")
16 @XmlAccessorType(XmlAccessType.FIELD)
17 public class ViolationReport
18 {
19 private String exception;
20
21 private ArrayList<ResteasyConstraintViolation> fieldViolations = new ArrayList<ResteasyConstraintViolation>();
22 private ArrayList<ResteasyConstraintViolation> propertyViolations = new ArrayList<ResteasyConstraintViolation>();
23 private ArrayList<ResteasyConstraintViolation> classViolations = new ArrayList<ResteasyConstraintViolation>();
24 private ArrayList<ResteasyConstraintViolation> parameterViolations = new ArrayList<ResteasyConstraintViolation>();
25 private ArrayList<ResteasyConstraintViolation> returnValueViolations = new ArrayList<ResteasyConstraintViolation>();
26
27 public ViolationReport(ResteasyViolationException exception)
28 {
29 Exception e = exception.getException();
30 if (e != null)
31 {
32 this.exception = e.toString();
33 }
34 this.fieldViolations = (ArrayList<ResteasyConstraintViolation>) exception.getFieldViolations();
35 this.propertyViolations = (ArrayList<ResteasyConstraintViolation>) exception.getPropertyViolations();
36 this.classViolations = (ArrayList<ResteasyConstraintViolation>) exception.getClassViolations();
37 this.parameterViolations = (ArrayList<ResteasyConstraintViolation>) exception.getParameterViolations();
38 this.returnValueViolations = (ArrayList<ResteasyConstraintViolation>) exception.getReturnValueViolations();
39 }
40
41 public ViolationReport(String s)
42 {
43 this(new ResteasyViolationException(s));
44 }
45
46 public ViolationReport()
47 {
48 }
49
50 public String getException()
51 {
52 return exception;
53 }
54
55 public ArrayList<ResteasyConstraintViolation> getFieldViolations()
56 {
57 return fieldViolations;
58 }
59
60 public ArrayList<ResteasyConstraintViolation> getPropertyViolations()
61 {
62 return propertyViolations;
63 }
64
65 public ArrayList<ResteasyConstraintViolation> getClassViolations()
66 {
67 return classViolations;
68 }
69
70 public ArrayList<ResteasyConstraintViolation> getParameterViolations()
71 {
72 return parameterViolations;
73 }
74
75 public ArrayList<ResteasyConstraintViolation> getReturnValueViolations()
76 {
77 return returnValueViolations;
78 }
79
80 public void setException(String exception)
81 {
82 this.exception = exception;
83 }
84
85 public void setFieldViolations(ArrayList<ResteasyConstraintViolation> fieldViolations)
86 {
87 this.fieldViolations = fieldViolations;
88 }
89
90 public void setPropertyViolations(ArrayList<ResteasyConstraintViolation> propertyViolations)
91 {
92 this.propertyViolations = propertyViolations;
93 }
94
95 public void setClassViolations(ArrayList<ResteasyConstraintViolation> classViolations)
96 {
97 this.classViolations = classViolations;
98 }
99
100 public void setParameterViolations(ArrayList<ResteasyConstraintViolation> parameterViolations)
101 {
102 this.parameterViolations = parameterViolations;
103 }
104
105 public void setReturnValueViolations(ArrayList<ResteasyConstraintViolation> returnValueViolations)
106 {
107 this.returnValueViolations = returnValueViolations;
108 }
109 }
0 package org.jboss.resteasy.client;
1
2 import javax.ws.rs.core.UriBuilder;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
8 *
9 * @see org.jboss.resteasy.client.jaxrs.ClientHttpEngine
10 */
11 @Deprecated
12 public interface ClientExecutor
13 {
14 ClientRequest createRequest(String uriTemplate);
15
16 ClientRequest createRequest(UriBuilder uriBuilder);
17
18 ClientResponse execute(ClientRequest request) throws Exception;
19
20 void close() throws Exception;
21 }
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.BaseClientResponse;
3 import org.jboss.resteasy.client.core.ClientInterceptorRepositoryImpl;
4 import org.jboss.resteasy.core.interception.ClientExecutionContextImpl;
5 import org.jboss.resteasy.core.interception.ClientWriterInterceptorContext;
6 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
7 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
8 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
9 import org.jboss.resteasy.spi.Link;
10 import org.jboss.resteasy.spi.LinkHeader;
11 import org.jboss.resteasy.spi.ProviderFactoryDelegate;
12 import org.jboss.resteasy.spi.ResteasyProviderFactory;
13 import org.jboss.resteasy.spi.StringConverter;
14 import org.jboss.resteasy.util.Encode;
15 import org.jboss.resteasy.util.GenericType;
16
17 import javax.ws.rs.core.Cookie;
18 import javax.ws.rs.core.HttpHeaders;
19 import javax.ws.rs.core.MediaType;
20 import javax.ws.rs.core.MultivaluedMap;
21 import javax.ws.rs.core.UriBuilder;
22 import javax.ws.rs.ext.MessageBodyWriter;
23 import javax.ws.rs.ext.Providers;
24 import javax.ws.rs.ext.RuntimeDelegate;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.lang.annotation.Annotation;
29 import java.lang.reflect.Type;
30 import java.net.URI;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35
36 import static org.jboss.resteasy.util.HttpHeaderNames.ACCEPT;
37
38 /**
39 * Create a hand coded request to send to the server. You call methods like accept(), body(), pathParameter()
40 * etc. to create the state of the request. Then you call a get(), post(), etc. method to execute the request.
41 * After an execution of a request, the internal state remains the same. You can invoke the request again.
42 * You can clear the request with the clear() method.
43 *
44 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
45 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
46 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
47 * @version $Revision: 1 $
48 *
49 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
50 * @see javax.ws.rs.client.Invocation
51 */
52 @Deprecated
53 @SuppressWarnings("unchecked")
54 public class ClientRequest extends ClientInterceptorRepositoryImpl implements Cloneable
55 {
56 protected ResteasyProviderFactory providerFactory;
57 protected ResteasyUriBuilder uri;
58 protected ClientExecutor executor;
59 protected MultivaluedMap<String, Object> headers;
60 protected MultivaluedMap<String, String> queryParameters;
61 protected MultivaluedMap<String, String> formParameters;
62 protected MultivaluedMap<String, String> pathParameters;
63 protected MultivaluedMap<String, String> matrixParameters;
64 protected Object body;
65 protected Class bodyType;
66 protected Type bodyGenericType;
67 protected Annotation[] bodyAnnotations;
68 protected MediaType bodyContentType;
69 protected boolean followRedirects;
70 protected String httpMethod;
71 protected String finalUri;
72 protected List<String> pathParameterList;
73 protected LinkHeader linkHeader;
74 protected Map<String, Object> attributes = new HashMap<String, Object>();
75
76 private static String defaultExecutorClasss = "org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor";
77
78 /**
79 * Set the default executor class name.
80 *
81 * @param classname
82 */
83 public static void setDefaultExecutorClass(String classname)
84 {
85 defaultExecutorClasss = classname;
86 }
87
88 public static ClientExecutor getDefaultExecutor()
89 {
90 try
91 {
92 Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(defaultExecutorClasss);
93 return (ClientExecutor) clazz.newInstance();
94 }
95 catch (Exception e)
96 {
97 throw new RuntimeException(e);
98 }
99 }
100
101 public ClientRequest(String uriTemplate)
102 {
103 this(uriTemplate, getDefaultExecutor());
104 }
105
106 public ClientRequest(String uriTemplate, ClientExecutor executor)
107 {
108 this(getBuilder(uriTemplate), executor);
109 }
110
111 public ClientRequest(UriBuilder uri, ClientExecutor executor)
112 {
113 this(uri, executor, ResteasyProviderFactory.getInstance());
114 }
115
116 public ClientRequest(UriBuilder uri, ClientExecutor executor,
117 ResteasyProviderFactory providerFactory)
118 {
119 this.uri = (ResteasyUriBuilder) uri;
120 this.executor = executor;
121 if (providerFactory instanceof ProviderFactoryDelegate)
122 {
123 this.providerFactory = ((ProviderFactoryDelegate) providerFactory)
124 .getDelegate();
125 }
126 else
127 {
128 this.providerFactory = providerFactory;
129 }
130 }
131
132 /**
133 * Clear this request's state so that it can be re-used
134 */
135 public void clear()
136 {
137 headers = null;
138 queryParameters = null;
139 formParameters = null;
140 pathParameters = null;
141 matrixParameters = null;
142 body = null;
143 bodyType = null;
144 bodyGenericType = null;
145 bodyAnnotations = null;
146 bodyContentType = null;
147 httpMethod = null;
148 finalUri = null;
149 pathParameterList = null;
150 linkHeader = null;
151
152 }
153
154
155 private static UriBuilder getBuilder(String uriTemplate)
156 {
157 return new ResteasyUriBuilder().uriTemplate(uriTemplate);
158 }
159
160 public boolean followRedirects()
161 {
162 return followRedirects;
163 }
164
165 public Map<String, Object> getAttributes()
166 {
167 return attributes;
168 }
169
170 public ClientRequest followRedirects(boolean followRedirects)
171 {
172 this.followRedirects = followRedirects;
173 return this;
174 }
175
176 public ClientRequest accept(MediaType accepts)
177 {
178 return header(ACCEPT, accepts.toString());
179 }
180
181 public ClientRequest accept(String accept)
182 {
183 String curr = (String) getHeadersAsObjects().getFirst(ACCEPT);
184 if (curr != null)
185 curr += "," + accept;
186 else
187 curr = accept;
188 getHeadersAsObjects().putSingle(ACCEPT, curr);
189 return this;
190 }
191
192 protected String toString(Object object)
193 {
194 if (object instanceof String)
195 return (String) object;
196 StringConverter converter = providerFactory.getStringConverter(object
197 .getClass());
198 if (converter != null)
199 return converter.toString(object);
200 else
201 return object.toString();
202
203 }
204
205 protected String toHeaderString(Object object)
206 {
207 return providerFactory.toHeaderString(object);
208
209 }
210
211 public ClientRequest addLink(Link link)
212 {
213 if (linkHeader == null)
214 {
215 linkHeader = new LinkHeader();
216 }
217 linkHeader.getLinks().add(link);
218 return this;
219 }
220
221 public ClientRequest addLink(String title, String rel, String href, String type)
222 {
223 Link link = new Link(title, rel, href, type, null);
224 return addLink(link);
225 }
226
227 public ClientRequest formParameter(String parameterName, Object value)
228 {
229 getFormParameters().add(parameterName, toString(value));
230 return this;
231 }
232
233 public ClientRequest queryParameter(String parameterName, Object value)
234 {
235 getQueryParameters().add(parameterName, toString(value));
236 return this;
237 }
238
239 public ClientRequest matrixParameter(String parameterName, Object value)
240 {
241 getMatrixParameters().add(parameterName, toString(value));
242 return this;
243 }
244
245 public ClientRequest header(String headerName, Object value)
246 {
247 getHeadersAsObjects().add(headerName, value);
248 return this;
249 }
250
251 public ClientRequest cookie(String cookieName, Object value)
252 {
253 return cookie(new Cookie(cookieName, toString(value)));
254 }
255
256 public ClientRequest cookie(Cookie cookie)
257 {
258 return header(HttpHeaders.COOKIE, cookie);
259 }
260
261 public ClientRequest pathParameter(String parameterName, Object value)
262 {
263 getPathParameters().add(parameterName, toString(value));
264 return this;
265 }
266
267 public ClientRequest pathParameters(Object... values)
268 {
269 for (Object value : values)
270 {
271 getPathParameterList().add(toString(value));
272 }
273 return this;
274 }
275
276 public ClientRequest body(String contentType, Object data)
277 {
278 return body(MediaType.valueOf(contentType), data, data.getClass(), null,
279 null);
280 }
281
282 public ClientRequest body(MediaType contentType, Object data)
283 {
284 return body(contentType, data, data.getClass(), null, null);
285 }
286
287 public ClientRequest body(MediaType contentType, Object data,
288 GenericType genericType)
289 {
290 return body(contentType, data, genericType.getType(), genericType
291 .getGenericType(), null);
292 }
293
294 public ClientRequest body(MediaType contentType, Object data,
295 Type genericType)
296 {
297 return body(contentType, data, data.getClass(), genericType, null);
298 }
299
300 public ClientRequest body(MediaType contentType, Object data, Class type,
301 Type genericType, Annotation[] annotations)
302 {
303 this.body = data;
304 this.bodyContentType = contentType;
305 this.bodyGenericType = genericType;
306 this.bodyType = type;
307 this.bodyAnnotations = annotations;
308 return this;
309 }
310
311 public ResteasyProviderFactory getProviderFactory()
312 {
313 return providerFactory;
314 }
315
316 public ClientExecutor getExecutor()
317 {
318 return executor;
319 }
320
321 /**
322 * @return a copy of all header objects converted to a string
323 */
324 public MultivaluedMap<String, String> getHeaders()
325 {
326 MultivaluedMap<String, String> rtn = new MultivaluedMapImpl<String, String>();
327 if (headers == null) return rtn;
328 for (Map.Entry<String, List<Object>> entry : headers.entrySet())
329 {
330 for (Object obj : entry.getValue())
331 {
332 rtn.add(entry.getKey(), toHeaderString(obj));
333 }
334 }
335 return rtn;
336 }
337
338 public MultivaluedMap<String, Object> getHeadersAsObjects()
339 {
340 if (headers == null)
341 headers = new MultivaluedMapImpl<String, Object>();
342 return headers;
343 }
344
345 public MultivaluedMap<String, String> getQueryParameters()
346 {
347 if (queryParameters == null)
348 queryParameters = new MultivaluedMapImpl<String, String>();
349 return queryParameters;
350 }
351
352 public MultivaluedMap<String, String> getFormParameters()
353 {
354 if (formParameters == null)
355 formParameters = new MultivaluedMapImpl<String, String>();
356 return formParameters;
357 }
358
359 public MultivaluedMap<String, String> getPathParameters()
360 {
361 if (pathParameters == null)
362 pathParameters = new MultivaluedMapImpl<String, String>();
363 return pathParameters;
364 }
365
366 public List<String> getPathParameterList()
367 {
368 if (pathParameterList == null)
369 pathParameterList = new ArrayList<String>();
370 return pathParameterList;
371 }
372
373 public MultivaluedMap<String, String> getMatrixParameters()
374 {
375 if (matrixParameters == null)
376 matrixParameters = new MultivaluedMapImpl<String, String>();
377 return matrixParameters;
378 }
379
380 public Object getBody()
381 {
382 return body;
383 }
384
385 public Class getBodyType()
386 {
387 return bodyType;
388 }
389
390 public Type getBodyGenericType()
391 {
392 return bodyGenericType;
393 }
394
395 public Annotation[] getBodyAnnotations()
396 {
397 return bodyAnnotations;
398 }
399
400 public MediaType getBodyContentType()
401 {
402 return bodyContentType;
403 }
404
405 public String getHttpMethod()
406 {
407 return httpMethod;
408 }
409
410 public void setHttpMethod(String httpMethod)
411 {
412 this.httpMethod = httpMethod;
413 }
414
415 public ClientResponse execute() throws Exception
416 {
417 Providers current = ResteasyProviderFactory.getContextData(Providers.class);
418 ResteasyProviderFactory.pushContext(Providers.class, providerFactory);
419 try
420 {
421
422 if (linkHeader != null) header("Link", linkHeader);
423
424 if (getReaderInterceptorList().isEmpty())
425 {
426 setReaderInterceptors(providerFactory.getClientReaderInterceptorRegistry().postMatch(null, null));
427 }
428
429 if (getExecutionInterceptorList().isEmpty())
430 {
431 setExecutionInterceptors(providerFactory
432 .getClientExecutionInterceptorRegistry().bindForList(null, null));
433 }
434
435 BaseClientResponse response = null;
436 if (getExecutionInterceptorList().isEmpty())
437 {
438 response = (BaseClientResponse) executor.execute(this);
439 }
440 else
441 {
442 ClientExecutionContextImpl ctx = new ClientExecutionContextImpl(
443 getExecutionInterceptorList(), executor, this);
444 response = (BaseClientResponse) ctx.proceed();
445 }
446 response.setAttributes(attributes);
447 response.setReaderInterceptors(getReaderInterceptors());
448 return response;
449 }
450 finally
451 {
452 ResteasyProviderFactory.popContextData(Providers.class);
453 if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
454
455 }
456 }
457
458 public void writeRequestBody(MultivaluedMap<String, Object> headers,
459 OutputStream outputStream) throws IOException
460 {
461 if (body == null)
462 {
463 return;
464 }
465
466 if (getWriterInterceptorList().isEmpty())
467 {
468 setWriterInterceptors(providerFactory.getClientWriterInterceptorRegistry().postMatch(null, null));
469 }
470 new ClientWriterInterceptorContext(getWriterInterceptors(), providerFactory, body,
471 bodyType, bodyGenericType, bodyAnnotations, bodyContentType,
472 headers, outputStream, attributes).proceed();
473 }
474
475 public ClientResponse get() throws Exception
476 {
477 return httpMethod("GET");
478 }
479
480 /**
481 * Tries to automatically unmarshal to target type.
482 *
483 * @param returnType
484 * @param <T>
485 * @return
486 * @throws Exception
487 */
488 public <T> T getTarget(Class<T> returnType) throws Exception
489 {
490 BaseClientResponse<T> response = (BaseClientResponse<T>) get(returnType);
491 if (response.getStatus() == 204) return null;
492 if (response.getStatus() != 200) throw new ClientResponseFailure(response);
493 T obj = response.getEntity();
494 if (obj instanceof InputStream)
495 {
496 response.setWasReleased(true);
497 }
498 return obj;
499 }
500
501 /**
502 * Templates the returned ClientResponse for easy access to returned entity
503 *
504 * @param returnType
505 * @param <T>
506 * @return
507 * @throws Exception
508 */
509 public <T> ClientResponse<T> get(Class<T> returnType) throws Exception
510 {
511 BaseClientResponse response = (BaseClientResponse) get();
512 response.setReturnType(returnType);
513 return response;
514 }
515
516 public <T> ClientResponse<T> get(Class<T> returnType, Type genericType)
517 throws Exception
518 {
519 BaseClientResponse response = (BaseClientResponse) get();
520 response.setReturnType(returnType);
521 response.setGenericReturnType(genericType);
522 return response;
523 }
524
525 public <T> ClientResponse<T> get(GenericType type) throws Exception
526 {
527 BaseClientResponse response = (BaseClientResponse) get();
528 response.setReturnType(type.getType());
529 response.setGenericReturnType(type.getGenericType());
530 return response;
531 }
532
533 public ClientResponse head() throws Exception
534 {
535 return httpMethod("HEAD");
536 }
537
538 public ClientResponse put() throws Exception
539 {
540 return httpMethod("PUT");
541 }
542
543 public <T> ClientResponse<T> put(Class<T> returnType) throws Exception
544 {
545 BaseClientResponse response = (BaseClientResponse) put();
546 response.setReturnType(returnType);
547 return response;
548 }
549
550 public <T> ClientResponse<T> put(Class<T> returnType, Type genericType)
551 throws Exception
552 {
553 BaseClientResponse response = (BaseClientResponse) put();
554 response.setReturnType(returnType);
555 response.setGenericReturnType(genericType);
556 return response;
557 }
558
559 public <T> ClientResponse<T> put(GenericType type) throws Exception
560 {
561 BaseClientResponse response = (BaseClientResponse) put();
562 response.setReturnType(type.getType());
563 response.setGenericReturnType(type.getGenericType());
564 return response;
565 }
566
567 public ClientResponse post() throws Exception
568 {
569 return httpMethod("POST");
570 }
571
572 public <T> ClientResponse<T> post(Class<T> returnType) throws Exception
573 {
574 BaseClientResponse response = (BaseClientResponse) post();
575 response.setReturnType(returnType);
576 return response;
577 }
578
579 public <T> T postTarget(Class<T> returnType) throws Exception
580 {
581 BaseClientResponse<T> response = (BaseClientResponse<T>) post(returnType);
582 if (response.getStatus() == 204) return null;
583 if (response.getStatus() != 200) throw new ClientResponseFailure(response);
584 T obj = response.getEntity();
585 if (obj instanceof InputStream)
586 {
587 response.setWasReleased(true);
588 }
589 return obj;
590 }
591
592 public <T> ClientResponse<T> post(Class<T> returnType, Type genericType)
593 throws Exception
594 {
595 BaseClientResponse response = (BaseClientResponse) post();
596 response.setReturnType(returnType);
597 response.setGenericReturnType(genericType);
598 return response;
599 }
600
601 public <T> ClientResponse<T> post(GenericType type) throws Exception
602 {
603 BaseClientResponse response = (BaseClientResponse) post();
604 response.setReturnType(type.getType());
605 response.setGenericReturnType(type.getGenericType());
606 return response;
607 }
608
609 /**
610 * Automatically does POST/Create pattern. Will throw a ClientResponseFailure
611 * if status is something other than 201
612 *
613 * @return Link to created resource
614 * @throws Exception, ClientResponseFailure
615 */
616 public Link create() throws Exception, ClientResponseFailure
617 {
618 BaseClientResponse response = (BaseClientResponse) post();
619 if (response.getStatus() != 201) throw new ClientResponseFailure(response);
620 return response.getLocationLink();
621 }
622
623
624 public ClientResponse delete() throws Exception
625 {
626 return httpMethod("DELETE");
627 }
628
629 public <T> ClientResponse<T> delete(Class<T> returnType) throws Exception
630 {
631 BaseClientResponse response = (BaseClientResponse) delete();
632 response.setReturnType(returnType);
633 return response;
634 }
635
636 public <T> ClientResponse<T> delete(Class<T> returnType, Type genericType)
637 throws Exception
638 {
639 BaseClientResponse response = (BaseClientResponse) delete();
640 response.setReturnType(returnType);
641 response.setGenericReturnType(genericType);
642 return response;
643 }
644
645 public <T> ClientResponse<T> delete(GenericType type) throws Exception
646 {
647 BaseClientResponse response = (BaseClientResponse) delete();
648 response.setReturnType(type.getType());
649 response.setGenericReturnType(type.getGenericType());
650 return response;
651 }
652
653 public ClientResponse options() throws Exception
654 {
655 return httpMethod("OPTIONS");
656 }
657
658 public <T> ClientResponse<T> options(Class<T> returnType) throws Exception
659 {
660 BaseClientResponse response = (BaseClientResponse) options();
661 response.setReturnType(returnType);
662 return response;
663 }
664
665 public <T> ClientResponse<T> options(Class<T> returnType, Type genericType)
666 throws Exception
667 {
668 BaseClientResponse response = (BaseClientResponse) options();
669 response.setReturnType(returnType);
670 response.setGenericReturnType(genericType);
671 return response;
672 }
673
674 public <T> ClientResponse<T> options(GenericType type) throws Exception
675 {
676 BaseClientResponse response = (BaseClientResponse) options();
677 response.setReturnType(type.getType());
678 response.setGenericReturnType(type.getGenericType());
679 return response;
680 }
681
682 public ClientResponse httpMethod(String httpMethod) throws Exception
683 {
684 this.httpMethod = httpMethod;
685 return execute();
686 }
687
688 public <T> ClientResponse<T> httpMethod(String method, Class<T> returnType)
689 throws Exception
690 {
691 BaseClientResponse response = (BaseClientResponse) httpMethod(method);
692 response.setReturnType(returnType);
693 return response;
694 }
695
696 public <T> ClientResponse<T> httpMethod(String method, Class<T> returnType,
697 Type genericType) throws Exception
698 {
699 BaseClientResponse response = (BaseClientResponse) httpMethod(method);
700 response.setReturnType(returnType);
701 response.setGenericReturnType(genericType);
702 return response;
703 }
704
705 public <T> ClientResponse<T> httpMethod(String method, GenericType type)
706 throws Exception
707 {
708 BaseClientResponse response = (BaseClientResponse) httpMethod(method);
709 response.setReturnType(type.getType());
710 response.setGenericReturnType(type.getGenericType());
711 return response;
712 }
713
714 public void overrideUri(URI uri)
715 {
716 this.uri.uri(uri);
717 }
718
719 /**
720 * This method populates all path, matrix, and query parameters and saves it
721 * internally. Once its called once it returns the cached value.
722 *
723 * @return
724 * @throws Exception
725 */
726 public String getUri() throws Exception
727
728 {
729 if (finalUri != null)
730 return finalUri;
731
732 ResteasyUriBuilder builder = (ResteasyUriBuilder) uri.clone();
733 if (matrixParameters != null)
734 {
735 for (Map.Entry<String, List<String>> entry : matrixParameters
736 .entrySet())
737 {
738 List<String> values = entry.getValue();
739 for (String value : values)
740 builder.matrixParam(entry.getKey(), value);
741 }
742 }
743 if (queryParameters != null)
744 {
745 for (Map.Entry<String, List<String>> entry : queryParameters
746 .entrySet())
747 {
748 List<String> values = entry.getValue();
749 for (String value : values)
750 builder.clientQueryParam(entry.getKey(), value);
751 }
752 }
753 if (pathParameterList != null && !pathParameterList.isEmpty())
754 {
755 finalUri = builder.build(pathParameterList.toArray()).toString();
756 }
757 else if (pathParameters != null && !pathParameters.isEmpty())
758 {
759 for (Map.Entry<String, List<String>> entry : pathParameters.entrySet())
760 {
761 List<String> values = entry.getValue();
762 for (String value : values)
763 {
764 value = Encode.encodePathAsIs(value);
765 builder.substitutePathParam(entry.getKey(), value, true);
766 }
767 }
768 }
769 if (finalUri == null)
770 finalUri = builder.build().toString();
771 return finalUri;
772 }
773
774 public ClientRequest createSubsequentRequest(URI uri)
775 {
776 try
777 {
778 ClientRequest clone = (ClientRequest) this.clone();
779 clone.clear();
780 clone.uri = new ResteasyUriBuilder();
781 clone.uri.uri(uri);
782 return clone;
783 }
784 catch (CloneNotSupportedException e)
785 {
786 // this shouldn't happen
787 throw new RuntimeException(Messages.MESSAGES.clientRequestDoesntSupportClonable());
788 }
789 }
790 }
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.ClientInterceptorRepository;
3 import org.jboss.resteasy.client.core.ClientInterceptorRepositoryImpl;
4 import org.jboss.resteasy.client.core.ClientInvoker;
5 import org.jboss.resteasy.client.core.ClientInvokerInterceptorFactory;
6 import org.jboss.resteasy.client.core.ClientInvokerModifier;
7 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
8 import org.jboss.resteasy.client.core.marshallers.ResteasyClientProxy;
9 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
10 import org.jboss.resteasy.spi.ResteasyProviderFactory;
11
12 import java.net.URI;
13
14 /**
15 * Helper class that allows you to pre-initialize an Executor, preset some ClientRequest attributes (like follow redirects)
16 * and define some client-side interceptors you want applied
17 *
18 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
19 * @author Solomon Duskis
20 * @version $Revision: 1 $
21 *
22 * @see org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder
23 * @see org.jboss.resteasy.client.jaxrs.ResteasyWebTarget
24 */
25 @Deprecated
26 public class ClientRequestFactory
27 {
28 private ResteasyProviderFactory providerFactory;
29 private ClientExecutor executor;
30 private URI base = null;
31 private boolean applyDefaultInterceptors = false;
32 private boolean followRedirects = false;
33 private ClientInterceptorRepositoryImpl prefixInterceptors = new ClientInterceptorRepositoryImpl();
34 private ClientInterceptorRepositoryImpl suffixInterceptors = new ClientInterceptorRepositoryImpl();
35
36 public ClientRequestFactory()
37 {
38 init(null, null, null);
39 }
40
41 public ClientRequestFactory(URI base)
42 {
43 init(null, null, base);
44 }
45
46 public ClientRequestFactory(ClientExecutor executor, URI base)
47 {
48 init(executor, null, base);
49 }
50
51 public ClientRequestFactory(ClientExecutor executor,
52 ResteasyProviderFactory providerFactory)
53 {
54 init(executor, providerFactory, null);
55 }
56
57 public ClientRequestFactory(ClientExecutor executor,
58 ResteasyProviderFactory providerFactory, URI base)
59 {
60 init(executor, providerFactory, base);
61 }
62
63 private void init(ClientExecutor executor,
64 ResteasyProviderFactory providerFactory, URI base)
65 {
66 if (providerFactory == null)
67 this.providerFactory = ResteasyProviderFactory.getInstance();
68 else
69 this.providerFactory = providerFactory;
70 if (executor == null)
71 this.executor = new ApacheHttpClient4Executor();
72 else
73 this.executor = executor;
74 this.base = base;
75 }
76
77 public ClientRequestFactory(ClientRequestFactory other)
78 {
79 this.providerFactory = other.providerFactory;
80 this.executor = other.executor;
81 this.setBase(other.getBase());
82 this.applyDefaultInterceptors = other.applyDefaultInterceptors;
83 this.followRedirects = other.followRedirects;
84 other.prefixInterceptors
85 .copyClientInterceptorsTo(this.prefixInterceptors);
86 other.suffixInterceptors
87 .copyClientInterceptorsTo(this.suffixInterceptors);
88 }
89
90 public URI getBase()
91 {
92 return base;
93 }
94
95 public void setBase(URI base)
96 {
97 this.base = base;
98 }
99
100 public void enableDefaultInterceptors()
101 {
102 applyDefaultInterceptors = true;
103 }
104
105 public ClientInterceptorRepository getPrefixInterceptors()
106 {
107 return prefixInterceptors;
108 }
109
110 public ClientInterceptorRepository getSuffixInterceptors()
111 {
112 return suffixInterceptors;
113 }
114
115 public boolean isFollowRedirects()
116 {
117 return followRedirects;
118 }
119
120 public void setFollowRedirects(boolean followRedirects)
121 {
122 this.followRedirects = followRedirects;
123 }
124
125 private void applyInterceptors(ClientInterceptorRepositoryImpl repository)
126 {
127 prefixInterceptors.prefixClientInterceptorsTo(repository);
128 suffixInterceptors.copyClientInterceptorsTo(repository);
129 }
130
131 public ClientRequestFactory clone()
132 {
133 return new ClientRequestFactory(this);
134 }
135
136 public ClientRequest createRelativeRequest(String uriTemplate)
137 {
138 return createRequest(base.toString() + uriTemplate);
139 }
140
141 public ClientRequest createRequest(String uriTemplate)
142 {
143 ClientRequest clientRequest = new ClientRequest(new ResteasyUriBuilder()
144 .uriTemplate(uriTemplate), executor, providerFactory);
145 if (applyDefaultInterceptors)
146 {
147 ClientInvokerInterceptorFactory.applyDefaultInterceptors(
148 clientRequest, providerFactory);
149 }
150 if (followRedirects)
151 {
152 clientRequest.followRedirects();
153 }
154 applyInterceptors(clientRequest);
155 return clientRequest;
156 }
157
158 public <T> T getRelative(String uriTemplate, Class<T> type, Object... params)
159 throws Exception
160 {
161 return get(base.toString() + uriTemplate, type, params);
162 }
163
164 public <T> T get(String uriTemplate, Class<T> type, Object... params)
165 throws Exception
166 {
167 return createRequest(uriTemplate).followRedirects(true).pathParameters(
168 params).get(type).getEntity();
169 }
170
171 public <T> T createProxy(Class<T> clazz)
172 {
173 assert base != null;
174 return createProxy(clazz, base);
175 }
176
177 public <T> T createProxy(Class<T> clazz, String baseUri)
178 {
179 return createProxy(clazz, URI.create(baseUri));
180 }
181
182 public <T> T createProxy(Class<T> clazz, URI baseUri)
183 {
184 // right now all proxies get the default interceptors
185 T proxy = ProxyFactory.create(clazz, baseUri, executor, providerFactory);
186 ResteasyClientProxy clientProxy = (ResteasyClientProxy) proxy;
187 clientProxy.applyClientInvokerModifier(new ClientInvokerModifier()
188 {
189 public void modify(ClientInvoker invoker)
190 {
191 applyInterceptors(invoker);
192 }
193 });
194 return proxy;
195 }
196 }
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.spi.Link;
3 import org.jboss.resteasy.spi.LinkHeader;
4 import org.jboss.resteasy.util.GenericType;
5
6 import javax.ws.rs.core.MultivaluedMap;
7 import javax.ws.rs.core.Response;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Type;
10 import java.util.Map;
11
12 /**
13 * Response extension for the RESTEasy client framework. Use this, or Response
14 * in your client proxy interface method return type declarations if you want
15 * access to the response entity as well as status and header information.
16 *
17 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 *
21 * @see javax.ws.rs.core.Response
22 * @see org.jboss.resteasy.client.jaxrs.internal.ClientResponse
23 */
24 @Deprecated
25 public abstract class ClientResponse<T> extends Response
26 {
27 /**
28 * This method returns the same exact map as Response.getMetadata() except as a map of strings rather than objects
29 *
30 * @return
31 */
32 public abstract MultivaluedMap<String, String> getResponseHeaders();
33
34 public abstract Response.Status getResponseStatus();
35
36 /**
37 * Unmarshal the target entity from the response OutputStream. You must have type information set via <T>
38 * otherwise, this will not work.
39 * <p/>
40 * This method actually does the reading on the OutputStream. It will only do the read once. Afterwards, it will
41 * cache the result and return the cached result.
42 *
43 * @return
44 */
45 public abstract T getEntity();
46
47 /**
48 * Extract the response body with the provided type information
49 * <p/>
50 * This method actually does the reading on the OutputStream. It will only do the read once. Afterwards, it will
51 * cache the result and return the cached result.
52 *
53 * @param type
54 * @param genericType
55 * @param <T2>
56 * @return
57 */
58 public abstract <T2> T2 getEntity(Class<T2> type);
59
60 /**
61 * Extract the response body with the provided type information
62 * <p/>
63 * This method actually does the reading on the OutputStream. It will only do the read once. Afterwards, it will
64 * cache the result and return the cached result.
65 *
66 * @param type
67 * @param genericType
68 * @param <T2>
69 * @return
70 */
71 public abstract <T2> T2 getEntity(Class<T2> type, Type genericType);
72
73 /**
74 * @param type
75 * @param genericType
76 * @param annotations
77 * @param <T2>
78 * @return
79 */
80 public abstract <T2> T2 getEntity(Class<T2> type, Type genericType, Annotation[] annotations);
81
82 /**
83 * Extract the response body with the provided type information. GenericType is a trick used to
84 * pass in generic type information to the resteasy runtime.
85 * <p/>
86 * For example:
87 * <pre>
88 * List<String> list = response.getEntity(new GenericType<List<String>() {});
89 *
90 *
91 * This method actually does the reading on the OutputStream. It will only do the read once. Afterwards, it will
92 * cache the result and return the cached result.
93 *
94 * @param type
95 * @param <T2>
96 * @return
97 */
98 public abstract <T2> T2 getEntity(GenericType<T2> type);
99
100 /**
101 * @param type
102 * @param annotations
103 * @param <T2>
104 * @return
105 */
106 public abstract <T2> T2 getEntity(GenericType<T2> type, Annotation[] annotations);
107
108 /**
109 * Get the <a href="http://tools.ietf.org/html/draft-nottingham-http-link-header-10">link headers</a> of the response.
110 * All Link objects returned will automatically have the same ClientExecutor as the request.
111 *
112 * @return non-null
113 */
114 public abstract LinkHeader getLinkHeader();
115
116 /**
117 * Get the Location header as a Link so you can easily execute on it.
118 * All Link objects returned will automatically have the same ClientExecutor as the request.
119 *
120 * @return
121 */
122 public abstract Link getLocationLink();
123
124 /**
125 * Header is assumed to be a URL, a Link object is created from it if it exists. Also, the type field of the
126 * link with be initialized if there is another header appended with -Type. i.e. if the header was "custom"
127 * it will also look for a header of custom-type and expect that this is a media type.
128 * <p/>
129 * All Link objects returned will automatically have the same ClientExecutor as the request.
130 *
131 * @param headerName
132 * @return null if it doesn't exist
133 */
134 public abstract Link getHeaderAsLink(String headerName);
135
136 /**
137 * Attempts to reset the InputStream of the response. Useful for refetching an entity after a marshalling failure
138 */
139 public abstract void resetStream();
140
141 public abstract void releaseConnection();
142
143 /**
144 * Used to pass information to and between interceptors.
145 *
146 * @return
147 */
148 public abstract Map<String, Object> getAttributes();
149 }
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.BaseClientResponse;
3
4 /**
5 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
6 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7 * @version $Revision: 1 $
8 *
9 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
10 * @see javax.ws.rs.client.ResponseProcessingException
11 * @see javax.ws.rs.client.ProcessingException
12 * @see javax.ws.rs.client.WebApplicationException
13 */
14 @Deprecated
15 public class ClientResponseFailure extends RuntimeException
16 {
17 private static final long serialVersionUID = 7491381058971118249L;
18 private ClientResponse response;
19
20 public ClientResponseFailure(ClientResponse response)
21 {
22 super("Failed with status: " + response.getStatus());
23 this.response = BaseClientResponse.copyFromError(response);
24 // release connection just in case it doesn't get garbage collected or manually released
25 response.releaseConnection();
26 }
27
28 public ClientResponseFailure(String s, ClientResponse response)
29 {
30 super(s);
31 this.response = BaseClientResponse.copyFromError(response);
32 // release the connection because we don't trust users to catch and clean up
33 response.releaseConnection();
34 }
35
36 public ClientResponseFailure(String s, Throwable throwable, ClientResponse response)
37 {
38 super(s, throwable);
39 this.response = BaseClientResponse.copyFromError(response);
40 // release the connection because we don't trust users to catch and clean up
41 response.releaseConnection();
42 }
43
44 public ClientResponseFailure(Throwable throwable, ClientResponse response)
45 {
46 super(throwable);
47 this.response = BaseClientResponse.copyFromError(response);
48 // release the connection because we don't trust users to catch and clean up
49 response.releaseConnection();
50 }
51
52 public ClientResponse getResponse()
53 {
54 return response;
55 }
56 }
0 package org.jboss.resteasy.client;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Used to annotate a predefined URL (as opposed to a @PAthParam /@QueryParam)
9 * in a Proxied client.<br>
10 * <p/>
11 * For Example:
12 * <p/>
13 *
14 * @author <a href="mailto:sduskis@gmail.com">Solomon</a>
15 * @version $Revision: 1 $
16 * @GET MyDTO getDTO(@ClientURI String uri);
17 */
18 @Target({ElementType.PARAMETER})
19 @Retention(RetentionPolicy.RUNTIME)
20 public @interface ClientURI
21 {
22
23 }
0 package org.jboss.resteasy.client;
1
2 import javax.ws.rs.core.MultivaluedMap;
3
4 /**
5 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
6 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7 * @version $Revision: 1 $
8 *
9 * <p>
10 * <b>Note.</b> org.jboss.resteasy.client.ClientResponse<T> is a generic type in the Resteasy client framework,
11 * but org.jboss.resteasy.client.jaxrs.internal.ClientResponse in the resteasy-client module is not, so
12 * EntityTypeFactory is no longer useful.
13 *
14 */
15 @Deprecated
16 public interface EntityTypeFactory
17 {
18 @SuppressWarnings("unchecked")
19 Class getEntityType(int status, MultivaluedMap<String, Object> metadata);
20 }
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.ClientProxy;
3 import org.jboss.resteasy.client.core.MethodInvoker;
4 import org.jboss.resteasy.client.core.SubResourceInvoker;
5 import org.jboss.resteasy.client.core.extractors.DefaultEntityExtractorFactory;
6 import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory;
7 import org.jboss.resteasy.client.core.marshallers.ResteasyClientProxy;
8 import org.jboss.resteasy.spi.ProviderFactoryDelegate;
9 import org.jboss.resteasy.spi.ResteasyProviderFactory;
10 import org.jboss.resteasy.util.IsHttpMethod;
11
12 import javax.ws.rs.Path;
13 import javax.ws.rs.core.MediaType;
14 import java.lang.reflect.Method;
15 import java.lang.reflect.Proxy;
16 import java.net.URI;
17 import java.util.Arrays;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Set;
22
23 /**
24 *
25 * @param <T>
26 * @deprecated The Resteasy proxy facility in the client framework in resteasy-jaxrs is replaced by the
27 * proxy facility extension in the JAX-RS 2.0 compliant resteasy-client module.
28 *
29 * @see resteasy-client
30 * @see org.jboss.resteasy.client.jaxrs.ProxyBuilder
31 * @see org.jboss.resteasy.client.jaxrs.ResteasyWebTarget
32 */
33 @Deprecated
34 public class ProxyBuilder<T>
35 {
36 public static <T> ProxyBuilder<T> build(Class<T> iface, URI base)
37 {
38 return new ProxyBuilder<T>(iface, base);
39 }
40
41 public static <T> ProxyBuilder<T> build(Class<T> iface, String base)
42 {
43 return new ProxyBuilder<T>(iface, ProxyFactory.createUri(base));
44 }
45
46 private final Class<T> iface;
47 private final URI baseUri;
48 private ClassLoader loader;
49 private ClientExecutor executor;
50 private ResteasyProviderFactory providerFactory;
51 private EntityExtractorFactory extractorFactory;
52 private Map<String, Object> requestAttributes;
53 private MediaType serverConsumes;
54 private MediaType serverProduces;
55
56 private ProxyBuilder(Class<T> iface, URI base)
57 {
58 this.iface = iface;
59 this.baseUri = base;
60 this.loader = iface.getClassLoader();
61 }
62
63 public ProxyBuilder<T> classloader(ClassLoader cl)
64 {
65 this.loader = cl;
66 return this;
67 }
68
69 public ProxyBuilder<T> executor(ClientExecutor exec)
70 {
71 this.executor = exec;
72 return this;
73 }
74
75 public ProxyBuilder<T> providerFactory(ResteasyProviderFactory fact)
76 {
77 this.providerFactory = fact;
78 return this;
79 }
80
81 public ProxyBuilder<T> extractorFactory(EntityExtractorFactory fact)
82 {
83 this.extractorFactory = fact;
84 return this;
85 }
86
87 /** shortcut for serverProduces(type).serverConsumes(type) */
88 public ProxyBuilder<T> serverMediaType(MediaType type)
89 {
90 this.serverProduces = type;
91 this.serverConsumes = type;
92 return this;
93 }
94
95 public ProxyBuilder<T> serverProduces(MediaType type)
96 {
97 this.serverProduces = type;
98 return this;
99 }
100
101 public ProxyBuilder<T> serverConsumes(MediaType type)
102 {
103 this.serverConsumes = type;
104 return this;
105 }
106
107 public ProxyBuilder<T> requestAttributes(Map<String, Object> attrs)
108 {
109 this.requestAttributes = attrs;
110 return this;
111 }
112
113 private static final Class<?>[] cClassArgArray =
114 {
115 Class.class
116 };
117
118 public T now()
119 {
120 if (providerFactory instanceof ProviderFactoryDelegate)
121 providerFactory = ((ProviderFactoryDelegate) providerFactory).getDelegate();
122
123 if (executor == null)
124 executor = ClientRequest.getDefaultExecutor();
125 if (providerFactory == null)
126 providerFactory = ResteasyProviderFactory.getInstance();
127 if (extractorFactory == null)
128 extractorFactory = new DefaultEntityExtractorFactory();
129 if (requestAttributes == null)
130 requestAttributes = Collections.emptyMap();
131
132 final ProxyConfig config = new ProxyConfig(loader, executor, providerFactory, extractorFactory, requestAttributes, serverConsumes, serverProduces);
133 return createProxy(iface, baseUri, config);
134 }
135
136 @SuppressWarnings("unchecked")
137 public static <T> T createProxy(final Class<T> iface, URI baseUri, final ProxyConfig config)
138 {
139 HashMap<Method, MethodInvoker> methodMap = new HashMap<Method, MethodInvoker>();
140 for (Method method : iface.getMethods())
141 {
142 // ignore the as method to allow declaration in client interfaces
143 if (!("as".equals(method.getName()) && Arrays.equals(method.getParameterTypes(), cClassArgArray)))
144 {
145 MethodInvoker invoker;
146 Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
147 if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface())
148 {
149 invoker = new SubResourceInvoker(baseUri, method, config);
150 }
151 else
152 {
153 invoker = ProxyFactory.createClientInvoker(iface, method, baseUri, config);
154 }
155 methodMap.put(method, invoker);
156 }
157 }
158
159 Class<?>[] intfs =
160 {
161 iface, ResteasyClientProxy.class
162 };
163
164 ClientProxy clientProxy = new ClientProxy(methodMap, baseUri, config);
165 // this is done so that equals and hashCode work ok. Adding the proxy to a
166 // Collection will cause equals and hashCode to be invoked. The Spring
167 // infrastructure had some problems without this.
168 clientProxy.setClazz(iface);
169
170 return (T) Proxy.newProxyInstance(config.getLoader(), intfs, clientProxy);
171 }
172 }
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.core.MediaType;
6 import java.util.Map;
7
8 /**
9 * @deprecated The Resteasy proxy facility in the client framework in resteasy-jaxrs is replaced by the
10 * proxy facility extension in the JAX-RS 2.0 compliant resteasy-client module.
11 *
12 * @see resteasy-client
13 * @see org.jboss.resteasy.client.jaxrs.ProxyConfig
14 */
15 @Deprecated
16 public class ProxyConfig
17 {
18 private final ClassLoader loader;
19 private final ClientExecutor executor;
20 private final ResteasyProviderFactory providerFactory;
21 private final EntityExtractorFactory extractorFactory;
22 private final Map<String, Object> requestAttributes;
23 private final MediaType serverConsumes;
24 private final MediaType serverProduces;
25
26 public ProxyConfig(ClassLoader loader, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map<String, Object> requestAttributes, MediaType serverConsumes, MediaType serverProduces)
27 {
28 super();
29 this.loader = loader;
30 this.executor = executor;
31 this.providerFactory = providerFactory;
32 this.extractorFactory = extractorFactory;
33 this.requestAttributes = requestAttributes;
34 this.serverConsumes = serverConsumes;
35 this.serverProduces = serverProduces;
36 }
37
38 public ClassLoader getLoader()
39 {
40 return loader;
41 }
42
43 public ClientExecutor getExecutor()
44 {
45 return executor;
46 }
47
48 public ResteasyProviderFactory getProviderFactory()
49 {
50 return providerFactory;
51 }
52
53 public EntityExtractorFactory getExtractorFactory()
54 {
55 return extractorFactory;
56 }
57
58 public Map<String, Object> getRequestAttributes()
59 {
60 return requestAttributes;
61 }
62
63 public MediaType getServerConsumes()
64 {
65 return serverConsumes;
66 }
67
68 public MediaType getServerProduces()
69 {
70 return serverProduces;
71 }
72 }
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.ClientInvoker;
3 import org.jboss.resteasy.client.core.ClientInvokerInterceptorFactory;
4 import org.jboss.resteasy.client.core.extractors.DefaultEntityExtractorFactory;
5 import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory;
6 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
7 import org.jboss.resteasy.spi.ResteasyProviderFactory;
8 import org.jboss.resteasy.util.IsHttpMethod;
9
10 import java.lang.reflect.Method;
11 import java.net.URI;
12 import java.net.URISyntaxException;
13 import java.util.HashMap;
14 import java.util.Map;
15 import java.util.Set;
16
17 /**
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 *
21 * @deprecated The Resteasy proxy facility in the client framework in resteasy-jaxrs is replaced by the
22 * proxy facility extension in the JAX-RS 2.0 compliant resteasy-client module.
23 *
24 * @see resteasy-client
25 * @see org.jboss.resteasy.client.jaxrs.ProxyBuilder
26 * @see org.jboss.resteasy.client.jaxrs.ResteasyWebTarget
27 */
28 @Deprecated
29 public class ProxyFactory
30 {
31
32 public static <T> T create(Class<T> clazz, String base)
33 {
34 return create(clazz, base, ClientRequest.getDefaultExecutor());
35 }
36
37 public static <T> T create(Class<T> clazz, String base, Map<String, Object> requestAttributes)
38 {
39 return create(clazz, createUri(base), ClientRequest.getDefaultExecutor(), ResteasyProviderFactory.getInstance(), new DefaultEntityExtractorFactory(), requestAttributes);
40 }
41
42 public static <T> T create(Class<T> clazz, String base, ResteasyProviderFactory providerFactory, Map<String, Object> requestAttributes)
43 {
44 return create(clazz, createUri(base), ClientRequest.getDefaultExecutor(), providerFactory, new DefaultEntityExtractorFactory(), requestAttributes);
45 }
46
47 public static <T> T create(Class<T> clazz, String base, ClientExecutor client)
48 {
49 return create(clazz, createUri(base), client, ResteasyProviderFactory.getInstance());
50 }
51
52 public static URI createUri(String base)
53 {
54 try
55 {
56 return new URI(base);
57 }
58 catch (URISyntaxException e)
59 {
60 throw new RuntimeException(e);
61 }
62 }
63
64 public static <T> T create(Class<T> clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory)
65 {
66 return create(clazz, baseUri, executor, providerFactory, new DefaultEntityExtractorFactory());
67 }
68
69 public static <T> T create(Class<T> clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory)
70 {
71 return create(clazz, baseUri, executor, providerFactory, extractorFactory, new HashMap<String, Object>());
72 }
73
74 public static <T> T create(Class<T> clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map<String, Object> requestAttributes)
75 {
76 return ProxyBuilder.build(clazz, baseUri).executor(executor).providerFactory(providerFactory).extractorFactory(extractorFactory).requestAttributes(requestAttributes).now();
77 }
78
79 public static <T> ClientInvoker createClientInvoker(Class<T> clazz, Method method, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory)
80 {
81 return createClientInvoker(clazz, method, baseUri, executor, providerFactory, extractorFactory, new HashMap<String, Object>());
82 }
83
84 public static <T> ClientInvoker createClientInvoker(Class<T> clazz, Method method, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map<String, Object> requestAttributes)
85 {
86 return createClientInvoker(clazz, method, baseUri, new ProxyConfig(null, executor, providerFactory, extractorFactory, requestAttributes, null, null));
87 }
88
89 public static <T> ClientInvoker createClientInvoker(Class<T> clazz, Method method, URI baseUri, ProxyConfig config)
90 {
91 Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
92 if (httpMethods == null || httpMethods.size() != 1)
93 {
94 throw new RuntimeException(Messages.MESSAGES.mustUseOneHttpMethod(method.toString()));
95 }
96 ClientInvoker invoker = new ClientInvoker(baseUri, clazz, method, config);
97 invoker.getAttributes().putAll(config.getRequestAttributes());
98 ClientInvokerInterceptorFactory.applyDefaultInterceptors(invoker, config.getProviderFactory(), clazz, method);
99 invoker.setHttpMethod(httpMethods.iterator().next());
100 return invoker;
101 }
102 }
0 package org.jboss.resteasy.client.cache;
1
2 import javax.ws.rs.core.MediaType;
3 import javax.ws.rs.core.MultivaluedMap;
4 import java.io.Serializable;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 *
10 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
11 * caching in the JAX-RS 2.0 compliant resteasy-client module.
12 *
13 * @see resteasy-client
14 * @see org.jboss.resteasy.client.jaxrs.cache.BrowserCache
15 */
16 @Deprecated
17 public interface BrowserCache
18 {
19 public static class Header implements Serializable
20 {
21 private static final long serialVersionUID = 4145981086454860081L;
22
23 private String name;
24 private String value;
25
26 public Header(String name, String value)
27 {
28 this.name = name;
29 this.value = value;
30 }
31
32 public String getName()
33 {
34 return name;
35 }
36
37 public String getValue()
38 {
39 return value;
40 }
41 }
42
43 public static interface Entry
44 {
45 MultivaluedMap<String, String> getHeaders();
46
47 boolean expired();
48
49 Header[] getValidationHeaders();
50
51 byte[] getCached();
52
53 MediaType getMediaType();
54 }
55
56 Entry getAny(String key);
57
58 Entry get(String key, MediaType accept);
59
60 Entry put(String key, MediaType mediaType, MultivaluedMap<String, String> headers, byte[] cached, int expires, String etag, String lastModified);
61
62 Entry remove(String key, MediaType type);
63
64 void clear();
65
66 }
0 package org.jboss.resteasy.client.cache;
1
2 import org.jboss.resteasy.client.cache.BrowserCache.Entry;
3 import org.jboss.resteasy.client.cache.BrowserCache.Header;
4
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.MultivaluedMap;
7 import java.io.Serializable;
8 import java.util.Map;
9 import java.util.concurrent.ConcurrentHashMap;
10
11 /**
12 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
13 * caching in the JAX-RS 2.0 compliant resteasy-client module.
14 *
15 * @see resteasy-client
16 * @see org.jboss.resteasy.client.jaxrs.cache.CacheEntry
17 */
18 @Deprecated
19 public class CacheEntry implements Entry, Serializable
20 {
21 private static final long serialVersionUID = -1922521972113619372L;
22 private final String mediaType;
23 private final byte[] cached;
24 private final int expires;
25 private final long timestamp = System.currentTimeMillis();
26 private final MultivaluedMap<String, String> headers;
27 private Header[] validationHeaders = {};
28 private final String key;
29 private Map extendedProperties = new ConcurrentHashMap();
30
31 public CacheEntry(String key, MultivaluedMap<String, String> headers, byte[] cached, int expires, String etag, String lastModified, MediaType mediaType)
32 {
33 this.key = key;
34 this.cached = cached;
35 this.expires = expires;
36 this.mediaType = mediaType.toString();
37 this.headers = headers;
38
39 if (etag != null || lastModified != null)
40 {
41 if (etag != null && lastModified != null)
42 {
43 validationHeaders = new Header[2];
44 validationHeaders[0] = new Header("If-Modified-Since", lastModified);
45 validationHeaders[1] = new Header("If-None-Match", etag);
46 }
47 else if (etag != null)
48 {
49 validationHeaders = new Header[1];
50 validationHeaders[0] = new Header("If-None-Match", etag);
51 }
52 else if (lastModified != null)
53 {
54 validationHeaders = new Header[1];
55 validationHeaders[0] = new Header("If-Modified-Since", lastModified);
56 }
57
58 }
59 }
60
61 public String getKey()
62 {
63 return key;
64 }
65
66 public MultivaluedMap<String, String> getHeaders()
67 {
68 return headers;
69 }
70
71 public boolean expired()
72 {
73 return System.currentTimeMillis() - timestamp >= expires * 1000L;
74 }
75
76 public Header[] getValidationHeaders()
77 {
78 return validationHeaders;
79 }
80
81 public byte[] getCached()
82 {
83 return cached;
84 }
85
86 public MediaType getMediaType()
87 {
88 return MediaType.valueOf(mediaType);
89 }
90
91 public void addExtendedProperty(Serializable key, Serializable value)
92 {
93 extendedProperties.put(key, value);
94 }
95
96 public Object getExtendedProperty(Serializable key)
97 {
98 return extendedProperties.get(key);
99 }
100 }
0 package org.jboss.resteasy.client.cache;
1
2 import org.jboss.resteasy.client.core.ClientInterceptorRepository;
3 import org.jboss.resteasy.client.core.ClientInvoker;
4 import org.jboss.resteasy.client.core.ClientInvokerModifier;
5 import org.jboss.resteasy.client.core.marshallers.ResteasyClientProxy;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 *
11 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
12 * caching in the JAX-RS 2.0 compliant resteasy-client module.
13 *
14 * @see resteasy-client
15 */
16 @Deprecated
17 public class CacheFactory
18 {
19 /**
20 * Makes the client proxy cacheable. Returns the cache that will hold
21 * returned values from the server.
22 *
23 * @param clientProxy
24 * @return
25 */
26 public static LightweightBrowserCache makeCacheable(Object clientProxy)
27 {
28 LightweightBrowserCache cache = new LightweightBrowserCache();
29 makeCacheable(clientProxy, cache);
30 return cache;
31 }
32
33 /**
34 * Makes the client proxy cacheable. This method allows you to pass in a
35 * shared cache that the proxy should use
36 *
37 * @param clientProxy
38 * @param cache
39 */
40 public static void makeCacheable(Object clientProxy, BrowserCache cache)
41 {
42 final CacheInterceptor interceptor = new CacheInterceptor(cache);
43 ResteasyClientProxy proxy = (ResteasyClientProxy) clientProxy;
44 proxy.applyClientInvokerModifier(new ClientInvokerModifier()
45 {
46 public void modify(ClientInvoker invoker)
47 {
48 if (invoker.getHttpMethod().equalsIgnoreCase("GET"))
49 {
50 invoker.getExecutionInterceptorList().addFirst(interceptor);
51 }
52 }
53 });
54 }
55
56 /**
57 * Make a raw ClientRequest cache results in the provided cache.
58 *
59 * @param request
60 * @param cache
61 */
62 public static void makeCacheable(
63 ClientInterceptorRepository interceptorRepository, BrowserCache cache)
64 {
65 interceptorRepository.getExecutionInterceptorList().addFirst(
66 new CacheInterceptor(cache));
67 }
68 }
0 package org.jboss.resteasy.client.cache;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.client.core.BaseClientResponse;
5 import org.jboss.resteasy.client.core.BaseClientResponse.BaseClientResponseStreamFactory;
6 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
7 import org.jboss.resteasy.spi.interception.ClientExecutionContext;
8 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
9 import org.jboss.resteasy.util.DateUtil;
10 import org.jboss.resteasy.util.MediaTypeHelper;
11 import org.jboss.resteasy.util.ReadFromStream;
12 import org.jboss.resteasy.util.WeightedMediaType;
13
14 import javax.ws.rs.GET;
15 import javax.ws.rs.core.CacheControl;
16 import javax.ws.rs.core.HttpHeaders;
17 import javax.ws.rs.core.MediaType;
18 import javax.ws.rs.core.Response;
19 import java.io.ByteArrayInputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.lang.reflect.Method;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.Date;
26 import java.util.List;
27
28 /**
29 *
30 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
31 * @version $Revision: 1 $
32 *
33 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
34 * caching in the JAX-RS 2.0 compliant resteasy-client module.
35 *
36 * @see resteasy-client
37 * @see org.jboss.resteasy.client.jaxrs.cache.CacheInterceptor
38 */
39 @Deprecated
40 @SuppressWarnings("unchecked")
41 public class CacheInterceptor implements ClientExecutionInterceptor, AcceptedByMethod
42 {
43 protected BrowserCache cache;
44
45 static class CachedStreamFactory implements BaseClientResponseStreamFactory
46 {
47 BrowserCache.Entry entry;
48
49 public CachedStreamFactory(BrowserCache.Entry entry)
50 {
51 this.entry = entry;
52 }
53
54 public InputStream getInputStream() throws IOException
55 {
56 return new ByteArrayInputStream(entry.getCached());
57 }
58
59 public void performReleaseConnection()
60 {
61 }
62 }
63
64 public CacheInterceptor(BrowserCache cache)
65 {
66 this.cache = cache;
67 }
68
69 public boolean accept(Class declaring, Method method)
70 {
71 if (declaring == null || method == null) return true;
72 return method.isAnnotationPresent(GET.class);
73 }
74
75 public ClientResponse execute(ClientExecutionContext ctx) throws Exception
76 {
77 ClientRequest request = ctx.getRequest();
78 if (!request.getHttpMethod().equals("GET"))
79 {
80 return ctx.proceed();
81 }
82
83 BrowserCache.Entry entry = getEntry(request);
84 if (entry == null)
85 {
86 return cache(request, ctx.proceed());
87 }
88
89 if (entry.expired())
90 {
91 cache.remove(request.getUri(), entry.getMediaType());
92 BrowserCache.Header[] headers = entry.getValidationHeaders();
93 for (BrowserCache.Header header : headers)
94 {
95 request.header(header.getName(), header.getValue());
96 }
97 return handleExpired(ctx, request, entry);
98 }
99
100 return createClientResponse(request, entry);
101 }
102
103 protected ClientResponse handleExpired(ClientExecutionContext ctx,
104 ClientRequest request, BrowserCache.Entry entry) throws Exception
105 {
106 ClientResponse response = ctx.proceed();
107 if (response.getStatus() == Response.Status.NOT_MODIFIED.getStatusCode())
108 {
109 return updateOnNotModified(request, entry, (BaseClientResponse) response);
110 }
111 return cache(request, response);
112 }
113
114 private ClientResponse cache(ClientRequest request, ClientResponse response)
115 throws Exception
116 {
117 if (response.getStatus() != 200) return response;
118 return cacheIfPossible(request, (BaseClientResponse) response);
119 }
120
121 public ClientResponse updateOnNotModified(ClientRequest request, BrowserCache.Entry old, BaseClientResponse response) throws Exception
122 {
123 old.getHeaders().remove(HttpHeaders.CACHE_CONTROL);
124 old.getHeaders().remove(HttpHeaders.EXPIRES);
125 old.getHeaders().remove(HttpHeaders.LAST_MODIFIED);
126 String cc = (String) response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
127 String exp = (String) response.getResponseHeaders().getFirst(HttpHeaders.EXPIRES);
128 int expires = -1;
129
130 if (cc != null)
131 {
132 CacheControl cacheControl = CacheControl.valueOf(cc);
133 if (cacheControl.isNoCache())
134 {
135 return createClientResponse(request, old);
136 }
137 expires = cacheControl.getMaxAge();
138 }
139 else if (exp != null)
140 {
141 Date date = DateUtil.parseDate(exp);
142 expires = (int) ((date.getTime() - System.currentTimeMillis()) / 1000);
143 }
144
145 if (cc != null)
146 {
147 old.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cc);
148 }
149 if (exp != null)
150 {
151 old.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, exp);
152 }
153
154 String lastModified = (String) response.getResponseHeaders().getFirst(HttpHeaders.LAST_MODIFIED);
155 String etag = (String) response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
156
157 if (etag == null) etag = old.getHeaders().getFirst(HttpHeaders.ETAG);
158 else old.getHeaders().putSingle(HttpHeaders.ETAG, etag);
159
160 if (lastModified != null)
161 {
162 old.getHeaders().putSingle(HttpHeaders.LAST_MODIFIED, lastModified);
163 }
164
165 if (etag == null && lastModified == null && cc == null && exp == null) // don't cache
166 {
167 return createClientResponse(request, old);
168 }
169
170
171 BrowserCache.Entry entry = cache.put(request.getUri(), old.getMediaType(), old.getHeaders(), old.getCached(), expires, etag, lastModified);
172 return createClientResponse(request, entry);
173
174 }
175
176 private BaseClientResponse createClientResponse(ClientRequest request, BrowserCache.Entry entry)
177 {
178 BaseClientResponse response = new BaseClientResponse(new CachedStreamFactory(entry));
179 response.setStatus(200);
180 response.setHeaders(entry.getHeaders());
181 response.setProviderFactory(request.getProviderFactory());
182 return response;
183 }
184
185
186 public ClientResponse cacheIfPossible(ClientRequest request, BaseClientResponse response) throws Exception
187 {
188 String cc = (String) response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
189 String exp = (String) response.getResponseHeaders().getFirst(HttpHeaders.EXPIRES);
190 int expires = -1;
191
192 if (cc != null)
193 {
194 CacheControl cacheControl = CacheControl.valueOf(cc);
195 if (cacheControl.isNoCache()) return response;
196 expires = cacheControl.getMaxAge();
197 }
198 else if (exp != null)
199 {
200 Date date = DateUtil.parseDate(exp);
201 expires = (int) ((date.getTime() - System.currentTimeMillis()) / 1000);
202 }
203
204 String lastModified = (String) response.getResponseHeaders().getFirst(HttpHeaders.LAST_MODIFIED);
205 String etag = (String) response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
206
207 String contentType = (String) response.getResponseHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
208
209 byte[] cached = ReadFromStream.readFromStream(1024, response.getStreamFactory().getInputStream());
210 response.getStreamFactory().performReleaseConnection();
211
212 MediaType mediaType = MediaType.valueOf(contentType);
213 final BrowserCache.Entry entry = cache.put(request.getUri(), mediaType,
214 response.getResponseHeaders(), cached, expires, etag, lastModified);
215
216 response.setStreamFactory(new CachedStreamFactory(entry));
217
218 return response;
219 }
220
221 protected BrowserCache.Entry getEntry(ClientRequest request) throws Exception
222 {
223 String uri = request.getUri();
224
225 BrowserCache.Entry entry = null;
226 String acceptHeader = request.getHeaders().getFirst(HttpHeaders.ACCEPT);
227 if (acceptHeader != null)
228 {
229 List<WeightedMediaType> waccepts = new ArrayList<WeightedMediaType>();
230 String[] split = acceptHeader.split(",");
231 for (String accept : split)
232 {
233 waccepts.add(WeightedMediaType.valueOf(accept));
234 }
235 Collections.sort(waccepts);
236 List<MediaType> accepts = new ArrayList<MediaType>();
237 for (WeightedMediaType accept : waccepts)
238 {
239 accepts.add(new MediaType(accept.getType(), accept.getSubtype(), accept.getParameters()));
240 }
241 for (MediaType accept : accepts)
242 {
243 entry = cache.get(uri, accept);
244 if (entry != null) return entry;
245 if (MediaTypeHelper.isTextLike(accept))
246 {
247 entry = cache.get(uri, accept.withCharset("UTF-8"));
248 if (entry != null) return entry;
249 }
250 }
251 }
252 else
253 {
254 return cache.getAny(uri);
255 }
256
257 return null;
258 }
259 }
0 package org.jboss.resteasy.client.cache;
1
2
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import java.util.concurrent.atomic.AtomicLong;
6
7 /**
8 * In-memory BrowserCache. Uses an underlying cache, with ConcurrentMapCache as
9 * the default. You specify maximum bytes you want the cache to have. The
10 * default is 2Megabytes. If the cache exceeds this amount, it is wiped clean.
11 * This rather draconian approach to cache reaping is to avoid synchronization
12 * that you would normally have to do in a sophisticated cache.
13 * <p/>
14 * With high concurrent access, because this is not a sophisticated cache,
15 * sometimes a cache entry may be lost. It is consistent though.
16 *
17 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
18 * @version $Revision: 1 $
19 *
20 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
21 * caching in the JAX-RS 2.0 compliant resteasy-client module.
22 *
23 * @see resteasy-client
24 * @see org.jboss.resteasy.client.jaxrs.cache.LightweightBrowserCache
25 */
26 @Deprecated
27 public class LightweightBrowserCache implements BrowserCache
28 {
29
30 protected long maxBytes = 2000000; // 2 meg default
31 protected BrowserCache internalCache = null;
32 protected AtomicLong bytes = new AtomicLong(0);
33
34 public LightweightBrowserCache()
35 {
36 this(new MapCache());
37 }
38
39 public LightweightBrowserCache(BrowserCache cache)
40 {
41 this.internalCache = cache;
42 }
43
44 public BrowserCache getInternalCache()
45 {
46 return internalCache;
47 }
48
49 public void setInternalCache(BrowserCache internalCache)
50 {
51 this.internalCache = internalCache;
52 }
53
54 public long getMaxBytes()
55 {
56 return maxBytes;
57 }
58
59 public void setMaxBytes(long maxBytes)
60 {
61 this.maxBytes = maxBytes;
62 }
63
64 public Entry getAny(String key)
65 {
66 return internalCache.getAny(key);
67 }
68
69 public Entry remove(String key, MediaType type)
70 {
71 Entry entry = internalCache.remove(key, type);
72 if (entry != null) bytes.addAndGet(-1 * entry.getCached().length);
73 return entry;
74 }
75
76 public long getByteCount()
77 {
78 return bytes.get();
79 }
80
81 public Entry get(String key, MediaType accept)
82 {
83 return internalCache.get(key, accept);
84 }
85
86 public Entry put(String key, MediaType mediaType,
87 MultivaluedMap<String, String> headers, byte[] cached, int expires,
88 String etag, String lastModified)
89 {
90 Entry previousValue = internalCache.get(key, mediaType);
91
92 int sizeDiff = -1;
93 if (previousValue == null)
94 sizeDiff = cached.length;
95 else
96 sizeDiff = cached.length - previousValue.getCached().length;
97
98 if (bytes.addAndGet(sizeDiff) > maxBytes)
99 {
100 clear();
101 bytes.addAndGet(sizeDiff);
102 }
103 return internalCache.put(key, mediaType, headers, cached, expires, etag, lastModified);
104 }
105
106 public void clear()
107 {
108 internalCache.clear();
109 bytes.set(0);
110 }
111 }
0 package org.jboss.resteasy.client.cache;
1
2 import javax.ws.rs.core.MediaType;
3 import javax.ws.rs.core.MultivaluedMap;
4 import java.util.Iterator;
5 import java.util.Map;
6 import java.util.concurrent.ConcurrentHashMap;
7
8 /**
9 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
10 * caching in the JAX-RS 2.0 compliant resteasy-client module.
11 *
12 * @see resteasy-client
13 * @see org.jboss.resteasy.client.jaxrs.cache.MapCache
14 */
15 @Deprecated
16 public class MapCache implements BrowserCache
17 {
18 protected Map<String, Map<String, Entry>> cache = null;
19
20 public MapCache()
21 {
22 this(new ConcurrentHashMap<String, Map<String, Entry>>());
23 }
24
25 public MapCache(Map<String, Map<String, Entry>> cache)
26 {
27 this.cache = cache;
28 }
29
30 protected Map<String, Map<String, Entry>> createCache()
31 {
32 return new ConcurrentHashMap<String, Map<String, Entry>>();
33 }
34
35 public Entry get(String key, MediaType accept)
36 {
37 Map<String, Entry> parent = cache.get(key);
38 if (parent == null) return null;
39 return parent.get(accept.toString());
40 }
41
42 public Entry getAny(String key)
43 {
44 Map<String, Entry> parent = cache.get(key);
45 if (parent == null) return null;
46 Iterator<Entry> iterator = parent.values().iterator();
47 if (iterator.hasNext()) return iterator.next();
48 return null;
49 }
50
51 public Entry getEntry(String key, MediaType accept)
52 {
53 Map<String, Entry> parent = cache.get(key);
54 if (parent == null) return null;
55 return parent.get(accept.toString());
56 }
57
58 public Entry remove(String key, MediaType type)
59 {
60 Map<String, Entry> data = cache.get(key);
61 if (data == null) return null;
62 Entry removed = data.remove(type.toString());
63 if (data.isEmpty())
64 {
65 cache.remove(key);
66 }
67 else
68 {
69 cache.put(key, data);
70 }
71 return removed;
72 }
73
74 public void clear()
75 {
76 cache.clear();
77 }
78
79 public Entry put(CacheEntry cacheEntry)
80 {
81 Map<String, Entry> map = cache.get(cacheEntry.getKey());
82 if (map == null)
83 {
84 map = new ConcurrentHashMap<String, Entry>();
85 }
86 map.put(cacheEntry.getMediaType().toString(), cacheEntry);
87 cache.put(cacheEntry.getKey(), map);
88 return cacheEntry;
89 }
90
91 public Entry put(String key, MediaType mediaType,
92 MultivaluedMap<String, String> headers, byte[] cached, int expires,
93 String etag, String lastModified)
94 {
95 return put(new CacheEntry(key, headers, cached, expires, etag, lastModified, mediaType));
96 }
97 }
98
0 /**
1 * The client cache facility in Resteasy 2.x is deprecated in favor of the client cache
2 * facility in the resteasy-client module.
3 */
4 package org.jboss.resteasy.client.cache;
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.client.ClientResponseFailure;
5 import org.jboss.resteasy.core.ProvidersContextRetainer;
6 import org.jboss.resteasy.core.interception.ClientReaderInterceptorContext;
7 import org.jboss.resteasy.plugins.delegates.LinkHeaderDelegate;
8 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
9 import org.jboss.resteasy.spi.Link;
10 import org.jboss.resteasy.spi.LinkHeader;
11 import org.jboss.resteasy.spi.MarshalledEntity;
12 import org.jboss.resteasy.spi.NotImplementedYetException;
13 import org.jboss.resteasy.spi.ReaderException;
14 import org.jboss.resteasy.spi.ResteasyProviderFactory;
15 import org.jboss.resteasy.util.CaseInsensitiveMap;
16 import org.jboss.resteasy.util.GenericType;
17 import org.jboss.resteasy.util.HttpHeaderNames;
18 import org.jboss.resteasy.util.HttpResponseCodes;
19 import org.jboss.resteasy.util.InputStreamToByteArray;
20 import org.jboss.resteasy.util.ReadFromStream;
21 import org.jboss.resteasy.util.Types;
22
23 import javax.ws.rs.core.EntityTag;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.core.NewCookie;
27 import javax.ws.rs.ext.MessageBodyReader;
28 import javax.ws.rs.ext.Providers;
29 import javax.ws.rs.ext.ReaderInterceptor;
30
31 import java.io.ByteArrayInputStream;
32 import java.io.FilterInputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.lang.annotation.Annotation;
36 import java.lang.reflect.ParameterizedType;
37 import java.lang.reflect.Type;
38 import java.net.URI;
39 import java.util.Date;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.Map;
43 import java.util.Set;
44
45 import static java.lang.String.format;
46
47 /**
48 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
49 * @version $Revision: 1 $
50 */
51 @SuppressWarnings("unchecked")
52 public class BaseClientResponse<T> extends ClientResponse<T>
53 {
54 public static interface BaseClientResponseStreamFactory
55 {
56 InputStream getInputStream() throws IOException;
57
58 void performReleaseConnection();
59 }
60
61 protected ResteasyProviderFactory providerFactory;
62 protected String attributeExceptionsTo;
63 protected MultivaluedMap<String, String> headers;
64 protected String alternateMediaType;
65 protected Class<?> returnType;
66 protected Type genericReturnType;
67 protected Annotation[] annotations = {};
68 protected int status;
69 protected boolean wasReleased = false;
70 protected Object unmarshaledEntity;
71 protected ReaderInterceptor[] readerInterceptors;
72 protected Exception exception;// These can only be set by an interceptor
73 protected BaseClientResponseStreamFactory streamFactory;
74 protected LinkHeader linkHeader;
75 protected Link location;
76 protected ClientExecutor executor;
77 protected Map<String, Object> attributes;
78
79 public BaseClientResponse(BaseClientResponseStreamFactory streamFactory, ClientExecutor executor)
80 {
81 this.streamFactory = streamFactory;
82 this.executor = executor;
83 }
84
85 public BaseClientResponse(BaseClientResponseStreamFactory streamFactory)
86 {
87 this.streamFactory = streamFactory;
88 }
89
90 /**
91 * Store entity within a byte array input stream because we want to release the connection
92 * if a ClientResponseFailure is thrown. Copy status and headers, but ignore
93 * all type information stored in the ClientResponse.
94 *
95 * @param copy
96 * @return
97 */
98 public static ClientResponse copyFromError(ClientResponse copy)
99 {
100 if (copy instanceof BaseClientResponse)
101 {
102 BaseClientResponse base = (BaseClientResponse) copy;
103 InputStream is = null;
104 if (copy.getResponseHeaders().containsKey("Content-Type"))
105 {
106 try
107 {
108 is = base.streamFactory.getInputStream();
109 if (is != null)
110 {
111 byte[] bytes = ReadFromStream.readFromStream(1024, is);
112 is = new ByteArrayInputStream(bytes);
113 }
114 }
115 catch (IOException e)
116 {
117 // ignored
118 }
119 }
120
121 final InputStream theIs = is;
122 BaseClientResponse tmp = new BaseClientResponse(new BaseClientResponse.BaseClientResponseStreamFactory()
123 {
124 InputStream stream;
125
126 public InputStream getInputStream() throws IOException
127 {
128 return theIs;
129 }
130
131 public void performReleaseConnection()
132 {
133 }
134 });
135 tmp.executor = base.executor;
136 tmp.status = base.status;
137 tmp.providerFactory = base.providerFactory;
138 tmp.headers = new CaseInsensitiveMap<String>();
139 tmp.headers.putAll(base.headers);
140 tmp.readerInterceptors = base.readerInterceptors;
141 return tmp;
142 }
143 else
144 {
145 // Not sure how this codepath could ever be reached.
146 InputStream is = null;
147 if (copy.getResponseHeaders().containsKey("Content-Type"))
148 {
149 GenericType<byte[]> gt = new GenericType<byte[]>()
150 {
151 };
152 try
153 {
154 byte[] bytes = (byte[]) copy.getEntity(gt);
155 is = new ByteArrayInputStream(bytes);
156 }
157 catch (Exception ignore)
158 {
159 }
160 }
161 final InputStream theIs = is;
162 BaseClientResponse tmp = new BaseClientResponse(new BaseClientResponse.BaseClientResponseStreamFactory()
163 {
164 InputStream stream;
165
166 public InputStream getInputStream() throws IOException
167 {
168 return theIs;
169 }
170
171 public void performReleaseConnection()
172 {
173 }
174 });
175 tmp.status = copy.getStatus();
176 tmp.providerFactory = ResteasyProviderFactory.getInstance();
177 tmp.headers = new CaseInsensitiveMap<String>();
178 tmp.headers.putAll(copy.getResponseHeaders());
179 tmp.headers.remove("Content-Encoding"); // remove encoding because we will have already extracted byte array
180 return tmp;
181 }
182 }
183
184 @Override
185 public Map<String, Object> getAttributes()
186 {
187 return attributes;
188 }
189
190 public void setAttributes(Map<String, Object> attributes)
191 {
192 this.attributes = attributes;
193 }
194
195 public void setReaderInterceptors(ReaderInterceptor[] readerInterceptors)
196 {
197 this.readerInterceptors = readerInterceptors;
198 }
199
200 public void setStatus(int status)
201 {
202 this.status = status;
203 }
204
205 public void setHeaders(MultivaluedMap<String, String> headers)
206 {
207 this.headers = headers;
208 }
209
210 public void setProviderFactory(ResteasyProviderFactory providerFactory)
211 {
212 this.providerFactory = providerFactory;
213 }
214
215 public void setReturnType(Class<T> returnType)
216 {
217 this.returnType = returnType;
218 }
219
220 public Class<?> getReturnType()
221 {
222 return returnType;
223 }
224
225 public void setGenericReturnType(Type genericReturnType)
226 {
227 this.genericReturnType = genericReturnType;
228 }
229
230 public void setAnnotations(Annotation[] annotations)
231 {
232 this.annotations = annotations;
233 }
234
235 public String getAttributeExceptionsTo()
236 {
237 return attributeExceptionsTo;
238 }
239
240 public void setAttributeExceptionsTo(String attributeExceptionsTo)
241 {
242 this.attributeExceptionsTo = attributeExceptionsTo;
243 }
244
245 public Exception getException()
246 {
247 return exception;
248 }
249
250 public void setException(Exception exception)
251 {
252 this.exception = exception;
253 }
254
255 public Annotation[] getAnnotations()
256 {
257 return this.annotations;
258 }
259
260 public String getResponseHeader(String headerKey)
261 {
262 if (headers == null) return null;
263 return headers.getFirst(headerKey);
264 }
265
266 public LinkHeader getLinkHeader()
267 {
268 if (linkHeader != null) return linkHeader;
269 linkHeader = new LinkHeader();
270 if (!headers.containsKey("Link"))
271 {
272 return linkHeader;
273 }
274 List<String> links = headers.get("Link");
275 LinkHeaderDelegate delegate = new LinkHeaderDelegate();
276 for (String link : links)
277 {
278 LinkHeader tmp = delegate.fromString(link);
279 linkHeader.getLinks().addAll(tmp.getLinks());
280 linkHeader.getLinksByRelationship().putAll(tmp.getLinksByRelationship());
281 linkHeader.getLinksByTitle().putAll(tmp.getLinksByTitle());
282
283 }
284 for (Link link : linkHeader.getLinks())
285 {
286 link.setExecutor(executor);
287 }
288 return linkHeader;
289 }
290
291 public Link getLocationLink()
292 {
293 if (location != null) return location;
294 if (!headers.containsKey("Location")) return null;
295 String header = headers.getFirst("Location");
296
297 location = new Link();
298 location.setHref(header);
299 location.setExecutor(executor);
300
301 return location;
302 }
303
304 @Override
305 public Link getHeaderAsLink(String headerName)
306 {
307 String value = headers.getFirst(headerName);
308 if (value == null) return null;
309 String type = headers.getFirst(headerName + "-type");
310 Link link = new Link();
311 link.setHref(value);
312 link.setType(type);
313 link.setExecutor(executor);
314 return link;
315 }
316
317 public void setAlternateMediaType(String alternateMediaType)
318 {
319 this.alternateMediaType = alternateMediaType;
320 }
321
322 public BaseClientResponseStreamFactory getStreamFactory()
323 {
324 return streamFactory;
325 }
326
327 public void setStreamFactory(BaseClientResponseStreamFactory streamFactory)
328 {
329 this.streamFactory = streamFactory;
330 }
331
332 @Override
333 public void resetStream()
334 {
335 try
336 {
337 if (this.streamFactory.getInputStream().markSupported())
338 {
339 this.streamFactory.getInputStream().reset();
340 }
341 }
342 catch (IOException e)
343 {
344 throw new RuntimeException(e);
345 }
346 }
347
348 @Override
349 public T getEntity()
350 {
351 if (returnType == null)
352 {
353 throw new RuntimeException(Messages.MESSAGES.noTypeInformationForEntity());
354 }
355 return (T) getEntity(returnType, genericReturnType, this.annotations);
356 }
357
358 @Override
359 public <T2> T2 getEntity(Class<T2> type)
360 {
361 return getEntity(type, null);
362 }
363
364 @Override
365 public <T2> T2 getEntity(Class<T2> type, Type genericType)
366 {
367 return getEntity(type, genericType, getAnnotations(type, genericType));
368 }
369
370 private <T2> Annotation[] getAnnotations(Class<T2> type, Type genericType)
371 {
372 if (this.annotations != null)
373 {
374 return this.annotations;
375 }
376 return (this.returnType == type && this.genericReturnType == genericType) ? this.annotations
377 : null;
378 }
379
380 @Override
381 public <T2> T2 getEntity(Class<T2> type, Type genericType, Annotation[] anns)
382 {
383 if (exception != null)
384 {
385 throw new RuntimeException(Messages.MESSAGES.unableToUnmarshalResponse(attributeExceptionsTo), exception);
386 }
387
388 if (unmarshaledEntity != null && !type.isInstance(this.unmarshaledEntity))
389 throw new RuntimeException(Messages.MESSAGES.entityAlreadyRead(unmarshaledEntity.getClass()));
390
391 if (unmarshaledEntity == null)
392 {
393 if (status == HttpResponseCodes.SC_NO_CONTENT)
394 return null;
395
396 unmarshaledEntity = readFrom(type, genericType, getMediaType(), anns);
397 // only release connection if we actually unmarshalled something and if the object is *NOT* an InputStream
398 // If it is an input stream, the user may be doing their own stream processing.
399 if (unmarshaledEntity != null && !InputStream.class.isInstance(unmarshaledEntity)) releaseConnection();
400 }
401 return (T2) unmarshaledEntity;
402 }
403
404 public MediaType getMediaType()
405 {
406 String mediaType = getResponseHeader(HttpHeaderNames.CONTENT_TYPE);
407 if (mediaType == null)
408 {
409 mediaType = alternateMediaType;
410 }
411
412 return mediaType == null ? MediaType.WILDCARD_TYPE : MediaType.valueOf(mediaType);
413 }
414
415 // this is synchronized in conjunction with finalize to protect against premature finalize called by the GC
416 protected synchronized <T2> Object readFrom(Class<T2> type, Type genericType,
417 MediaType media, Annotation[] annotations)
418 {
419 Type useGeneric = genericType == null ? type : genericType;
420 Class<?> useType = type;
421 boolean isMarshalledEntity = false;
422 if (type.equals(MarshalledEntity.class))
423 {
424 isMarshalledEntity = true;
425 ParameterizedType param = (ParameterizedType) useGeneric;
426 useGeneric = param.getActualTypeArguments()[0];
427 useType = Types.getRawType(useGeneric);
428 }
429
430 Providers current = ResteasyProviderFactory.getContextData(Providers.class);
431 ResteasyProviderFactory.pushContext(Providers.class, providerFactory);
432 Object obj = null;
433 try
434 {
435 InputStream is = streamFactory.getInputStream();
436 if (is == null)
437 {
438 throw new ClientResponseFailure(Messages.MESSAGES.inputStreamEmpty(), this);
439 }
440 if (isMarshalledEntity)
441 {
442 is = new InputStreamToByteArray(is);
443
444 }
445
446 final Object finalObj = new ClientReaderInterceptorContext(readerInterceptors, providerFactory, useType,
447 useGeneric, annotations, media, getResponseHeaders(), new InputStreamWrapper(is), attributes)
448 .proceed();
449 obj = finalObj;
450 if (isMarshalledEntity)
451 {
452 InputStreamToByteArray isba = (InputStreamToByteArray) is;
453 final byte[] bytes = isba.toByteArray();
454 return new MarshalledEntity()
455 {
456 @Override
457 public byte[] getMarshalledBytes()
458 {
459 return bytes;
460 }
461
462 @Override
463 public Object getEntity()
464 {
465 return finalObj;
466 }
467 };
468 }
469 else
470 {
471 return (T2) finalObj;
472 }
473
474 }
475 catch (Exception e)
476 {
477 if (e instanceof ReaderException)
478 {
479 throw (ReaderException) e;
480 }
481 else
482 {
483 throw new ReaderException(e);
484 }
485 }
486 finally
487 {
488 ResteasyProviderFactory.popContextData(Providers.class);
489 if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
490 if (obj instanceof ProvidersContextRetainer)
491 {
492 ((ProvidersContextRetainer) obj).setProviders(providerFactory);
493 }
494 }
495 }
496
497 private static class InputStreamWrapper extends FilterInputStream {
498 protected InputStreamWrapper(InputStream in) {
499 super(in);
500 }
501
502 @Override
503 public void close() throws IOException {
504 }
505 }
506
507 @Override
508 public <T2> T2 getEntity(GenericType<T2> genericType)
509 {
510 return getEntity(genericType.getType(), genericType.getGenericType());
511 }
512
513 @Override
514 public <T2> T2 getEntity(GenericType<T2> genericType, Annotation[] ann)
515 {
516 return getEntity(genericType.getType(), genericType.getGenericType(), ann);
517 }
518
519 public MultivaluedMap<String, String> getResponseHeaders()
520 {
521 return headers;
522 }
523
524 @Override
525 public MultivaluedMap<String, Object> getMetadata()
526 {
527 // hack to cast from <String, String> to <String, Object>
528 return (MultivaluedMap) headers;
529 }
530
531 @Override
532 public int getStatus()
533 {
534 return status;
535 }
536
537 @Override
538 public StatusType getStatusInfo()
539 {
540 StatusType statusType = Status.fromStatusCode(status);
541 if (statusType == null)
542 {
543 statusType = new StatusType()
544 {
545 @Override
546 public int getStatusCode()
547 {
548 return status;
549 }
550
551 @Override
552 public Status.Family getFamily()
553 {
554 return Status.Family.OTHER;
555 }
556
557 @Override
558 public String getReasonPhrase()
559 {
560 return "Unknown Code";
561 }
562 };
563 }
564 return statusType;
565 }
566
567 public void checkFailureStatus()
568 {
569 if (status > 399 && status < 599)
570 {
571 // throw createResponseFailure(format("Error status %d %s returned", status, getResponseStatus()));
572 throw createResponseFailure(Messages.MESSAGES.clientResponseFailureStatus(status, getResponseStatus()));
573 }
574 }
575
576 public ClientResponseFailure createResponseFailure(String message)
577 {
578 return createResponseFailure(message, null);
579 }
580
581 public ClientResponseFailure createResponseFailure(String message, Exception e)
582 {
583 setException(e);
584 this.returnType = byte[].class;
585 this.genericReturnType = null;
586 this.annotations = null;
587 return new ClientResponseFailure(message, e, (ClientResponse<byte[]>) this);
588 }
589
590 @Override
591 public Status getResponseStatus()
592 {
593 return Status.fromStatusCode(getStatus());
594 }
595
596 public boolean wasReleased()
597 {
598 return wasReleased;
599 }
600
601 public void setWasReleased(boolean wasReleased)
602 {
603 this.wasReleased = wasReleased;
604 }
605
606 public final void releaseConnection()
607 {
608 if (!wasReleased)
609 {
610 if (streamFactory != null) streamFactory.performReleaseConnection();
611 wasReleased = true;
612 }
613 }
614
615 @Override
616 // this is synchronized to protect against premature finalize called by the GC
617 protected synchronized final void finalize() throws Throwable
618 {
619 releaseConnection();
620 }
621
622 @Override
623 public <T> T readEntity(Class<T> entityType)
624 {
625 throw new NotImplementedYetException();
626 }
627
628 @Override
629 public <T> T readEntity(javax.ws.rs.core.GenericType<T> entityType)
630 {
631 throw new NotImplementedYetException();
632 }
633
634 @Override
635 public <T> T readEntity(Class<T> entityType, Annotation[] annotations)
636 {
637 throw new NotImplementedYetException();
638 }
639
640 @Override
641 public <T> T readEntity(javax.ws.rs.core.GenericType<T> entityType, Annotation[] annotations)
642 {
643 throw new NotImplementedYetException();
644 }
645
646 @Override
647 public boolean hasEntity()
648 {
649 throw new NotImplementedYetException();
650 }
651
652 @Override
653 public boolean bufferEntity()
654 {
655 throw new NotImplementedYetException();
656 }
657
658 @Override
659 public void close()
660 {
661 releaseConnection();
662 }
663
664 @Override
665 public String getHeaderString(String name)
666 {
667 throw new NotImplementedYetException();
668 }
669
670 @Override
671 public Locale getLanguage()
672 {
673 throw new NotImplementedYetException();
674 }
675
676 @Override
677 public int getLength()
678 {
679 throw new NotImplementedYetException();
680 }
681
682 @Override
683 public Map<String, NewCookie> getCookies()
684 {
685 throw new NotImplementedYetException();
686 }
687
688 @Override
689 public EntityTag getEntityTag()
690 {
691 throw new NotImplementedYetException();
692 }
693
694 @Override
695 public Date getDate()
696 {
697 throw new NotImplementedYetException();
698 }
699
700 @Override
701 public Date getLastModified()
702 {
703 throw new NotImplementedYetException();
704 }
705
706 @Override
707 public Set<javax.ws.rs.core.Link> getLinks()
708 {
709 throw new NotImplementedYetException();
710 }
711
712 @Override
713 public boolean hasLink(String relation)
714 {
715 throw new NotImplementedYetException();
716 }
717
718 @Override
719 public javax.ws.rs.core.Link getLink(String relation)
720 {
721 throw new NotImplementedYetException();
722 }
723
724 @Override
725 public javax.ws.rs.core.Link.Builder getLinkBuilder(String relation)
726 {
727 throw new NotImplementedYetException();
728 }
729
730 @Override
731 public URI getLocation()
732 {
733 throw new NotImplementedYetException();
734 }
735
736 @Override
737 public Set<String> getAllowedMethods()
738 {
739 throw new NotImplementedYetException();
740 }
741
742 @Override
743 public MultivaluedMap<String, String> getStringHeaders()
744 {
745 throw new NotImplementedYetException();
746 }
747 }
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ClientResponse;
3
4 import javax.ws.rs.core.Response;
5
6 /**
7 * {@link ClientErrorInterceptor} provides a hook into the proxy
8 * {@link ClientResponse} request lifecycle. If a Client Proxy method is called,
9 * resulting in a client exception, and the proxy return type is not
10 * {@link Response} or {@link ClientResponse}, registered interceptors will be
11 * given a chance to process the response manually, or throw a new exception. If
12 * all interceptors successfully return, RestEasy will re-throw the original
13 * encountered exception.
14 *
15 * @author <a href="mailto:lincoln@ocpsoft.com">Lincoln Baxter, III</a>
16 */
17 public interface ClientErrorInterceptor
18 {
19 /**
20 * Attempt to handle the current {@link ClientResponse}. If this method
21 * returns successfully, the next registered
22 * {@link ClientErrorInterceptor} will attempt to handle the
23 * {@link ClientResponse}. If this method throws an exception, no further
24 * interceptors will be processed.
25 *
26 * @throws RuntimeException RestEasy will abort request processing if any exception is
27 * thrown from this method.
28 */
29 void handle(ClientResponse<?> response) throws RuntimeException;
30 }
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
3
4 import javax.ws.rs.ext.ReaderInterceptor;
5 import javax.ws.rs.ext.WriterInterceptor;
6 import java.util.LinkedList;
7
8 /**
9 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
10 * @version $Revision: 1 $
11 */
12 public interface ClientInterceptorRepository
13 {
14
15 LinkedList<ReaderInterceptor> getReaderInterceptorList();
16
17 LinkedList<WriterInterceptor> getWriterInterceptorList();
18
19 LinkedList<ClientExecutionInterceptor> getExecutionInterceptorList();
20
21 void registerInterceptor(Object interceptor);
22 }
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.core.interception.ReaderInterceptorRegistry;
3 import org.jboss.resteasy.core.interception.WriterInterceptorRegistry;
4 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
5 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
6 import org.jboss.resteasy.spi.interception.MessageBodyReaderInterceptor;
7 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
8
9 import javax.ws.rs.ext.ReaderInterceptor;
10 import javax.ws.rs.ext.WriterInterceptor;
11
12 import java.lang.reflect.Array;
13 import java.util.Arrays;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.LinkedList;
17 import java.util.Map;
18 import java.util.Map.Entry;
19
20 @SuppressWarnings("unchecked")
21 public class ClientInterceptorRepositoryImpl implements ClientInterceptorRepository
22 {
23
24 private static enum InterceptorType
25 {
26 MessageBodyReader(ReaderInterceptor.class),
27 MessageBodyWriter(
28 WriterInterceptor.class),
29 ClientExecution(
30 ClientExecutionInterceptor.class);
31
32 Class<?> clazz;
33
34 public static InterceptorType getInterceptorTypeFor(Class<?> type)
35 {
36 for (InterceptorType interceptorType : InterceptorType.values())
37 {
38 if (type == interceptorType.clazz)
39 {
40 return interceptorType;
41 }
42 }
43 return null;
44 }
45
46 InterceptorType(Class<?> clazz)
47 {
48 this.clazz = clazz;
49 }
50 }
51
52 private Map<InterceptorType, LinkedList<?>> interceptorLists = new HashMap<InterceptorType, LinkedList<?>>();
53
54 protected ReaderInterceptor[] getReaderInterceptors()
55 {
56 return getArray(ReaderInterceptor.class);
57 }
58
59 protected WriterInterceptor[] getWriterInterceptors()
60 {
61 return getArray(WriterInterceptor.class);
62 }
63
64 protected ClientExecutionInterceptor[] getExecutionInterceptors()
65 {
66 return getArray(ClientExecutionInterceptor.class);
67 }
68
69 private <T> T[] getArray(Class<T> type)
70 {
71 LinkedList<T> interceptors = getInterceptors(type);
72 return (T[]) interceptors.toArray((T[]) Array.newInstance(type,
73 interceptors.size()));
74 }
75
76 protected void setReaderInterceptors(
77 ReaderInterceptor[] readerInterceptors)
78 {
79 setData(InterceptorType.MessageBodyReader, readerInterceptors);
80 }
81
82 protected void setWriterInterceptors(
83 WriterInterceptor[] writerInterceptors)
84 {
85 setData(InterceptorType.MessageBodyWriter, writerInterceptors);
86 }
87
88 protected void setExecutionInterceptors(
89 ClientExecutionInterceptor[] executionInterceptors)
90 {
91 setData(InterceptorType.ClientExecution, executionInterceptors);
92 }
93
94 protected void setExecutionInterceptors(
95 Collection<ClientExecutionInterceptor> executionInterceptorList)
96 {
97 setData(InterceptorType.ClientExecution, executionInterceptorList);
98 }
99
100 public LinkedList<ReaderInterceptor> getReaderInterceptorList()
101 {
102 return getInterceptors(InterceptorType.MessageBodyReader);
103 }
104
105 public LinkedList<WriterInterceptor> getWriterInterceptorList()
106 {
107 return getInterceptors(InterceptorType.MessageBodyWriter);
108 }
109
110 public LinkedList<ClientExecutionInterceptor> getExecutionInterceptorList()
111 {
112 return getInterceptors(InterceptorType.ClientExecution);
113 }
114
115 protected <T> LinkedList<T> getInterceptors(Class<T> clazz)
116 {
117 InterceptorType interceptorType = InterceptorType
118 .getInterceptorTypeFor(clazz);
119 if (interceptorType == null)
120 return null;
121 return getInterceptors(interceptorType);
122 }
123
124 protected synchronized LinkedList getInterceptors(
125 InterceptorType interceptorType)
126 {
127 LinkedList interceptors = interceptorLists.get(interceptorType);
128 if (interceptors == null)
129 {
130 interceptorLists.put(interceptorType, interceptors = new LinkedList());
131 }
132 return interceptors;
133 }
134
135 private void setData(InterceptorType type, Object[] arr)
136 {
137 setData(type, Arrays.asList(arr));
138 }
139
140 private void setData(InterceptorType type, Collection newList)
141 {
142 LinkedList list = getInterceptors(type);
143 list.clear();
144 list.addAll(newList);
145 }
146
147 public void copyClientInterceptorsTo(ClientInterceptorRepositoryImpl copyTo)
148 {
149 for (Entry<InterceptorType, LinkedList<?>> entry : interceptorLists
150 .entrySet())
151 {
152 LinkedList copyToInterceptors = copyTo.getInterceptors(entry.getKey());
153 LinkedList copyFromInterceptors = this.getInterceptors(entry.getKey());
154 copyToInterceptors.addAll(copyFromInterceptors);
155 }
156 }
157
158 public void prefixClientInterceptorsTo(ClientInterceptorRepositoryImpl copyTo)
159 {
160 for (Entry<InterceptorType, LinkedList<?>> entry : interceptorLists
161 .entrySet())
162 {
163 LinkedList copyToInterceptors = copyTo.getInterceptors(entry.getKey());
164 LinkedList copyFromInterceptors = this.getInterceptors(entry.getKey());
165 for (Object interceptor : copyFromInterceptors)
166 {
167 copyToInterceptors.addFirst(interceptor);
168 }
169 }
170 }
171
172 public void registerInterceptor(Object interceptor)
173 {
174 boolean registered = false;
175 if (interceptor instanceof ClientExecutionInterceptor)
176 {
177 getExecutionInterceptorList().add(
178 (ClientExecutionInterceptor) interceptor);
179 registered = true;
180 }
181 if (interceptor instanceof MessageBodyReaderInterceptor)
182 {
183 getReaderInterceptorList().add(
184 new ReaderInterceptorRegistry.ReaderInterceptorFacade((MessageBodyReaderInterceptor)interceptor));
185 registered = true;
186 }
187 if (interceptor instanceof MessageBodyWriterInterceptor)
188 {
189 getWriterInterceptorList().add(
190 new WriterInterceptorRegistry.WriterInterceptorFacade((MessageBodyWriterInterceptor) interceptor));
191 registered = true;
192 }
193
194 if (!registered)
195 {
196 throw new RuntimeException(Messages.MESSAGES.entityNotOfUnderstoodType());
197 }
198 }
199
200 }
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.ProxyConfig;
6 import org.jboss.resteasy.client.core.extractors.ClientErrorHandler;
7 import org.jboss.resteasy.client.core.extractors.ClientRequestContext;
8 import org.jboss.resteasy.client.core.extractors.EntityExtractor;
9 import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory;
10 import org.jboss.resteasy.client.core.marshallers.ClientMarshallerFactory;
11 import org.jboss.resteasy.client.core.marshallers.Marshaller;
12 import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper;
13 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
14 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
15 import org.jboss.resteasy.spi.ResteasyProviderFactory;
16 import org.jboss.resteasy.util.MediaTypeHelper;
17
18 import javax.ws.rs.Path;
19 import javax.ws.rs.core.HttpHeaders;
20 import javax.ws.rs.core.MediaType;
21 import javax.ws.rs.ext.Providers;
22
23 import java.lang.reflect.Method;
24 import java.net.URI;
25 import java.util.HashMap;
26 import java.util.Map;
27
28 /**
29 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
30 * @version $Revision: 1 $
31 */
32 @SuppressWarnings("unchecked")
33 public class ClientInvoker extends ClientInterceptorRepositoryImpl implements MethodInvoker
34 {
35 protected ResteasyProviderFactory providerFactory;
36 protected String httpMethod;
37 protected ResteasyUriBuilder uri;
38 protected Method method;
39 protected Class declaring;
40 protected MediaType accepts;
41 protected Marshaller[] marshallers;
42 protected ClientExecutor executor;
43 protected boolean followRedirects;
44 protected EntityExtractor extractor;
45 protected EntityExtractorFactory extractorFactory;
46 protected URI baseUri;
47 protected Map<String, Object> attributes = new HashMap<String, Object>();
48
49
50 public ClientInvoker(URI baseUri, Class declaring, Method method, ResteasyProviderFactory providerFactory, ClientExecutor executor, EntityExtractorFactory extractorFactory)
51 {
52 this(baseUri, declaring, method, new ProxyConfig(null, executor, providerFactory, extractorFactory, null, null, null));
53 }
54
55 public ClientInvoker(URI baseUri, Class declaring, Method method, ProxyConfig config)
56 {
57 this.declaring = declaring;
58 this.method = method;
59 this.marshallers = ClientMarshallerFactory.createMarshallers(declaring, method, providerFactory, config.getServerConsumes());
60 this.providerFactory = config.getProviderFactory();
61 this.executor = config.getExecutor();
62 accepts = MediaTypeHelper.getProduces(declaring, method, config.getServerProduces());
63 this.uri = new ResteasyUriBuilder();
64 this.baseUri = baseUri;
65 uri.uri(baseUri);
66 if (declaring.isAnnotationPresent(Path.class)) uri.path(declaring);
67 if (method.isAnnotationPresent(Path.class)) uri.path(method);
68 this.extractorFactory = config.getExtractorFactory();
69 this.extractor = extractorFactory.createExtractor(method);
70 }
71
72 public Map<String, Object> getAttributes()
73 {
74 return attributes;
75 }
76
77 public MediaType getAccepts()
78 {
79 return accepts;
80 }
81
82 public Method getMethod()
83 {
84 return method;
85 }
86
87 public Class getDeclaring()
88 {
89 return declaring;
90 }
91
92 public ResteasyProviderFactory getProviderFactory()
93 {
94 return providerFactory;
95 }
96
97 public Object invoke(Object[] args)
98 {
99 boolean isProvidersSet = ResteasyProviderFactory.getContextData(Providers.class) != null;
100 if (!isProvidersSet) ResteasyProviderFactory.pushContext(Providers.class, providerFactory);
101
102 try
103 {
104 if (uri == null) throw new RuntimeException(Messages.MESSAGES.baseURINotSetForClientProxy());
105
106
107 ClientRequest request = createRequest(args);
108
109 BaseClientResponse clientResponse = null;
110 try
111 {
112 clientResponse = (BaseClientResponse) request.httpMethod(httpMethod);
113 }
114 catch (Exception e)
115 {
116 ClientExceptionMapper<Exception> mapper = providerFactory.getClientExceptionMapper(Exception.class);
117 if (mapper != null)
118 {
119 throw mapper.toException(e);
120 }
121 throw new RuntimeException(e);
122 }
123 ClientErrorHandler errorHandler = new ClientErrorHandler(providerFactory.getClientErrorInterceptors());
124 clientResponse.setAttributeExceptionsTo(method.toString());
125 clientResponse.setAnnotations(method.getAnnotations());
126 ClientRequestContext clientRequestContext = new ClientRequestContext(request, clientResponse, errorHandler, extractorFactory, baseUri);
127 return extractor.extractEntity(clientRequestContext);
128 }
129 finally
130 {
131 if (!isProvidersSet) ResteasyProviderFactory.popContextData(Providers.class);
132 }
133 }
134
135 protected ClientRequest createRequest(Object[] args)
136 {
137 ClientRequest request = new ClientRequest(uri, executor, providerFactory);
138 request.getAttributes().putAll(attributes);
139 if (accepts != null) request.header(HttpHeaders.ACCEPT, accepts.toString());
140 this.copyClientInterceptorsTo(request);
141
142 boolean isClientResponseResult = ClientResponse.class.isAssignableFrom(method.getReturnType());
143 request.followRedirects(!isClientResponseResult || this.followRedirects);
144
145 for (int i = 0; i < marshallers.length; i++)
146 {
147 marshallers[i].build(request, args[i]);
148 }
149 return request;
150 }
151
152 public String getHttpMethod()
153 {
154 return httpMethod;
155 }
156
157 public void setHttpMethod(String httpMethod)
158 {
159 this.httpMethod = httpMethod;
160 }
161
162 public boolean isFollowRedirects()
163 {
164 return followRedirects;
165 }
166
167 public void setFollowRedirects(boolean followRedirects)
168 {
169 this.followRedirects = followRedirects;
170 }
171
172 public void followRedirects()
173 {
174 setFollowRedirects(true);
175 }
176 }
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3
4 import java.lang.reflect.Method;
5
6 @SuppressWarnings("unchecked")
7 public class ClientInvokerInterceptorFactory
8 {
9 public static void applyDefaultInterceptors(
10 ClientInterceptorRepositoryImpl repository,
11 ResteasyProviderFactory providerFactory)
12 {
13 applyDefaultInterceptors(repository, providerFactory, null, null);
14 }
15
16 public static void applyDefaultInterceptors(
17 ClientInterceptorRepositoryImpl repository,
18 ResteasyProviderFactory providerFactory, Class declaring, Method method)
19 {
20 repository.setReaderInterceptors(providerFactory
21 .getClientReaderInterceptorRegistry().postMatch(declaring,
22 method));
23 repository.setWriterInterceptors(providerFactory
24 .getClientWriterInterceptorRegistry().postMatch(declaring,
25 method));
26 repository.setExecutionInterceptors(providerFactory
27 .getClientExecutionInterceptorRegistry().bind(declaring, method));
28 }
29
30 }
0 package org.jboss.resteasy.client.core;
1
2 /**
3 * used to modify all of the ClientInvokers of a given ResteasyClientProxy. @see
4 * ResteasyClientProxy.applyClientInvokerModifier
5 *
6 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
7 * @version $Revision: 1 $
8 */
9 public interface ClientInvokerModifier
10 {
11 void modify(ClientInvoker invoker);
12 }
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ProxyBuilder;
3 import org.jboss.resteasy.client.ProxyConfig;
4 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
5
6 import java.lang.reflect.InvocationHandler;
7 import java.lang.reflect.Method;
8 import java.net.URI;
9 import java.util.Map;
10
11 /**
12 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
13 * @version $Revision: 1 $
14 */
15 public class ClientProxy implements InvocationHandler
16 {
17 private Map<Method, MethodInvoker> methodMap;
18 private Class<?> clazz;
19 private final URI base;
20 private final ProxyConfig config;
21
22 public ClientProxy(Map<Method, MethodInvoker> methodMap, URI base, ProxyConfig config)
23 {
24 super();
25 this.methodMap = methodMap;
26 this.base = base;
27 this.config = config;
28 }
29
30 public Class<?> getClazz()
31 {
32 return clazz;
33 }
34
35 public void setClazz(Class<?> clazz)
36 {
37 this.clazz = clazz;
38 }
39
40 public Object invoke(Object o, Method method, Object[] args)
41 throws Throwable
42 {
43 // equals and hashCode were added for cases where the proxy is added to
44 // collections. The Spring transaction management, for example, adds
45 // transactional Resources to a Collection, and it calls equals and
46 // hashCode.
47
48 MethodInvoker clientInvoker = methodMap.get(method);
49 if (clientInvoker == null)
50 {
51 if (method.getName().equals("equals"))
52 {
53 return this.equals(o);
54 }
55 else if (method.getName().equals("hashCode"))
56 {
57 return this.hashCode();
58 }
59 else if (method.getName().equals("toString") && (args == null || args.length == 0))
60 {
61 return this.toString();
62 }
63 else if (method.getName().equals("getResteasyClientInvokers"))
64 {
65 return methodMap.values();
66 }
67 else if (method.getName().equals("applyClientInvokerModifier"))
68 {
69 ClientInvokerModifier modifier = (ClientInvokerModifier) args[0];
70 for (MethodInvoker invoker : methodMap.values())
71 {
72 if(invoker instanceof ClientInvoker)
73 modifier.modify((ClientInvoker)invoker);
74 }
75
76 return null;
77 }
78 else if(method.getName().equals("as") && args.length == 1 && args[0] instanceof Class)
79 {
80 return ProxyBuilder.createProxy((Class<?>)args[0], base, config);
81 }
82 }
83
84 if (clientInvoker == null)
85 {
86 throw new RuntimeException(Messages.MESSAGES.couldNotFindMethod(method));
87 }
88 return clientInvoker.invoke(args);
89 }
90
91 @Override
92 public boolean equals(Object obj)
93 {
94 if (obj == null || !(obj instanceof ClientProxy))
95 return false;
96 ClientProxy other = (ClientProxy) obj;
97 if (other == this)
98 return true;
99 if (other.clazz != this.clazz)
100 return false;
101 return super.equals(obj);
102 }
103
104 @Override
105 public int hashCode()
106 {
107 return clazz.hashCode();
108 }
109
110 public String toString()
111 {
112 return "Client Proxy for :" + clazz.getName();
113 }
114 }
0 package org.jboss.resteasy.client.core;
1
2 public interface MethodInvoker
3 {
4 Object invoke(Object[] args);
5 }
0 package org.jboss.resteasy.client.core;
1
2 import java.io.BufferedInputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
7
8 /**
9 * Extension of {@link BufferedInputStream} enforcing the contract where reset()
10 * always returns to the beginning of the stream, and the internal buffer
11 * expands automatically to the total length of content read from the underlying
12 * stream.
13 *
14 * @author ul8b
15 */
16 public class SelfExpandingBufferredInputStream extends BufferedInputStream
17 {
18 private static int defaultBufferSize = 8192;
19
20 public SelfExpandingBufferredInputStream(InputStream in)
21 {
22 super(in);
23 super.mark(defaultBufferSize);
24 }
25
26 public SelfExpandingBufferredInputStream(InputStream in, int size)
27 {
28 super(in, size);
29 super.mark(size);
30 }
31
32 /**
33 * Not supported. Mark position is always zero.
34 */
35 @Override
36 public synchronized void mark(int readlimit)
37 {
38 throw new UnsupportedOperationException(Messages.MESSAGES.alwaysMarkedAtIndex0());
39 }
40
41 @Override
42 public synchronized int read() throws IOException
43 {
44 if (pos == marklimit)
45 {
46 expand();
47 }
48 return super.read();
49 }
50
51 @Override
52 public synchronized int read(byte[] b, int off, int len) throws IOException
53 {
54 while (pos + len > marklimit)
55 {
56 expand();
57 }
58 return super.read(b, off, len);
59 }
60
61 @Override
62 public synchronized int read(byte[] b) throws IOException
63 {
64 while (pos + b.length > marklimit)
65 {
66 expand();
67 }
68 return super.read(b);
69 }
70
71 /**
72 * Double the current buffer size limit. Reset to zero, then double the
73 * buffer size and restore last position in the buffer.
74 *
75 * @throws IOException
76 */
77 private void expand() throws IOException
78 {
79 int lastPos = pos;
80 super.reset();
81 super.mark((marklimit < (Integer.MAX_VALUE - 8) / 2) ? (marklimit * 2) : (Integer.MAX_VALUE - 8));
82 pos = lastPos;
83 }
84
85 /**
86 * Return the current maximum size of the internal buffer. This is
87 * independent of how much data is actually contained within the buffer.
88 */
89 public int getBufSize()
90 {
91 return buf.length;
92 }
93
94 public int getCount()
95 {
96 return count;
97 }
98
99 public int getPos()
100 {
101 return pos;
102 }
103
104 public int getMarkLimit()
105 {
106 return marklimit;
107 }
108
109 public int getMarkPos()
110 {
111 return markpos;
112 }
113 }
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ProxyBuilder;
3 import org.jboss.resteasy.client.ProxyConfig;
4 import org.jboss.resteasy.client.ProxyFactory;
5
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Method;
10 import java.net.URI;
11
12 public class SubResourceInvoker implements MethodInvoker
13 {
14 final ProxyConfig config;
15 final Class<?> iface;
16 final String base;
17 final String format;
18
19 public SubResourceInvoker(URI uri, Method method, ProxyConfig config)
20 {
21 String base = uri.toString();
22 if (!base.endsWith("/"))
23 base = base + "/";
24 this.base = base;
25 this.iface = method.getReturnType();
26 this.config = config;
27 String path = method.getAnnotation(Path.class).value();
28 if (path.startsWith("/"))
29 path = path.substring(1);
30 Annotation[][] params = method.getParameterAnnotations();
31 int index = 1;
32 for (Annotation[] param : params)
33 {
34 for (Annotation a : param)
35 {
36 if (a instanceof PathParam)
37 {
38 String name = ((PathParam) a).value();
39 path = path.replaceFirst("\\{" + name + "(\\s)*(:.*)?\\}", "%" + index + "\\$s");
40 break;
41 }
42 }
43 index++;
44 }
45 this.format = path;
46 }
47
48 @Override
49 public Object invoke(Object[] args)
50 {
51 String path = String.format(format, args);
52 return ProxyBuilder.createProxy(iface, ProxyFactory.createUri(base + path), config);
53 }
54 }
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.EntityTypeFactory;
3
4 import javax.ws.rs.core.MultivaluedMap;
5
6 public class VoidEntityTypeFactory implements EntityTypeFactory
7 {
8
9 @SuppressWarnings("unchecked")
10 public Class getEntityType(int status,
11 MultivaluedMap<String, Object> metadata)
12 {
13 return Void.class;
14 }
15
16 }
0 package org.jboss.resteasy.client.core.executors;
1
2 import org.apache.commons.io.output.DeferredFileOutputStream;
3 import org.apache.http.Header;
4 import org.apache.http.HttpEntity;
5 import org.apache.http.HttpResponse;
6 import org.apache.http.NameValuePair;
7 import org.apache.http.client.HttpClient;
8 import org.apache.http.client.entity.UrlEncodedFormEntity;
9 import org.apache.http.client.methods.HttpGet;
10 import org.apache.http.client.methods.HttpPost;
11 import org.apache.http.client.methods.HttpRequestBase;
12 import org.apache.http.client.params.HttpClientParams;
13 import org.apache.http.conn.ClientConnectionManager;
14 import org.apache.http.entity.ByteArrayEntity;
15 import org.apache.http.impl.client.DefaultHttpClient;
16 import org.apache.http.entity.FileEntity;
17 import org.apache.http.message.BasicHeader;
18 import org.apache.http.message.BasicNameValuePair;
19 import org.apache.http.protocol.HTTP;
20 import org.apache.http.protocol.HttpContext;
21 import org.jboss.resteasy.client.ClientExecutor;
22 import org.jboss.resteasy.client.ClientRequest;
23 import org.jboss.resteasy.client.ClientResponse;
24 import org.jboss.resteasy.client.core.BaseClientResponse;
25 import org.jboss.resteasy.client.core.BaseClientResponse.BaseClientResponseStreamFactory;
26 import org.jboss.resteasy.client.core.SelfExpandingBufferredInputStream;
27 import org.jboss.resteasy.client.exception.mapper.ApacheHttpClient4ExceptionMapper;
28 import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper;
29 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
30 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
31 import org.jboss.resteasy.spi.ResteasyProviderFactory;
32 import org.jboss.resteasy.util.CaseInsensitiveMap;
33 import org.jboss.resteasy.util.Types;
34
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.core.UriBuilder;
37
38 import java.io.BufferedInputStream;
39 import java.io.ByteArrayOutputStream;
40 import java.io.File;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.lang.management.ManagementFactory;
44 import java.lang.reflect.Type;
45 import java.util.ArrayList;
46 import java.util.List;
47 import java.util.Map;
48
49 /**
50 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
51 * @version $Revision: 1 $
52 */
53 public class ApacheHttpClient4Executor implements ClientExecutor
54 {
55 public static final String BYTE_MEMORY_UNIT = "BY";
56 public static final String KILOBYTE_MEMORY_UNIT = "KB";
57 public static final String MEGABYTE_MEMORY_UNIT = "MB";
58 public static final String GIGABYTE_MEMORY_UNIT = "GB";
59
60 /**
61 * Used to build temp file prefix.
62 */
63 private static String processId = null;
64
65 static
66 {
67 ApacheHttpClient4Executor.processId = ManagementFactory.getRuntimeMXBean().getName().replaceAll("[^0-9a-zA-Z]", "");
68 }
69
70 static synchronized private void checkClientExceptionMapper()
71 {
72 if (ResteasyProviderFactory.getInstance().getClientExceptionMapper(Exception.class) == null)
73 {
74 Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class, ClientExceptionMapper.class)[0];
75 ResteasyProviderFactory.getInstance().addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);
76 }
77 }
78
79 protected HttpClient httpClient;
80 protected boolean createdHttpClient;
81 protected HttpContext httpContext;
82 protected boolean closed;
83
84 /**
85 * For uploading File's over JAX-RS framework, this property, together with {@link #fileUploadMemoryUnit},
86 * defines the maximum File size allowed in memory. If fileSize exceeds this size, it will be stored to
87 * {@link #fileUploadTempFileDir}. <br>
88 * <br>
89 * Defaults to 1 MB
90 */
91 private int fileUploadInMemoryThresholdLimit = 1;
92
93 /**
94 * The unit for {@link #fileUploadInMemoryThresholdLimit}. <br>
95 * <br>
96 * Defaults to MB.
97 *
98 * @see MemoryUnit
99 */
100 private MemoryUnit fileUploadMemoryUnit = MemoryUnit.MB;
101
102 /**
103 * Temp directory to write output request stream to. Any file to be uploaded has to be written out to the
104 * output request stream to be sent to the service and when the File is too huge the output request stream is
105 * written out to the disk rather than to memory. <br>
106 * <br>
107 * Defaults to JVM temp directory.
108 */
109 private File fileUploadTempFileDir = new File(System.getProperty("java.io.tmpdir"));
110 protected int responseBufferSize = 8192;
111
112 public ApacheHttpClient4Executor()
113 {
114 this(new DefaultHttpClient(), null);
115 this.createdHttpClient = true;
116 }
117
118 public ApacheHttpClient4Executor(HttpClient httpClient)
119 {
120 this(httpClient, null);
121 }
122
123 public ApacheHttpClient4Executor(HttpClient httpClient, HttpContext httpContext)
124 {
125 this.httpClient = httpClient;
126 this.httpContext = httpContext;
127 checkClientExceptionMapper();
128 }
129
130 /**
131 * Response stream is wrapped in a BufferedInputStream. Default is 8192. Value of 0 will not wrap it.
132 * Value of -1 will use a SelfExpandingBufferedInputStream
133 *
134 * @return
135 */
136 public int getResponseBufferSize()
137 {
138 return responseBufferSize;
139 }
140
141 /**
142 * Response stream is wrapped in a BufferedInputStream. Default is 8192. Value of 0 will not wrap it.
143 * Value of -1 will use a SelfExpandingBufferedInputStream
144 *
145 * @param responseBufferSize
146 */
147 public void setResponseBufferSize(int responseBufferSize)
148 {
149 this.responseBufferSize = responseBufferSize;
150 }
151
152 public HttpClient getHttpClient()
153 {
154 return httpClient;
155 }
156
157 public HttpContext getHttpContext()
158 {
159 return httpContext;
160 }
161
162 public void setHttpContext(HttpContext httpContext)
163 {
164 this.httpContext = httpContext;
165 }
166
167 public static CaseInsensitiveMap<String> extractHeaders(
168 HttpResponse response)
169 {
170 final CaseInsensitiveMap<String> headers = new CaseInsensitiveMap<String>();
171
172 for (Header header : response.getAllHeaders())
173 {
174 headers.add(header.getName(), header.getValue());
175 }
176 return headers;
177 }
178
179 public ClientRequest createRequest(String uriTemplate)
180 {
181 return new ClientRequest(uriTemplate, this);
182 }
183
184 public ClientRequest createRequest(UriBuilder uriBuilder)
185 {
186 return new ClientRequest(uriBuilder, this);
187 }
188
189 static class ResponseStream extends SelfExpandingBufferredInputStream
190 {
191 BaseClientResponse response;
192
193 public ResponseStream(InputStream in, BaseClientResponse response)
194 {
195 super(in);
196 // Keep a reference to the response object to prevent it being finalized prematurely
197 this.response = response;
198 }
199
200 public synchronized void close() throws IOException
201 {
202 super.close();
203 // Response object is no longer needed and can be finalized
204 response = null;
205 }
206 }
207
208 protected InputStream createBufferedStream(InputStream is)
209 {
210 if (responseBufferSize == 0)
211 {
212 return is;
213 }
214 if (responseBufferSize < 0)
215 {
216 return new SelfExpandingBufferredInputStream(is);
217 }
218 BufferedInputStream bis = new BufferedInputStream(is, responseBufferSize);
219 // mark read limit
220 bis.mark(responseBufferSize);
221 return bis;
222 }
223
224 @SuppressWarnings("unchecked")
225 public ClientResponse execute(ClientRequest request) throws Exception
226 {
227 String uri = request.getUri();
228 final HttpRequestBase httpMethod = createHttpMethod(uri, request.getHttpMethod());
229 try
230 {
231 loadHttpMethod(request, httpMethod);
232
233 final HttpResponse res = httpClient.execute(httpMethod, httpContext);
234
235 final BaseClientResponse response = new BaseClientResponse(null, this);
236 BaseClientResponseStreamFactory sf = new BaseClientResponseStreamFactory()
237 {
238 InputStream stream;
239
240 public InputStream getInputStream() throws IOException
241 {
242 if (stream == null)
243 {
244 HttpEntity entity = res.getEntity();
245 if (entity == null) return null;
246 // stream = new SelfExpandingBufferredInputStream(entity.getContent());
247 stream = createBufferedStream(entity.getContent());
248 }
249 return stream;
250 }
251
252 public void performReleaseConnection()
253 {
254 // Apache Client 4 is stupid, You have to get the InputStream and close it if there is an entity
255 // otherwise the connection is never released. There is, of course, no close() method on response
256 // to make this easier.
257 try
258 {
259 if (stream != null)
260 {
261 stream.close();
262 }
263 else
264 {
265 InputStream is = getInputStream();
266 if (is != null)
267 {
268 is.close();
269 }
270 }
271 }
272 catch (Exception ignore)
273 {
274 }
275 }
276 };
277 response.setStreamFactory(sf);
278 response.setAttributes(request.getAttributes());
279 response.setStatus(res.getStatusLine().getStatusCode());
280 response.setHeaders(extractHeaders(res));
281 response.setProviderFactory(request.getProviderFactory());
282 return response;
283 }
284 finally
285 {
286 cleanUpAfterExecute(httpMethod);
287 }
288 }
289
290 /**
291 * If passed httpMethod is of type HttpPost then obtain its entity. If the entity has an enclosing File then
292 * delete it by invoking this method after the request has completed. The entity will have an enclosing File
293 * only if it was too huge to fit into memory.
294 *
295 * @param httpMethod - the httpMethod to clean up.
296 * @see #writeRequestBodyToOutputStream(ClientRequest)
297 */
298 protected void cleanUpAfterExecute(final HttpRequestBase httpMethod)
299 {
300 if (httpMethod != null && httpMethod instanceof HttpPost)
301 {
302 HttpPost postMethod = (HttpPost) httpMethod;
303 HttpEntity entity = postMethod.getEntity();
304 if (entity != null && entity instanceof FileExposingFileEntity)
305 {
306 File tempRequestFile = ((FileExposingFileEntity) entity).getFile();
307 try
308 {
309 boolean isDeleted = tempRequestFile.delete();
310 if (!isDeleted)
311 {
312 handleFileNotDeletedError(tempRequestFile, null);
313 }
314 }
315 catch (Exception ex)
316 {
317 handleFileNotDeletedError(tempRequestFile, ex);
318 }
319 }
320 }
321 }
322
323 private HttpRequestBase createHttpMethod(String url, String restVerb)
324 {
325 if ("GET".equals(restVerb))
326 {
327 return new HttpGet(url);
328 }
329 else if ("POST".equals(restVerb))
330 {
331 return new HttpPost(url);
332 }
333 else
334 {
335 final String verb = restVerb;
336 return new HttpPost(url)
337 {
338 @Override
339 public String getMethod()
340 {
341 return verb;
342 }
343 };
344 }
345 }
346
347 public void loadHttpMethod(final ClientRequest request, HttpRequestBase httpMethod) throws Exception
348 {
349 if (httpMethod instanceof HttpGet && request.followRedirects())
350 {
351 HttpClientParams.setRedirecting(httpMethod.getParams(), true);
352 }
353 else
354 {
355 HttpClientParams.setRedirecting(httpMethod.getParams(), false);
356 }
357
358 if (request.getBody() != null && !request.getFormParameters().isEmpty())
359 throw new RuntimeException(Messages.MESSAGES.cannotSendFormParametersAndEntity());
360
361 if (!request.getFormParameters().isEmpty())
362 {
363 commitHeaders(request, httpMethod);
364 HttpPost post = (HttpPost) httpMethod;
365
366 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
367
368 for (Map.Entry<String, List<String>> formParam : request.getFormParameters().entrySet())
369 {
370 List<String> values = formParam.getValue();
371 for (String value : values)
372 {
373 formparams.add(new BasicNameValuePair(formParam.getKey(), value));
374 }
375 }
376
377 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
378 post.setEntity(entity);
379 }
380 else if (request.getBody() != null)
381 {
382 if (httpMethod instanceof HttpGet) throw new RuntimeException(Messages.MESSAGES.getRequestCannotHaveBody());
383
384 try
385 {
386 HttpEntity entity = buildEntity(request);
387 HttpPost post = (HttpPost) httpMethod;
388 commitHeaders(request, httpMethod);
389 post.setEntity(entity);
390 }
391 catch (IOException e)
392 {
393 throw new RuntimeException(e);
394 }
395 }
396 else // no body
397 {
398 commitHeaders(request, httpMethod);
399 }
400 }
401
402 /**
403 * Build the HttpEntity to be sent to the Service as part of (POST) request. Creates a off-memory
404 * {@link FileExposingFileEntity} or a regular in-memory {@link ByteArrayEntity} depending on if the request
405 * OutputStream fit into memory when built by calling {@link #writeRequestBodyToOutputStream(ClientRequest)}.
406 *
407 * @param request -
408 * @return - the built HttpEntity
409 * @throws IOException -
410 */
411 protected HttpEntity buildEntity(final ClientRequest request) throws IOException
412 {
413 HttpEntity entityToBuild = null;
414 DeferredFileOutputStream memoryManagedOutStream = writeRequestBodyToOutputStream(request);
415
416 if (memoryManagedOutStream.isInMemory())
417 {
418 ByteArrayEntity entityToBuildByteArray = new ByteArrayEntity(memoryManagedOutStream.getData());
419 entityToBuildByteArray.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, request.getBodyContentType().toString()));
420 entityToBuild = entityToBuildByteArray;
421 }
422 else
423 {
424 entityToBuild = new FileExposingFileEntity(memoryManagedOutStream.getFile(), request.getBodyContentType().toString());
425 }
426
427 return entityToBuild;
428 }
429
430 /**
431 * Creates the request OutputStream, to be sent to the end Service invoked, as a
432 * <a href="http://commons.apache.org/io/api-release/org/apache/commons/io/output/DeferredFileOutputStream.html"
433 * >DeferredFileOutputStream</a>.
434 *
435 * @param request -
436 * @return - DeferredFileOutputStream with the ClientRequest written out per HTTP specification.
437 * @throws IOException -
438 */
439 private DeferredFileOutputStream writeRequestBodyToOutputStream(final ClientRequest request) throws IOException
440 {
441 DeferredFileOutputStream memoryManagedOutStream =
442 new DeferredFileOutputStream(this.fileUploadInMemoryThresholdLimit * getMemoryUnitMultiplier(),
443 getTempfilePrefix(), ".tmp", this.fileUploadTempFileDir);
444 request.writeRequestBody(request.getHeadersAsObjects(), memoryManagedOutStream);
445 memoryManagedOutStream.close();
446 return memoryManagedOutStream;
447 }
448
449 /**
450 * @return - the constant to multiply {@link #fileUploadInMemoryThresholdLimit} with based on
451 * {@link #fileUploadMemoryUnit} enumeration value.
452 */
453 private int getMemoryUnitMultiplier()
454 {
455 switch (this.fileUploadMemoryUnit)
456 {
457 case BY:
458 return 1;
459 case KB:
460 return 1024;
461 case MB:
462 return 1024 * 1024;
463 case GB:
464 return 1024 * 1024 * 1024;
465 }
466 return 1;
467 }
468
469 /**
470 * Use context information, which will include node name, to avoid conflicts in case of multiple VMS using same
471 * temp directory location.
472 *
473 * @return -
474 */
475 protected String getTempfilePrefix()
476 {
477 return ApacheHttpClient4Executor.processId;
478 }
479
480 /**
481 * Log that the file did not get deleted but prevent the request from failing by eating the exception.
482 * Register the file to be deleted on exit, so it will get deleted eventually.
483 *
484 * @param tempRequestFile -
485 * @param ex - a null may be passed in which case this param gets ignored.
486 */
487 private void handleFileNotDeletedError(File tempRequestFile, Exception ex)
488 {
489 LogMessages.LOGGER.couldNotDeleteFile(tempRequestFile.getAbsolutePath(), ex);
490 tempRequestFile.deleteOnExit();
491 }
492
493 /**
494 * Setter for the {@link HttpClient} to which this class delegates the actual HTTP call. Note that this class
495 * acts as the adapter between RestEasy and Apache HTTP Component library.
496 *
497 * @param pHttpClient -
498 */
499 void setHttpClient(HttpClient pHttpClient)
500 {
501 this.httpClient = pHttpClient;
502 }
503
504 /**
505 * Setter for {@link #fileUploadInMemoryThresholdLimit}
506 *
507 * @param pInMemoryThresholdLimit - the inMemoryThresholdLimitMB to set
508 */
509 public void setFileUploadInMemoryThresholdLimit(int pInMemoryThresholdLimit)
510 {
511 this.fileUploadInMemoryThresholdLimit = pInMemoryThresholdLimit;
512 }
513
514 /**
515 * Setter for {@link #fileUploadTempFileDir}
516 *
517 * @param pTempFileDir the tempFileDir to set
518 */
519 public void setFileUploadTempFileDir(File pTempFileDir)
520 {
521 this.fileUploadTempFileDir = pTempFileDir;
522 }
523
524 /**
525 * Setter for {@link #fileUploadMemoryUnit}
526 *
527 * @param pMemoryUnit the memoryUnit to set
528 */
529 public void setFileUploadMemoryUnit(String pMemoryUnit)
530 {
531 this.fileUploadMemoryUnit = MemoryUnit.valueOf(pMemoryUnit);
532 }
533
534 public void commitHeaders(ClientRequest request, HttpRequestBase httpMethod)
535 {
536 MultivaluedMap<String, String> headers = request.getHeaders();
537 for (Map.Entry<String, List<String>> header : headers.entrySet())
538 {
539 List<String> values = header.getValue();
540 for (String value : values)
541 {
542 // System.out.println(String.format("setting %s = %s", header.getKey(), value));
543 httpMethod.addHeader(header.getKey(), value);
544 }
545 }
546 }
547
548 public void close()
549 {
550 if (closed)
551 return;
552
553 if (createdHttpClient && httpClient != null)
554 {
555 ClientConnectionManager manager = httpClient.getConnectionManager();
556 if (manager != null)
557 {
558 manager.shutdown();
559 }
560 }
561 closed = true;
562 }
563
564 public boolean isClosed()
565 {
566 return closed;
567 }
568
569 public void finalize() throws Throwable
570 {
571 close();
572 super.finalize();
573 }
574
575 /**
576 * We use {@link FileEntity} as the {@link HttpEntity} implementation when the request OutputStream has been
577 * saved to a File on disk (because it was too large to fit into memory see
578 * {@link RestCFHttpClientExecutor#writeRequestBodyToOutputStream(ClientRequest)}); however, we have to delete
579 * the File supporting the <code>FileEntity</code>, otherwise the disk will soon run out of space - remember
580 * that there can be very huge files, in GB range, processed on a regular basis - and FileEntity exposes its
581 * content File as a protected field. For the enclosing parent class ( {@link ApacheHttpClient4Executor} ) to be
582 * able to get a handle to this content File and delete it, this class expose the content File.<br>
583 * This class is private scoped to prevent access to this content File outside of the parent class.
584 *
585 * @author <a href="mailto:stikoo@digitalriver.com">Sandeep Tikoo</a>
586 */
587 private static class FileExposingFileEntity extends FileEntity
588 {
589 /**
590 * @param pFile -
591 * @param pContentType -
592 */
593 public FileExposingFileEntity(File pFile, String pContentType)
594 {
595 super(pFile, pContentType);
596 }
597
598 /**
599 * @return - the content File enclosed by this FileEntity.
600 */
601 File getFile()
602 {
603 return this.file;
604 }
605 }
606
607 /**
608 * Enumeration to represent memory units.
609 */
610 private static enum MemoryUnit
611 {
612 /**
613 * Bytes
614 */
615 BY,
616 /**
617 * Killo Bytes
618 */
619 KB,
620
621 /**
622 * Mega Bytes
623 */
624 MB,
625
626 /**
627 * Giga Bytes
628 */
629 GB
630 }
631 }
0 package org.jboss.resteasy.client.core.executors;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.core.BaseClientResponse;
6 import org.jboss.resteasy.client.core.BaseClientResponse.BaseClientResponseStreamFactory;
7 import org.jboss.resteasy.core.Dispatcher;
8 import org.jboss.resteasy.core.SynchronousDispatcher;
9 import org.jboss.resteasy.core.SynchronousExecutionContext;
10 import org.jboss.resteasy.mock.MockHttpRequest;
11 import org.jboss.resteasy.mock.MockHttpResponse;
12 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
13 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
14 import org.jboss.resteasy.spi.Registry;
15 import org.jboss.resteasy.spi.ResteasyProviderFactory;
16
17 import javax.ws.rs.core.HttpHeaders;
18 import javax.ws.rs.core.MediaType;
19 import javax.ws.rs.core.MultivaluedMap;
20 import javax.ws.rs.core.UriBuilder;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.URI;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31
32 /**
33 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
34 * @version $Revision: 1 $
35 */
36 @SuppressWarnings("unchecked")
37 public class InMemoryClientExecutor implements ClientExecutor
38 {
39 protected Dispatcher dispatcher;
40 protected URI baseUri;
41
42 public InMemoryClientExecutor()
43 {
44 dispatcher = new SynchronousDispatcher(ResteasyProviderFactory.getInstance());
45 }
46
47 public InMemoryClientExecutor(Dispatcher dispatcher)
48 {
49 this.dispatcher = dispatcher;
50 }
51
52 public URI getBaseUri()
53 {
54 return baseUri;
55 }
56
57 public void setBaseUri(URI baseUri)
58 {
59 this.baseUri = baseUri;
60 }
61
62 public ClientRequest createRequest(String uriTemplate)
63 {
64 return new ClientRequest(uriTemplate, this);
65 }
66
67 public ClientRequest createRequest(UriBuilder uriBuilder)
68 {
69 return new ClientRequest(uriBuilder, this);
70 }
71
72
73 public ClientResponse execute(ClientRequest request) throws Exception
74 {
75 MockHttpRequest mockHttpRequest = MockHttpRequest.create(request.getHttpMethod(), new URI(request.getUri()),
76 baseUri);
77 final MockHttpResponse mockResponse = new MockHttpResponse();
78 mockHttpRequest.setAsynchronousContext(new SynchronousExecutionContext((SynchronousDispatcher)dispatcher, mockHttpRequest, mockResponse));
79 loadHttpMethod(request, mockHttpRequest);
80
81 dispatcher.invoke(mockHttpRequest, mockResponse);
82 return createResponse(request, mockResponse);
83 }
84
85 protected BaseClientResponse createResponse(ClientRequest request, final MockHttpResponse mockResponse)
86 {
87 BaseClientResponseStreamFactory streamFactory = createStreamFactory(mockResponse);
88 BaseClientResponse response = new BaseClientResponse(streamFactory, this);
89 response.setStatus(mockResponse.getStatus());
90 setHeaders(mockResponse, response);
91 response.setProviderFactory(request.getProviderFactory());
92 response.setAttributes(request.getAttributes());
93 return response;
94 }
95
96 protected void setHeaders(final MockHttpResponse mockResponse, BaseClientResponse response)
97 {
98 MultivaluedMapImpl<String, String> responseHeaders = new MultivaluedMapImpl<String, String>();
99 for (Entry<String, List<Object>> entry : mockResponse.getOutputHeaders().entrySet())
100 {
101 List<String> values = new ArrayList<String>(entry.getValue().size());
102 for (Object value : entry.getValue())
103 {
104 values.add(value.toString());
105 }
106 responseHeaders.addMultiple(entry.getKey(), values);
107 }
108 response.setHeaders(responseHeaders);
109 }
110
111 public static BaseClientResponseStreamFactory createStreamFactory(final MockHttpResponse mockResponse)
112 {
113 return new BaseClientResponseStreamFactory()
114 {
115 InputStream stream;
116
117 public InputStream getInputStream() throws IOException
118 {
119 if (stream == null)
120 {
121 stream = new ByteArrayInputStream(mockResponse.getOutput());
122 }
123 return stream;
124 }
125
126 public void performReleaseConnection()
127 {
128 }
129 };
130 }
131
132 public void loadHttpMethod(ClientRequest request, MockHttpRequest mockHttpRequest) throws Exception
133 {
134 // TODO: punt on redirects, for now.
135 // if (httpMethod instanceof GetMethod && request.followRedirects())
136 // httpMethod.setFollowRedirects(true);
137 // else httpMethod.setFollowRedirects(false);
138
139 if (request.getBody() != null && !request.getFormParameters().isEmpty())
140 throw new RuntimeException(Messages.MESSAGES.cannotSendFormParametersAndEntity());
141
142 if (!request.getFormParameters().isEmpty())
143 {
144 commitHeaders(request, mockHttpRequest);
145 for (Map.Entry<String, List<String>> formParam : request.getFormParameters().entrySet())
146 {
147 String key = formParam.getKey();
148 for (String value : formParam.getValue())
149 {
150 mockHttpRequest.getFormParameters().add(key, value);
151 }
152 }
153 }
154 else if (request.getBody() != null)
155 {
156 ByteArrayOutputStream baos = new ByteArrayOutputStream();
157
158 MediaType bodyContentType = request.getBodyContentType();
159 request.getHeadersAsObjects().add(HttpHeaders.CONTENT_TYPE, bodyContentType.toString());
160
161 request.writeRequestBody(request.getHeadersAsObjects(), baos);
162 // commit headers after byte array is complete.
163 commitHeaders(request, mockHttpRequest);
164 mockHttpRequest.content(baos.toByteArray());
165 mockHttpRequest.contentType(bodyContentType);
166 }
167 else
168 {
169 commitHeaders(request, mockHttpRequest);
170 }
171 }
172
173 public void commitHeaders(ClientRequest request, MockHttpRequest mockHttpRequest)
174 {
175 MultivaluedMap headers = mockHttpRequest.getHttpHeaders().getRequestHeaders();
176 headers.putAll(request.getHeaders());
177 }
178
179 private void setBody(ClientRequest request, MockHttpRequest mockHttpRequest) throws IOException
180 {
181 if (request.getBody() == null)
182 return;
183
184 }
185
186 public Registry getRegistry()
187 {
188 return this.dispatcher.getRegistry();
189 }
190
191 public Dispatcher getDispatcher()
192 {
193 return dispatcher;
194 }
195
196 public void close()
197 {
198 // empty
199 }
200
201 }
0 package org.jboss.resteasy.client.core.executors;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.core.BaseClientResponse;
6 import org.jboss.resteasy.client.core.BaseClientResponse.BaseClientResponseStreamFactory;
7 import org.jboss.resteasy.util.CaseInsensitiveMap;
8 import org.jboss.resteasy.util.CommitHeaderOutputStream;
9
10 import javax.ws.rs.core.MultivaluedMap;
11 import javax.ws.rs.core.UriBuilder;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.OutputStream;
15 import java.net.HttpURLConnection;
16 import java.net.ProtocolException;
17 import java.net.URL;
18 import java.util.List;
19 import java.util.Map.Entry;
20
21 import static org.jboss.resteasy.util.HttpHeaderNames.*;
22
23 public class URLConnectionClientExecutor implements ClientExecutor
24 {
25
26 public ClientResponse<?> execute(ClientRequest request) throws Exception
27 {
28 HttpURLConnection connection = createConnection(request);
29 return execute(request, connection);
30 }
31
32 private void commitHeaders(ClientRequest request, HttpURLConnection connection)
33 {
34 for (Entry<String, List<String>> entry : request.getHeaders().entrySet())
35 {
36 String value = null;
37 if (entry.getValue().size() == 1)
38 value = entry.getValue().get(0);
39 else
40 {
41 StringBuilder b = new StringBuilder();
42 String add = "";
43 for (String v : entry.getValue())
44 {
45 b.append(add).append(v);
46 add = ",";
47 }
48 value = b.toString();
49 }
50 connection.addRequestProperty(entry.getKey(), value);
51 }
52 }
53
54 public ClientRequest createRequest(String uriTemplate)
55 {
56 return new ClientRequest(uriTemplate, this);
57 }
58
59 public ClientRequest createRequest(UriBuilder uriBuilder)
60 {
61 return new ClientRequest(uriBuilder, this);
62 }
63
64 protected HttpURLConnection createConnection(ClientRequest request) throws Exception
65 {
66 String uri = request.getUri();
67 String httpMethod = request.getHttpMethod();
68
69 HttpURLConnection connection = (HttpURLConnection) new URL(uri).openConnection();
70 connection.setRequestMethod(httpMethod);
71 return connection;
72 }
73
74 private <T> ClientResponse<T> execute(ClientRequest request, final HttpURLConnection connection) throws IOException
75 {
76 outputBody(request, connection);
77 final int status = connection.getResponseCode();
78 BaseClientResponse<T> response = new BaseClientResponse<T>(new BaseClientResponseStreamFactory()
79 {
80 public InputStream getInputStream() throws IOException
81 {
82 return (status < 300) ? connection.getInputStream() : connection.getErrorStream();
83 }
84
85 public void performReleaseConnection()
86 {
87 try
88 {
89 getInputStream().close();
90 }
91 catch (IOException e)
92 {
93 }
94 connection.disconnect();
95 }
96 }, this);
97 response.setProviderFactory(request.getProviderFactory());
98 response.setStatus(status);
99 response.setHeaders(getHeaders(connection));
100 response.setAttributes(request.getAttributes());
101 return response;
102 }
103
104 public void close()
105 {
106 // empty
107 }
108
109 private MultivaluedMap<String, String> getHeaders(
110 final HttpURLConnection connection)
111 {
112 MultivaluedMap<String, String> headers = new CaseInsensitiveMap<String>();
113
114 for (Entry<String, List<String>> header : connection.getHeaderFields()
115 .entrySet())
116 {
117 if (header.getKey() != null)
118 for (String value : header.getValue())
119 headers.add(header.getKey(), value);
120 }
121 return headers;
122 }
123
124 private void outputBody(final ClientRequest request, final HttpURLConnection connection)
125 {
126 if (request.getBody() != null)
127 {
128 // System.out.println(request.getBody());
129 if (connection.getRequestProperty(CONTENT_TYPE) == null)
130 {
131 String type = request.getBodyContentType().toString();
132 connection.addRequestProperty(CONTENT_TYPE, type);
133 }
134 try
135 {
136 final CommitHeaderOutputStream commit = new CommitHeaderOutputStream();
137 CommitHeaderOutputStream.CommitCallback callback = new CommitHeaderOutputStream.CommitCallback()
138 {
139 @Override
140 public void commit()
141 {
142 connection.setDoOutput(true);
143 commitHeaders(request, connection);
144 OutputStream os = null;
145 try
146 {
147 os = connection.getOutputStream();
148 }
149 catch (IOException e)
150 {
151 throw new RuntimeException(e);
152 }
153 commit.setDelegate(os);
154
155 }
156 };
157 commit.setHeaders(callback);
158 try
159 {
160 request.writeRequestBody(request.getHeadersAsObjects(), commit);
161 }
162 finally
163 {
164 commit.getDelegate().flush();
165 commit.getDelegate().close();
166 }
167 }
168 catch (IOException e)
169 {
170 throw new RuntimeException(e);
171 }
172 }
173 else
174 {
175 commitHeaders(request, connection);
176 }
177 }
178 }
0 /**
1 *
2 */
3 package org.jboss.resteasy.client.core.extractors;
4
5 import org.jboss.resteasy.client.ClientResponseFailure;
6 import org.jboss.resteasy.client.core.BaseClientResponse;
7 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
8
9 import javax.ws.rs.ext.MessageBodyReader;
10
11 import java.io.InputStream;
12 import java.lang.reflect.Method;
13
14 /**
15 * BodyEntityExtractor extract body objects from responses. This ends up calling
16 * the appropriate MessageBodyReader through a series of calls
17 *
18 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
19 * @version $Revision: 1 $
20 * @see EntityExtractorFactory
21 * @see MessageBodyReader
22 */
23 @SuppressWarnings("unchecked")
24 public class BodyEntityExtractor implements EntityExtractor
25 {
26 private final Method method;
27
28 public BodyEntityExtractor(Method method)
29 {
30 this.method = method;
31 }
32
33 public Object extractEntity(ClientRequestContext context, Object... args)
34 {
35 final BaseClientResponse response = context.getClientResponse();
36 try
37 {
38 response.checkFailureStatus();
39 }
40 catch (ClientResponseFailure ce)
41 {
42 // If ClientResponseFailure do a copy of the response and then release the connection,
43 // we need to use the copy here and not the original response
44 context.getErrorHandler().clientErrorHandling((BaseClientResponse) ce.getResponse(), ce);
45 }
46 catch (RuntimeException e)
47 {
48 context.getErrorHandler().clientErrorHandling(response, e);
49 }
50
51 // only release connection if it is not an instance of an
52 // InputStream
53 boolean releaseConnectionAfter = true;
54 try
55 {
56 // void methods should be handled before this method gets called, but it's worth being defensive
57 if (method.getReturnType() == null)
58 {
59 // throw new RuntimeException(
60 // "No type information to extract entity with. You use other getEntity() methods");
61 throw new RuntimeException(Messages.MESSAGES.noTypeInformationForEntity());
62 }
63 Object obj = response.getEntity(method.getReturnType(), method.getGenericReturnType());
64 if (obj instanceof InputStream)
65 {
66 releaseConnectionAfter = false;
67 // we make sure that on GC, the Response does not release the InputStream
68 response.setWasReleased(true);
69 }
70 return obj;
71 }
72 catch (RuntimeException e)
73 {
74 context.getErrorHandler().clientErrorHandling(response, e);
75 }
76 finally
77 {
78 if (releaseConnectionAfter)
79 response.releaseConnection();
80 }
81 throw new RuntimeException(Messages.MESSAGES.shouldBeUnreachable());
82 }
83 }
0 package org.jboss.resteasy.client.core.extractors;
1
2 import org.jboss.resteasy.client.core.BaseClientResponse;
3 import org.jboss.resteasy.client.core.ClientErrorInterceptor;
4
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.util.List;
8
9 /**
10 * This class handles client errors (of course...).
11 *
12 * @author Solomon.Duskis
13 */
14
15 // TODO: expand this class for more robust, complicated error handling
16
17 public class ClientErrorHandler
18 {
19 private List<ClientErrorInterceptor> interceptors;
20
21 public ClientErrorHandler(List<ClientErrorInterceptor> interceptors)
22 {
23 this.interceptors = interceptors;
24 }
25
26 @SuppressWarnings("unchecked")
27 public void clientErrorHandling(BaseClientResponse clientResponse, RuntimeException e)
28 {
29 for (ClientErrorInterceptor handler : interceptors)
30 {
31 try
32 {
33 // attempt to reset the stream in order to provide a fresh stream
34 // to each ClientErrorInterceptor -- failing to reset the stream
35 // could mean that an unusable stream will be passed to the
36 // interceptor
37 InputStream stream = clientResponse.getStreamFactory().getInputStream();
38 if (stream != null)
39 {
40 stream.reset();
41 }
42 }
43 catch (IOException e1)
44 {
45 // eat this exception since it's not really relevant for the client
46 // response
47 }
48 handler.handle(clientResponse);
49 }
50 throw e;
51 }
52 }
0 package org.jboss.resteasy.client.core.extractors;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.core.BaseClientResponse;
4
5 import java.net.URI;
6
7 public class ClientRequestContext
8 {
9 private ClientRequest request;
10 private BaseClientResponse<?> clientResponse;
11 private ClientErrorHandler errorHandler;
12 private EntityExtractorFactory extractorFactory;
13 private URI baseURI;
14
15 public ClientRequestContext(ClientRequest request, BaseClientResponse<?> clientResponse,
16 ClientErrorHandler errorHandler, EntityExtractorFactory extractorFactory, URI baseURI)
17 {
18 this.request = request;
19 this.clientResponse = clientResponse;
20 this.errorHandler = errorHandler;
21 this.extractorFactory = extractorFactory;
22 this.baseURI = baseURI;
23 }
24
25 public ClientRequest getRequest()
26 {
27 return request;
28 }
29
30 public BaseClientResponse getClientResponse()
31 {
32 return clientResponse;
33 }
34
35 public ClientErrorHandler getErrorHandler()
36 {
37 return errorHandler;
38 }
39
40 public EntityExtractorFactory getExtractorFactory()
41 {
42 return extractorFactory;
43 }
44
45 public URI getBaseURI()
46 {
47 return baseURI;
48 }
49 }
0 package org.jboss.resteasy.client.core.extractors;
1
2 import java.lang.reflect.InvocationHandler;
3 import java.lang.reflect.Method;
4 import java.util.Map;
5
6 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
7
8 /**
9 * Implement a client proxy for ProxyFactory. This class implements each method
10 * using an EntityExtractor
11 *
12 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
13 * @version $Revision: 1 $
14 * @see ProxyFactory
15 * @see EntityExtractor
16 * @see EntityExtractorFactory
17 * @see ResponseObjectEntityExtractorFactory
18 */
19 @SuppressWarnings("unchecked")
20 public class ClientResponseProxy implements InvocationHandler
21 {
22 private ClientRequestContext context;
23 private Map<Method, EntityExtractor<?>> methodMap;
24 private Class<?> clazz;
25
26 public ClientResponseProxy(ClientRequestContext context, Map<Method, EntityExtractor<?>> methodMap, Class<?> clazz)
27 {
28 super();
29 this.methodMap = methodMap;
30 this.clazz = clazz;
31 this.context = context;
32 }
33
34 public Object invoke(Object o, Method method, Object[] args) throws Throwable
35 {
36 // equals and hashCode were added for cases where the proxy is added to
37 // collections. The Spring transaction management, for example, adds
38 // transactional Resources to a Collection, and it calls equals and
39 // hashCode.
40 if (method.getName().equals("equals"))
41 {
42 return this.equals(o);
43 }
44 else if (method.getName().equals("hashCode"))
45 {
46 return this.hashCode();
47 }
48
49 EntityExtractor entityExtractor = methodMap.get(method);
50 if (entityExtractor == null)
51 throw new RuntimeException(Messages.MESSAGES.couldNotProcessMethod(method));
52
53 return entityExtractor.extractEntity(context, entityExtractor, args);
54 }
55
56 @Override
57 public boolean equals(Object obj)
58 {
59 if (obj == null || !(obj instanceof ClientResponseProxy))
60 return false;
61 ClientResponseProxy other = (ClientResponseProxy) obj;
62 if (other == this)
63 return true;
64 if (other.clazz != this.clazz)
65 return false;
66 return super.equals(obj);
67 }
68
69 @Override
70 public int hashCode()
71 {
72 return clazz.hashCode();
73 }
74
75 public String toString()
76 {
77 return "Client Proxy for :" + clazz.getName();
78 }
79 }
0 package org.jboss.resteasy.client.core.extractors;
1
2 import org.jboss.resteasy.annotations.ClientResponseType;
3 import org.jboss.resteasy.annotations.ResponseObject;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.ClientResponseFailure;
6 import org.jboss.resteasy.client.EntityTypeFactory;
7 import org.jboss.resteasy.client.core.BaseClientResponse;
8 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
9 import org.jboss.resteasy.util.Types;
10
11 import javax.ws.rs.core.Response;
12
13 import java.lang.reflect.Method;
14 import java.lang.reflect.ParameterizedType;
15 import java.lang.reflect.Type;
16
17 /**
18 * @author Solomon.Duskis
19 */
20 @SuppressWarnings("unchecked")
21 public class DefaultEntityExtractorFactory implements EntityExtractorFactory
22 {
23
24 public static final EntityExtractor clientResponseExtractor = new EntityExtractor<ClientResponse>()
25 {
26 public ClientResponse extractEntity(ClientRequestContext context, Object... args)
27 {
28 return context.getClientResponse();
29 }
30 };
31
32 public static EntityExtractor<Response.Status> createStatusExtractor(final boolean release)
33 {
34 return new EntityExtractor<Response.Status>()
35 {
36 public Response.Status extractEntity(ClientRequestContext context, Object... args)
37 {
38 if (release)
39 context.getClientResponse().releaseConnection();
40 return context.getClientResponse().getResponseStatus();
41 }
42 };
43 }
44
45 public static final EntityExtractor createVoidExtractor(final boolean release)
46 {
47 return new EntityExtractor()
48 {
49 public Object extractEntity(ClientRequestContext context, Object... args)
50 {
51 try
52 {
53 context.getClientResponse().checkFailureStatus();
54 }
55 catch (ClientResponseFailure ce)
56 {
57 // If ClientResponseFailure do a copy of the response and then release the connection,
58 // we need to use the copy here and not the original response
59 context.getErrorHandler().clientErrorHandling((BaseClientResponse) ce.getResponse(), ce);
60 }
61 catch (RuntimeException e)
62 {
63 context.getErrorHandler().clientErrorHandling(context.getClientResponse(), e);
64 }
65 if (release)
66 context.getClientResponse().releaseConnection();
67 return null;
68 }
69 };
70 }
71
72 public EntityExtractor createExtractor(final Method method)
73 {
74 final Class returnType = method.getReturnType();
75 if (isVoidReturnType(returnType))
76 return createVoidExtractor(true);
77 if (returnType.equals(Response.Status.class))
78 return createStatusExtractor(true);
79
80 if (Response.class.isAssignableFrom(returnType))
81 return createResponseTypeEntityExtractor(method);
82
83 if (returnType.isInterface() && returnType.isAnnotationPresent(ResponseObject.class))
84 return new ResponseObjectProxy(method, new ResponseObjectEntityExtractorFactory());
85
86 // We are not a ClientResponse type so we need to unmarshall and narrow it
87 // to right type. If we are unable to unmarshall, or encounter any kind of
88 // Exception, give the ClientErrorHandlers a chance to handle the
89 // ClientResponse manually.
90
91 return new BodyEntityExtractor(method);
92 }
93
94 protected EntityExtractor createResponseTypeEntityExtractor(final Method method)
95 {
96 final ClientResponseType responseHint = method.getAnnotation(ClientResponseType.class);
97 if (responseHint != null)
98 {
99 final Class responseHintReturnType = responseHint.entityType();
100 if (isVoidReturnType(responseHintReturnType))
101 {
102 final Class<? extends EntityTypeFactory> entityTypeFactory = responseHint.entityTypeFactory();
103 return new EntityExtractor()
104 {
105 public Object extractEntity(ClientRequestContext context, Object... args)
106 {
107 EntityTypeFactory factory = null;
108 try
109 {
110 factory = entityTypeFactory.newInstance();
111 }
112 catch (InstantiationException e)
113 {
114 throw context.getClientResponse().createResponseFailure(Messages.MESSAGES.couldNotCreateEntityFactory(entityTypeFactory.getClass().getName()));
115 }
116 catch (IllegalAccessException e)
117 {
118 throw ((BaseClientResponse<?>)context.getClientResponse())
119 .createResponseFailure(Messages.MESSAGES.couldNotCreateEntityFactoryMessage(entityTypeFactory.getClass().getName(), e.getMessage()));
120 }
121 context.getClientResponse().setReturnType(
122 factory.getEntityType(((BaseClientResponse<?>) context.getClientResponse()).getStatus(),
123 ((BaseClientResponse<?>) context.getClientResponse()).getMetadata()));
124 return context.getClientResponse();
125 }
126 };
127 }
128 else
129 {
130 return new EntityExtractor()
131 {
132 public Object extractEntity(ClientRequestContext context, Object... args)
133 {
134 context.getClientResponse().setReturnType(responseHintReturnType);
135 return context.getClientResponse();
136 }
137 };
138 }
139 }
140 else
141 {
142 final Type methodGenericReturnType = method.getGenericReturnType();
143 if (methodGenericReturnType instanceof ParameterizedType)
144 {
145 final ParameterizedType zType = (ParameterizedType) methodGenericReturnType;
146 final Type genericReturnType = zType.getActualTypeArguments()[0];
147 final Class<?> responseReturnType = Types.getRawType(genericReturnType);
148 return new EntityExtractor()
149 {
150 public Object extractEntity(ClientRequestContext context, Object... args)
151 {
152 context.getClientResponse().setReturnType(responseReturnType);
153 context.getClientResponse().setGenericReturnType(genericReturnType);
154 return context.getClientResponse();
155 }
156 };
157 }
158 else
159 return clientResponseExtractor;
160 }
161 }
162
163 public static final boolean isVoidReturnType(Class<?> returnType)
164 {
165 return returnType == null || void.class.equals(returnType) || Void.class.equals(returnType);
166 }
167
168 }
0 package org.jboss.resteasy.client.core.extractors;
1
2
3 /**
4 * EntityExtractor extract objects from responses. An extractor can extract a
5 * status, a header, a cookie, the response body, the clientRequest object, the
6 * clientResponse object, or anything else that a "response object" might need.
7 *
8 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
9 * @version $Revision: 1 $
10 * @see EntityExtractorFactory
11 */
12 public interface EntityExtractor<T>
13 {
14 T extractEntity(ClientRequestContext context, Object... args);
15 }
0 package org.jboss.resteasy.client.core.extractors;
1
2 import java.lang.reflect.Method;
3
4 /**
5 * Create an EntityExtractor based on a method. This will allow different
6 * factories to be used for different purposes, including custom user driven
7 * factories.
8 *
9 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
10 * @version $Revision: 1 $
11 * @see EntityExtractor, DefaultObjectEntityExtractor,
12 * ResponseObjectEntityExtractor
13 */
14 public interface EntityExtractorFactory
15 {
16 @SuppressWarnings("unchecked")
17 public EntityExtractor createExtractor(Method method);
18 }
0 package org.jboss.resteasy.client.core.extractors;
1
2 import org.jboss.resteasy.annotations.Body;
3 import org.jboss.resteasy.annotations.LinkHeaderParam;
4 import org.jboss.resteasy.annotations.Status;
5 import org.jboss.resteasy.client.ClientExecutor;
6 import org.jboss.resteasy.client.ClientRequest;
7 import org.jboss.resteasy.client.ProxyFactory;
8 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
9 import org.jboss.resteasy.spi.Link;
10 import org.jboss.resteasy.spi.LinkHeader;
11 import org.jboss.resteasy.spi.ResteasyProviderFactory;
12 import org.jboss.resteasy.util.IsHttpMethod;
13
14 import javax.ws.rs.HeaderParam;
15 import javax.ws.rs.core.Response;
16
17 import java.lang.reflect.Method;
18 import java.net.MalformedURLException;
19 import java.net.URI;
20 import java.net.URISyntaxException;
21 import java.net.URL;
22 import java.util.Set;
23
24 /**
25 * This class represents the method level creation of a "rich response object"
26 * that has the @ResponseObject annotation. These EntityExtractors will be used
27 * to implment methods of ResponseObject via ResponseObjectEntityExtractor
28 *
29 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
30 * @version $Revision: 1 $
31 * @see EntityExtractor, ResponseObjectEntityExtractor
32 */
33 public class ResponseObjectEntityExtractorFactory extends DefaultEntityExtractorFactory
34 {
35
36 @SuppressWarnings("unchecked")
37 public EntityExtractor createExtractor(final Method method)
38 {
39 final Class<?> returnType = method.getReturnType();
40 if (method.isAnnotationPresent(Status.class))
41 {
42 if (returnType == Integer.class || returnType == int.class)
43 {
44
45 return new EntityExtractor<Integer>()
46 {
47 public Integer extractEntity(ClientRequestContext context, Object... args)
48 {
49 return context.getClientResponse().getStatus();
50 }
51 };
52 }
53 else if (returnType == Response.Status.class)
54 {
55 return createStatusExtractor(false);
56 }
57 }
58
59 if (method.isAnnotationPresent(Body.class))
60 {
61 return new BodyEntityExtractor(method);
62 }
63
64 final HeaderParam headerParam = method.getAnnotation(HeaderParam.class);
65 if (headerParam != null)
66 {
67 return new EntityExtractor()
68 {
69 public Object extractEntity(ClientRequestContext context, Object... args)
70 {
71 return context.getClientResponse().getResponseHeaders().getFirst(headerParam.value());
72 }
73 };
74 }
75
76 final LinkHeaderParam link = method.getAnnotation(LinkHeaderParam.class);
77 if (link != null)
78 {
79 return processLinkHeader(method, returnType, link);
80 }
81
82 if (returnType == ClientRequest.class)
83 {
84 return new EntityExtractor()
85 {
86 public Object extractEntity(ClientRequestContext context, Object... args)
87 {
88 return context.getRequest();
89 }
90 };
91 }
92
93 if (Response.class.isAssignableFrom(returnType))
94 {
95 return createResponseTypeEntityExtractor(method);
96 }
97
98 if (returnType == LinkHeader.class)
99 {
100 return new EntityExtractor()
101 {
102 public Object extractEntity(ClientRequestContext context, Object... args)
103 {
104 return context.getClientResponse().getLinkHeader();
105 }
106 };
107 }
108
109 return null;
110 }
111
112 private EntityExtractor processLinkHeader(final Method method, final Class<?> returnType,
113 final LinkHeaderParam link)
114 {
115 if ("".equals(link.rel()) && "".equals(link.title()))
116 {
117 throw new RuntimeException(Messages.MESSAGES.mustSetLinkHeaderRelOrTitle(method.getClass().getName(), method.getName()));
118 }
119 if (!"".equals(link.rel()) && !"".equals(link.title()))
120 {
121 throw new RuntimeException(Messages.MESSAGES.canOnlySetLinkHeaderRelOrTitle(method.getClass().getName(), method.getName()));
122 }
123
124 if (returnType == Link.class)
125 {
126 return new EntityExtractor()
127 {
128 public Object extractEntity(ClientRequestContext context, Object... args)
129 {
130 return getLink(link, context);
131 }
132 };
133 }
134
135 if (isInvokerMethod(method))
136 {
137 return new EntityExtractor()
138 {
139 public Object extractEntity(ClientRequestContext context, Object... args)
140 {
141 URI uri = getURI(method, link, context);
142 if (uri == null)
143 return null;
144
145 ClientRequest request = context.getRequest();
146 EntityExtractorFactory extractor = context.getExtractorFactory();
147 ResteasyProviderFactory provider = request.getProviderFactory();
148 ClientExecutor executor = request.getExecutor();
149 return ProxyFactory.createClientInvoker(method.getDeclaringClass(), method, uri,
150 executor, provider, extractor).invoke(args);
151 }
152 };
153 }
154
155 if (returnType == String.class)
156 {
157 return new EntityExtractor<String>()
158 {
159 public String extractEntity(ClientRequestContext context, Object... args)
160 {
161 Link link2 = getLink(link, context);
162 return link2 == null ? null : link2.getHref();
163 }
164 };
165 }
166
167 if (returnType == URL.class)
168 {
169 return new EntityExtractor<URL>()
170 {
171 public URL extractEntity(ClientRequestContext context, Object... args)
172 {
173 return getURL(method, link, context);
174 }
175 };
176 }
177 if (returnType == URI.class)
178 {
179 return new EntityExtractor<URI>()
180 {
181 public URI extractEntity(ClientRequestContext context, Object... args)
182 {
183 return getURI(method, link, context);
184 }
185 };
186 }
187
188 if (returnType.equals(ClientRequest.class))
189 {
190 return new EntityExtractor<ClientRequest>()
191 {
192 public ClientRequest extractEntity(ClientRequestContext context, Object... args)
193 {
194 URI uri = getURI(method, link, context);
195 return uri == null ? null : context.getRequest().createSubsequentRequest(uri);
196 }
197 };
198 }
199
200 return null;
201 }
202
203 private static boolean isInvokerMethod(Method method)
204 {
205 Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
206 return httpMethods != null && httpMethods.size() == 1;
207 }
208
209 private Link getLink(final LinkHeaderParam link, ClientRequestContext context)
210 {
211 LinkHeader linkHeader = context.getClientResponse().getLinkHeader();
212 if (!"".equals(link.rel()))
213 return linkHeader.getLinkByRelationship(link.rel());
214 else
215 return linkHeader.getLinkByTitle(link.title());
216 }
217
218 private URI getURI(final Method method, Link link)
219 {
220 if (link == null)
221 {
222 return null;
223 }
224 try
225 {
226 return new URI(link.getHref());
227 }
228 catch (URISyntaxException e)
229 {
230 throw new RuntimeException(Messages.MESSAGES.couldNotCreateURI(link.getHref(), method.getClass().getName(), method.getName()), e);
231 }
232 }
233
234 private URI getURI(final Method method, final LinkHeaderParam link, ClientRequestContext context)
235 {
236 return getURI(method, getLink(link, context));
237 }
238
239 private URL getURL(final Method method, final LinkHeaderParam link, ClientRequestContext context)
240 {
241 URI uri = getURI(method, link, context);
242 try
243 {
244 return uri == null ? null : uri.toURL();
245 }
246 catch (MalformedURLException e)
247 {
248 throw new RuntimeException(Messages.MESSAGES.couldNotCreateURI(uri.toASCIIString(), method.getClass().getName(), method.getName()), e);
249 }
250 }
251 }
0 package org.jboss.resteasy.client.core.extractors;
1
2 import java.lang.reflect.Method;
3 import java.lang.reflect.Proxy;
4 import java.util.HashMap;
5
6 /**
7 * This class represents the proxying functionality for creating a
8 * "rich response object" that has the @ResponseObject annotation. The method
9 * implementations ware created in ResponseObjectEntityExtractorFactory
10 *
11 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
12 * @version $Revision: 1 $
13 * @see EntityExtractor, ResponseObjectEntityExtractorFactory
14 */
15
16 @SuppressWarnings("unchecked")
17 public class ResponseObjectProxy<T> implements EntityExtractor
18 {
19 private Class<T> returnType;
20 private HashMap<Method, EntityExtractor<?>> methodHandlers;
21
22 public ResponseObjectProxy(Method method, EntityExtractorFactory extractorFactory)
23 {
24 this.returnType = (Class<T>) method.getReturnType();
25 this.methodHandlers = new HashMap<Method, EntityExtractor<?>>();
26 for (Method interfaceMethod : this.returnType.getMethods())
27 {
28 this.methodHandlers.put(interfaceMethod, extractorFactory.createExtractor(interfaceMethod));
29 }
30 }
31
32 public Object extractEntity(ClientRequestContext context, Object... args)
33 {
34 Class<?>[] intfs = {returnType};
35 ClientResponseProxy clientProxy = new ClientResponseProxy(context, methodHandlers, returnType);
36 return Proxy.newProxyInstance(returnType.getClassLoader(), intfs, clientProxy);
37 }
38
39 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.annotations.Form;
3 import org.jboss.resteasy.client.ClientURI;
4 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
5 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.util.FindAnnotation;
7 import org.jboss.resteasy.util.MediaTypeHelper;
8
9 import javax.ws.rs.BeanParam;
10 import javax.ws.rs.CookieParam;
11 import javax.ws.rs.Encoded;
12 import javax.ws.rs.FormParam;
13 import javax.ws.rs.HeaderParam;
14 import javax.ws.rs.MatrixParam;
15 import javax.ws.rs.PathParam;
16 import javax.ws.rs.QueryParam;
17 import javax.ws.rs.core.Context;
18 import javax.ws.rs.core.Cookie;
19 import javax.ws.rs.core.MediaType;
20
21 import java.lang.annotation.Annotation;
22 import java.lang.reflect.AccessibleObject;
23 import java.lang.reflect.Method;
24 import java.lang.reflect.Type;
25
26 public class ClientMarshallerFactory
27 {
28
29 public static Marshaller[] createMarshallers(Class declaringClass, Method method, ResteasyProviderFactory providerFactory)
30 {
31 return createMarshallers(declaringClass, method, providerFactory, null);
32 }
33
34 public static Marshaller[] createMarshallers(Class declaringClass, Method method, ResteasyProviderFactory providerFactory, MediaType defaultConsumes)
35 {
36 Marshaller[] params = new Marshaller[method.getParameterTypes().length];
37 for (int i = 0; i < method.getParameterTypes().length; i++)
38 {
39 Class<?> type = method.getParameterTypes()[i];
40 Annotation[] annotations = method.getParameterAnnotations()[i];
41 Type genericType = method.getGenericParameterTypes()[i];
42 AccessibleObject target = method;
43 params[i] = ClientMarshallerFactory.createMarshaller(declaringClass, providerFactory, type, annotations, genericType, target, defaultConsumes, false);
44 }
45 return params;
46 }
47
48 public static Marshaller createMarshaller(Class<?> declaring,
49 ResteasyProviderFactory providerFactory, Class<?> type,
50 Annotation[] annotations, Type genericType, AccessibleObject target,
51 boolean ignoreBody)
52 {
53 return createMarshaller(declaring, providerFactory, type, annotations, genericType, target, null, ignoreBody);
54 }
55
56 public static Marshaller createMarshaller(Class<?> declaring,
57 ResteasyProviderFactory providerFactory, Class<?> type,
58 Annotation[] annotations, Type genericType, AccessibleObject target, MediaType defaultConsumes,
59 boolean ignoreBody)
60 {
61 Marshaller marshaller = null;
62
63 QueryParam query;
64 HeaderParam header;
65 MatrixParam matrix;
66 PathParam uriParam;
67 CookieParam cookie;
68 FormParam formParam;
69 // Form form;
70
71 boolean isEncoded = FindAnnotation.findAnnotation(annotations,
72 Encoded.class) != null;
73
74 if ((query = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null)
75 {
76 marshaller = new QueryParamMarshaller(query.value());
77 }
78 else if ((header = FindAnnotation.findAnnotation(annotations,
79 HeaderParam.class)) != null)
80 {
81 marshaller = new HeaderParamMarshaller(header.value());
82 }
83 else if ((cookie = FindAnnotation.findAnnotation(annotations,
84 CookieParam.class)) != null)
85 {
86 marshaller = new CookieParamMarshaller(cookie.value());
87 }
88 else if ((uriParam = FindAnnotation.findAnnotation(annotations,
89 PathParam.class)) != null)
90 {
91 marshaller = new PathParamMarshaller(uriParam.value(), isEncoded,
92 providerFactory);
93 }
94 else if ((matrix = FindAnnotation.findAnnotation(annotations,
95 MatrixParam.class)) != null)
96 {
97 marshaller = new MatrixParamMarshaller(matrix.value());
98 }
99 else if ((formParam = FindAnnotation.findAnnotation(annotations,
100 FormParam.class)) != null)
101 {
102 marshaller = new FormParamMarshaller(formParam.value());
103 }
104 else if ((/* form = */FindAnnotation.findAnnotation(annotations,
105 Form.class)) != null)
106 {
107 marshaller = new FormMarshaller(type, providerFactory);
108 }
109 else if ((/* form = */FindAnnotation.findAnnotation(annotations,
110 BeanParam.class)) != null)
111 {
112 marshaller = new FormMarshaller(type, providerFactory);
113 }
114 else if ((FindAnnotation.findAnnotation(annotations,
115 Context.class)) != null)
116 {
117 marshaller = new NOOPMarshaller();
118 }
119 else if (type.equals(Cookie.class))
120 {
121 marshaller = new CookieParamMarshaller(null);
122 }
123 // this is for HATEAOS clients
124 else if (FindAnnotation.findAnnotation(annotations, ClientURI.class) != null)
125 {
126 marshaller = new URIParamMarshaller();
127 }
128 else if (!ignoreBody)
129 {
130 MediaType mediaType = MediaTypeHelper.getConsumes(declaring, target);
131 if(mediaType == null)
132 mediaType = defaultConsumes;
133 if (mediaType == null)
134 {
135 throw new RuntimeException(Messages.MESSAGES.mustDefineConsumes());
136 }
137 marshaller = new MessageBodyParameterMarshaller(mediaType, type,
138 genericType, annotations);
139 }
140 return marshaller;
141 }
142 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import javax.ws.rs.core.Cookie;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class CookieParamMarshaller implements Marshaller
11 {
12 private String cookieName;
13
14 public CookieParamMarshaller(String cookieName)
15 {
16 this.cookieName = cookieName;
17 }
18
19 public String getCookieName()
20 {
21 return cookieName;
22 }
23
24 public void build(ClientRequest request, Object object)
25 {
26 if (object == null) return; // don't set a null value
27 if (object instanceof Cookie)
28 {
29 Cookie cookie = (Cookie) object;
30 request.cookie(cookie);
31 }
32 else
33 {
34 request.cookie(cookieName, object);
35 }
36 }
37 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.spi.LoggableFailure;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import java.io.ByteArrayOutputStream;
7 import java.io.DataOutputStream;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Field;
10 import java.lang.reflect.InvocationTargetException;
11 import java.lang.reflect.Method;
12 import java.lang.reflect.Modifier;
13 import java.lang.reflect.Type;
14 import java.security.DigestOutputStream;
15 import java.security.MessageDigest;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20
21 /**
22 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
23 * @version $Revision: 1 $
24 */
25 public class FormMarshaller implements Marshaller
26 {
27 protected HashMap<Field, Marshaller> fieldMap = new HashMap<Field, Marshaller>();
28
29 private static class GetterMethod
30 {
31 private GetterMethod(Method method, Marshaller marshaller)
32 {
33 this.method = method;
34 this.marshaller = marshaller;
35 }
36
37 public Method method;
38 public Marshaller marshaller;
39 }
40
41 protected List<GetterMethod> getters = new ArrayList<GetterMethod>();
42 protected HashMap<Long, Method> getterHashes = new HashMap<Long, Method>();
43 protected Class clazz;
44
45 public FormMarshaller(Class clazz, ResteasyProviderFactory factory)
46 {
47 this.clazz = clazz;
48
49 populateMap(clazz, factory);
50 }
51
52 public static long methodHash(Method method)
53 throws Exception
54 {
55 Class[] parameterTypes = method.getParameterTypes();
56 StringBuilder methodDesc = new StringBuilder(method.getName()).append("(");
57 for (int j = 0; j < parameterTypes.length; j++)
58 {
59 methodDesc.append(getTypeString(parameterTypes[j]));
60 }
61 methodDesc.append(")").append(getTypeString(method.getReturnType()));
62 return createHash(methodDesc.toString());
63 }
64
65 public static long createHash(String methodDesc)
66 throws Exception
67 {
68 long hash = 0;
69 ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512);
70 MessageDigest messagedigest = MessageDigest.getInstance("SHA");
71 DataOutputStream dataoutputstream = new DataOutputStream(new DigestOutputStream(bytearrayoutputstream, messagedigest));
72 dataoutputstream.writeUTF(methodDesc);
73 dataoutputstream.flush();
74 byte abyte0[] = messagedigest.digest();
75 for (int j = 0; j < Math.min(8, abyte0.length); j++)
76 hash += (long) (abyte0[j] & 0xff) << j * 8;
77 return hash;
78
79 }
80
81 static String getTypeString(Class cl)
82 {
83 if (cl == Byte.TYPE)
84 {
85 return "B";
86 }
87 else if (cl == Character.TYPE)
88 {
89 return "C";
90 }
91 else if (cl == Double.TYPE)
92 {
93 return "D";
94 }
95 else if (cl == Float.TYPE)
96 {
97 return "F";
98 }
99 else if (cl == Integer.TYPE)
100 {
101 return "I";
102 }
103 else if (cl == Long.TYPE)
104 {
105 return "J";
106 }
107 else if (cl == Short.TYPE)
108 {
109 return "S";
110 }
111 else if (cl == Boolean.TYPE)
112 {
113 return "Z";
114 }
115 else if (cl == Void.TYPE)
116 {
117 return "V";
118 }
119 else if (cl.isArray())
120 {
121 return "[" + getTypeString(cl.getComponentType());
122 }
123 else
124 {
125 return "L" + cl.getName().replace('.', '/') + ";";
126 }
127 }
128
129 protected void populateMap(Class clazz, ResteasyProviderFactory factory)
130 {
131 for (Field field : clazz.getDeclaredFields())
132 {
133 Annotation[] annotations = field.getAnnotations();
134 if (annotations == null || annotations.length == 0) continue;
135 Class type = field.getType();
136 Type genericType = field.getGenericType();
137
138 Marshaller marshaller = ClientMarshallerFactory.createMarshaller(
139 clazz, factory, type, annotations, genericType, field, true);
140 if (marshaller != null)
141 {
142 if (!Modifier.isPublic(field.getModifiers())) field.setAccessible(true);
143 fieldMap.put(field, marshaller);
144 }
145 }
146 for (Method method : clazz.getDeclaredMethods())
147 {
148 if (!method.getName().startsWith("get")) continue;
149
150 if (method.getParameterTypes().length > 0) continue;
151
152 Annotation[] annotations = method.getAnnotations();
153 if (annotations == null || annotations.length == 0) continue;
154
155 Class type = method.getReturnType();
156 Type genericType = method.getGenericReturnType();
157
158 Marshaller marshaller = ClientMarshallerFactory
159 .createMarshaller(clazz, factory, type, annotations,
160 genericType, method, true);
161 if (marshaller != null)
162 {
163 long hash = 0;
164 try
165 {
166 hash = methodHash(method);
167 }
168 catch (Exception e)
169 {
170 throw new RuntimeException(e);
171 }
172 if (!Modifier.isPrivate(method.getModifiers()))
173 {
174 Method older = getterHashes.get(hash);
175 if (older != null) continue;
176 }
177
178 if (!Modifier.isPublic(method.getModifiers())) method.setAccessible(true);
179 getters.add(new GetterMethod(method, marshaller));
180 getterHashes.put(hash, method);
181 }
182
183 }
184 if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class))
185 populateMap(clazz.getSuperclass(), factory);
186
187
188 }
189
190 public void build(ClientRequest request, Object object)
191 {
192 if (object == null) return;
193
194 for (Map.Entry<Field, Marshaller> entry : fieldMap.entrySet())
195 {
196
197 try
198 {
199 Object val = entry.getKey().get(object);
200 entry.getValue().build(request, val);
201 }
202 catch (IllegalAccessException e)
203 {
204 throw new LoggableFailure(e);
205 }
206 }
207 for (GetterMethod getter : getters)
208 {
209 Object val = null;
210 try
211 {
212 val = getter.method.invoke(object);
213 }
214 catch (IllegalAccessException e)
215 {
216 throw new RuntimeException(e);
217 }
218 catch (InvocationTargetException e)
219 {
220 throw new RuntimeException(e);
221 }
222 getter.marshaller.build(request, val);
223 }
224 }
225
226 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import java.util.Collection;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class FormParamMarshaller implements Marshaller
11 {
12 private String paramName;
13
14 public FormParamMarshaller(String paramName)
15 {
16 this.paramName = paramName;
17 }
18
19 public void build(ClientRequest request, Object object)
20 {
21 if (object == null) return;
22
23 if (object instanceof Collection)
24 {
25 for (Object obj : (Collection) object)
26 {
27 request.formParameter(paramName, obj);
28 }
29 }
30 else if (object.getClass().isArray())
31 {
32 if (object.getClass().getComponentType().isPrimitive())
33 {
34 Class componentType = object.getClass().getComponentType();
35 if (componentType.equals(boolean.class))
36 {
37 for (Boolean bool : (boolean[]) object) request.formParameter(paramName, bool.toString());
38 }
39 else if (componentType.equals(byte.class))
40 {
41 for (Byte val : (byte[]) object) request.formParameter(paramName, val.toString());
42 }
43 else if (componentType.equals(short.class))
44 {
45 for (Short val : (short[]) object) request.formParameter(paramName, val.toString());
46 }
47 else if (componentType.equals(int.class))
48 {
49 for (Integer val : (int[]) object) request.formParameter(paramName, val.toString());
50 }
51 else if (componentType.equals(long.class))
52 {
53 for (Long val : (long[]) object) request.formParameter(paramName, val.toString());
54 }
55 else if (componentType.equals(float.class))
56 {
57 for (Float val : (float[]) object) request.formParameter(paramName, val.toString());
58 }
59 else if (componentType.equals(double.class))
60 {
61 for (Double val : (double[]) object) request.formParameter(paramName, val.toString());
62 }
63 }
64 else
65 {
66 Object[] objs = (Object[]) object;
67 for (Object obj : objs)
68 {
69 request.formParameter(paramName, obj);
70
71 }
72 }
73 }
74 else
75 {
76 request.formParameter(paramName, object);
77 }
78 }
79 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import java.util.Collection;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class HeaderParamMarshaller implements Marshaller
11 {
12 private String paramName;
13
14 public HeaderParamMarshaller(String paramName)
15 {
16 this.paramName = paramName;
17 }
18
19 public void build(ClientRequest request, Object object)
20 {
21 if (object == null) return;
22 if (object instanceof Collection)
23 {
24 for (Object obj : (Collection) object)
25 {
26 request.header(paramName, obj);
27 }
28 }
29 else if (object.getClass().isArray())
30 {
31 if (object.getClass().getComponentType().isPrimitive())
32 {
33 Class componentType = object.getClass().getComponentType();
34 if (componentType.equals(boolean.class))
35 {
36 for (Boolean bool : (boolean[]) object) request.header(paramName, bool.toString());
37 }
38 else if (componentType.equals(byte.class))
39 {
40 for (Byte val : (byte[]) object) request.header(paramName, val.toString());
41 }
42 else if (componentType.equals(short.class))
43 {
44 for (Short val : (short[]) object) request.header(paramName, val.toString());
45 }
46 else if (componentType.equals(int.class))
47 {
48 for (Integer val : (int[]) object) request.header(paramName, val.toString());
49 }
50 else if (componentType.equals(long.class))
51 {
52 for (Long val : (long[]) object) request.header(paramName, val.toString());
53 }
54 else if (componentType.equals(float.class))
55 {
56 for (Float val : (float[]) object) request.header(paramName, val.toString());
57 }
58 else if (componentType.equals(double.class))
59 {
60 for (Double val : (double[]) object) request.header(paramName, val.toString());
61 }
62 }
63 else
64 {
65 Object[] objs = (Object[]) object;
66 for (Object obj : objs)
67 {
68 request.header(paramName, obj);
69
70 }
71 }
72 }
73 else
74 {
75 request.header(paramName, object);
76 }
77 }
78 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 */
8 public interface Marshaller
9 {
10 void build(ClientRequest request, Object target);
11 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import java.util.Collection;
3 import java.util.Iterator;
4
5 import org.jboss.resteasy.client.ClientRequest;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 */
11 public class MatrixParamMarshaller implements Marshaller
12 {
13 private String paramName;
14
15 public MatrixParamMarshaller(String paramName)
16 {
17 this.paramName = paramName;
18 }
19
20 public void build(ClientRequest request, Object object)
21 {
22 if (object == null) return; // Don't add a null matrix parameter
23 if (object instanceof Collection)
24 {
25 for (Iterator<?> it = Collection.class.cast(object).iterator(); it.hasNext(); )
26 {
27 request.matrixParameter(paramName, it.next());
28 }
29 }
30 else
31 {
32 request.matrixParameter(paramName, object);
33 }
34 }
35
36 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import javax.ws.rs.core.MediaType;
5 import java.lang.annotation.Annotation;
6 import java.lang.reflect.Type;
7
8 /**
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @version $Revision: 1 $
11 */
12 public class MessageBodyParameterMarshaller implements Marshaller
13 {
14 private Class type;
15 private MediaType mediaType;
16 private Type genericType;
17 private Annotation[] annotations;
18
19 public MessageBodyParameterMarshaller(MediaType mediaType, Class type, Type genericType, Annotation[] annotations)
20 {
21 this.type = type;
22 this.mediaType = mediaType;
23 this.genericType = genericType;
24 this.annotations = annotations;
25 }
26
27 public void build(ClientRequest request, Object object)
28 {
29 request.body(mediaType, object, type, genericType, annotations);
30 }
31
32 public Class getType()
33 {
34 return type;
35 }
36
37 public MediaType getMediaType()
38 {
39 return mediaType;
40 }
41
42 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 /**
5 * Marshaller that doesn't do anything with the target. Useful for @Context parameters which are server-generated.
6 *
7 * @author Stephane Epardaud
8 */
9 public class NOOPMarshaller implements Marshaller
10 {
11
12 public void build(ClientRequest request, Object target)
13 {
14 // do nothing at all
15 }
16
17 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 /**
6 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7 * @version $Revision: 1 $
8 */
9 public class PathParamMarshaller implements Marshaller
10 {
11 private String paramName;
12 private boolean encoded;
13 private ResteasyProviderFactory factory;
14
15 public PathParamMarshaller(String paramName, boolean encoded, ResteasyProviderFactory factory)
16 {
17 this.paramName = paramName;
18 this.encoded = encoded;
19 this.factory = factory;
20 }
21
22 public void build(ClientRequest request, Object object)
23 {
24 request.pathParameter(paramName, object);
25 }
26
27 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import java.util.Collection;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class QueryParamMarshaller implements Marshaller
11 {
12 private String paramName;
13
14 public QueryParamMarshaller(String paramName)
15 {
16 this.paramName = paramName;
17 }
18
19 public void build(ClientRequest request, Object object)
20 {
21 if (object == null) return;
22 if (object instanceof Collection)
23 {
24 for (Object obj : (Collection) object)
25 {
26 request.queryParameter(paramName, obj);
27 }
28 }
29 else if (object.getClass().isArray())
30 {
31 if (object.getClass().getComponentType().isPrimitive())
32 {
33 Class componentType = object.getClass().getComponentType();
34 if (componentType.equals(boolean.class))
35 {
36 for (Boolean bool : (boolean[]) object) request.queryParameter(paramName, bool.toString());
37 }
38 else if (componentType.equals(byte.class))
39 {
40 for (Byte val : (byte[]) object) request.queryParameter(paramName, val.toString());
41 }
42 else if (componentType.equals(short.class))
43 {
44 for (Short val : (short[]) object) request.queryParameter(paramName, val.toString());
45 }
46 else if (componentType.equals(int.class))
47 {
48 for (Integer val : (int[]) object) request.queryParameter(paramName, val.toString());
49 }
50 else if (componentType.equals(long.class))
51 {
52 for (Long val : (long[]) object) request.queryParameter(paramName, val.toString());
53 }
54 else if (componentType.equals(float.class))
55 {
56 for (Float val : (float[]) object) request.queryParameter(paramName, val.toString());
57 }
58 else if (componentType.equals(double.class))
59 {
60 for (Double val : (double[]) object) request.queryParameter(paramName, val.toString());
61 }
62 }
63 else
64 {
65 Object[] objs = (Object[]) object;
66 for (Object obj : objs)
67 {
68 request.queryParameter(paramName, obj);
69
70 }
71 }
72 }
73 else
74 {
75 request.queryParameter(paramName, object);
76 }
77 }
78 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.core.ClientInvoker;
3 import org.jboss.resteasy.client.core.ClientInvokerModifier;
4
5 import java.util.Collection;
6
7 /**
8 * implemented by every generated proxy
9 *
10 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
11 *
12 * @see resteasy-client
13 * @see org.jboss.resteasy.client.jaxrs.internal.proxy.ResteasyClientProxy
14 *
15 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
16 * @version $Revision: 1 $
17 */
18 @Deprecated
19 public interface ResteasyClientProxy
20 {
21 Collection<ClientInvoker> getResteasyClientInvokers();
22
23 void applyClientInvokerModifier(ClientInvokerModifier modifier);
24
25 <T> T as(Class<T> iface);
26 }
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import java.net.URI;
5 import java.net.URISyntaxException;
6 import java.net.URL;
7
8 /**
9 * allows a user to specify the url.
10 *
11 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
12 * @version $Revision: 1 $
13 */
14 public class URIParamMarshaller implements Marshaller
15 {
16 public void build(ClientRequest request, Object target)
17 {
18 URI uri = getUri(target);
19
20 if (uri != null)
21 {
22 request.overrideUri(uri);
23 }
24 }
25
26 private URI getUri(Object target)
27 {
28 try
29 {
30 if (target instanceof URI)
31 {
32 return (URI) target;
33 }
34 else if (target instanceof URL)
35 {
36 return ((URL) target).toURI();
37 }
38 else if (target instanceof String)
39 {
40 return new URI(target.toString());
41 }
42 }
43 catch (URISyntaxException e)
44 {
45 throw new RuntimeException(e);
46 }
47 return null;
48 }
49 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyAuthChallengeException extends ResteasyAuthenticationException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyAuthChallengeException()
13 {
14 }
15
16 public ResteasyAuthChallengeException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyAuthChallengeException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyAuthChallengeException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyAuthenticationException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyAuthenticationException()
13 {
14 }
15
16 public ResteasyAuthenticationException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyAuthenticationException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyAuthenticationException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyCircularRedirectException extends ResteasyRedirectException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyCircularRedirectException()
13 {
14 }
15
16 public ResteasyCircularRedirectException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyCircularRedirectException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyCircularRedirectException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyClientException extends RuntimeException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyClientException()
13 {
14 }
15
16 public ResteasyClientException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyClientException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyClientException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyClientProtocolException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyClientProtocolException()
13 {
14 }
15
16 public ResteasyClientProtocolException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyClientProtocolException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyClientProtocolException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyConnectTimeoutException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyConnectTimeoutException()
13 {
14 }
15
16 public ResteasyConnectTimeoutException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyConnectTimeoutException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyConnectTimeoutException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyConnectionClosedException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyConnectionClosedException()
13 {
14 }
15
16 public ResteasyConnectionClosedException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyConnectionClosedException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyConnectionClosedException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyConnectionPoolTimeoutException extends ResteasyConnectTimeoutException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyConnectionPoolTimeoutException()
13 {
14 }
15
16 public ResteasyConnectionPoolTimeoutException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyConnectionPoolTimeoutException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyConnectionPoolTimeoutException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyCookieRestrictionViolationException extends ResteasyMalformedCookieException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyCookieRestrictionViolationException()
13 {
14 }
15
16 public ResteasyCookieRestrictionViolationException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyCookieRestrictionViolationException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyCookieRestrictionViolationException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyCredentialsNotAvailableException extends ResteasyAuthenticationException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyCredentialsNotAvailableException()
13 {
14 }
15
16 public ResteasyCredentialsNotAvailableException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyCredentialsNotAvailableException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyCredentialsNotAvailableException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyHttpContentTooLargeException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyHttpContentTooLargeException()
13 {
14 }
15
16 public ResteasyHttpContentTooLargeException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyHttpContentTooLargeException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyHttpContentTooLargeException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyHttpException extends ResteasyClientException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyHttpException()
13 {
14 }
15
16 public ResteasyHttpException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyHttpException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyHttpException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyHttpHostConnectException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyHttpHostConnectException()
13 {
14 }
15
16 public ResteasyHttpHostConnectException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyHttpHostConnectException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyHttpHostConnectException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyHttpRecoverableException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyHttpRecoverableException()
13 {
14 }
15
16 public ResteasyHttpRecoverableException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyHttpRecoverableException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyHttpRecoverableException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyIOException extends ResteasyClientException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyIOException()
13 {
14 }
15
16 public ResteasyIOException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyIOException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyIOException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyInvalidCredentialsException extends ResteasyAuthenticationException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyInvalidCredentialsException()
13 {
14 }
15
16 public ResteasyInvalidCredentialsException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyInvalidCredentialsException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyInvalidCredentialsException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyInvalidRedirectLocationException extends ResteasyRedirectException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyInvalidRedirectLocationException()
13 {
14 }
15
16 public ResteasyInvalidRedirectLocationException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyInvalidRedirectLocationException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyInvalidRedirectLocationException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyMalformedChallengeException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyMalformedChallengeException()
13 {
14 }
15
16 public ResteasyMalformedChallengeException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyMalformedChallengeException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyMalformedChallengeException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyMalformedChunkCodingException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyMalformedChunkCodingException()
13 {
14 }
15
16 public ResteasyMalformedChunkCodingException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyMalformedChunkCodingException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyMalformedChunkCodingException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyMalformedCookieException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyMalformedCookieException()
13 {
14 }
15
16 public ResteasyMalformedCookieException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyMalformedCookieException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyMalformedCookieException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyMethodNotSupportedException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyMethodNotSupportedException()
13 {
14 }
15
16 public ResteasyMethodNotSupportedException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyMethodNotSupportedException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyMethodNotSupportedException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyNTLMEngineException extends ResteasyAuthenticationException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyNTLMEngineException()
13 {
14 }
15
16 public ResteasyNTLMEngineException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyNTLMEngineException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyNTLMEngineException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyNoHttpResponseException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyNoHttpResponseException()
13 {
14 }
15
16 public ResteasyNoHttpResponseException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyNoHttpResponseException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyNoHttpResponseException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyNonRepeatableRequestException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyNonRepeatableRequestException()
13 {
14 }
15
16 public ResteasyNonRepeatableRequestException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyNonRepeatableRequestException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyNonRepeatableRequestException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyProtocolException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyProtocolException()
13 {
14 }
15
16 public ResteasyProtocolException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyProtocolException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyProtocolException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyRedirectException extends ResteasyNonRepeatableRequestException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyRedirectException()
13 {
14 }
15
16 public ResteasyRedirectException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyRedirectException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyRedirectException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyTunnelRefusedException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyTunnelRefusedException()
13 {
14 }
15
16 public ResteasyTunnelRefusedException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyTunnelRefusedException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyTunnelRefusedException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyURIException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyURIException()
13 {
14 }
15
16 public ResteasyURIException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyURIException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyURIException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyUnsupportedHttpVersionException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyUnsupportedHttpVersionException()
13 {
14 }
15
16 public ResteasyUnsupportedHttpVersionException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyUnsupportedHttpVersionException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyUnsupportedHttpVersionException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
0 package org.jboss.resteasy.client.exception.mapper;
1
2 import org.apache.http.ConnectionClosedException;
3 import org.apache.http.HttpException;
4 import org.apache.http.MalformedChunkCodingException;
5 import org.apache.http.MethodNotSupportedException;
6 import org.apache.http.NoHttpResponseException;
7 import org.apache.http.ProtocolException;
8 import org.apache.http.UnsupportedHttpVersionException;
9 import org.apache.http.auth.AuthenticationException;
10 import org.apache.http.auth.InvalidCredentialsException;
11 import org.apache.http.auth.MalformedChallengeException;
12 import org.apache.http.client.CircularRedirectException;
13 import org.apache.http.client.ClientProtocolException;
14 import org.apache.http.client.NonRepeatableRequestException;
15 import org.apache.http.client.RedirectException;
16 import org.apache.http.conn.ConnectTimeoutException;
17 import org.apache.http.conn.ConnectionPoolTimeoutException;
18 import org.apache.http.conn.HttpHostConnectException;
19 import org.apache.http.cookie.CookieRestrictionViolationException;
20 import org.apache.http.cookie.MalformedCookieException;
21 import org.apache.http.impl.auth.NTLMEngineException;
22 import org.apache.http.impl.client.TunnelRefusedException;
23 import org.jboss.resteasy.client.exception.ResteasyAuthenticationException;
24 import org.jboss.resteasy.client.exception.ResteasyCircularRedirectException;
25 import org.jboss.resteasy.client.exception.ResteasyClientException;
26 import org.jboss.resteasy.client.exception.ResteasyClientProtocolException;
27 import org.jboss.resteasy.client.exception.ResteasyConnectTimeoutException;
28 import org.jboss.resteasy.client.exception.ResteasyConnectionClosedException;
29 import org.jboss.resteasy.client.exception.ResteasyConnectionPoolTimeoutException;
30 import org.jboss.resteasy.client.exception.ResteasyCookieRestrictionViolationException;
31 import org.jboss.resteasy.client.exception.ResteasyHttpException;
32 import org.jboss.resteasy.client.exception.ResteasyHttpHostConnectException;
33 import org.jboss.resteasy.client.exception.ResteasyIOException;
34 import org.jboss.resteasy.client.exception.ResteasyInvalidCredentialsException;
35 import org.jboss.resteasy.client.exception.ResteasyMalformedChallengeException;
36 import org.jboss.resteasy.client.exception.ResteasyMalformedChunkCodingException;
37 import org.jboss.resteasy.client.exception.ResteasyMalformedCookieException;
38 import org.jboss.resteasy.client.exception.ResteasyMethodNotSupportedException;
39 import org.jboss.resteasy.client.exception.ResteasyNTLMEngineException;
40 import org.jboss.resteasy.client.exception.ResteasyNoHttpResponseException;
41 import org.jboss.resteasy.client.exception.ResteasyNonRepeatableRequestException;
42 import org.jboss.resteasy.client.exception.ResteasyProtocolException;
43 import org.jboss.resteasy.client.exception.ResteasyRedirectException;
44 import org.jboss.resteasy.client.exception.ResteasyTunnelRefusedException;
45 import org.jboss.resteasy.client.exception.ResteasyUnsupportedHttpVersionException;
46
47 import javax.ws.rs.ext.Provider;
48 import java.io.IOException;
49
50 /**
51 *
52 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
53 * @version $Revision: 1.1 $
54 *
55 * Copyright Jul 28, 2012
56 */
57 @Provider
58 public class ApacheHttpClient4ExceptionMapper implements ClientExceptionMapper<Exception>
59 {
60 @Override
61 public ResteasyClientException toException(Exception exception)
62 {
63 if (exception instanceof IOException)
64 {
65 return mapIOException(IOException.class.cast(exception));
66 }
67 if (exception instanceof HttpException)
68 {
69 return mapHttpException(HttpException.class.cast(exception));
70 }
71 return new ResteasyClientException("Unexpected exception type", exception);
72 }
73
74 private ResteasyClientException mapIOException(IOException e)
75 {
76 if (ClientProtocolException.class.equals(e.getClass()))
77 {
78 return new ResteasyClientProtocolException(e);
79 }
80 if (ConnectionClosedException.class.equals(e.getClass()))
81 {
82 return new ResteasyConnectionClosedException(e);
83 }
84 if (ConnectionPoolTimeoutException.class.equals(e.getClass()))
85 {
86 return new ResteasyConnectionPoolTimeoutException(e);
87 }
88 if (ConnectTimeoutException.class.equals(e.getClass()))
89 {
90 return new ResteasyConnectTimeoutException(e);
91 }
92 if (HttpHostConnectException.class.equals(e.getClass()))
93 {
94 return new ResteasyHttpHostConnectException(e);
95 }
96 if (MalformedChunkCodingException.class.equals(e.getClass()))
97 {
98 return new ResteasyMalformedChunkCodingException(e);
99 }
100 if (NoHttpResponseException.class.equals(e.getClass()))
101 {
102 return new ResteasyNoHttpResponseException(e);
103 }
104 if (NoHttpResponseException.class.equals(e.getClass()))
105 {
106 return new ResteasyNoHttpResponseException(e);
107 }
108 return new ResteasyIOException("IOException", e);
109 }
110
111 private ResteasyClientException mapHttpException(HttpException e)
112 {
113 if (AuthenticationException.class.equals(e.getClass()))
114 {
115 return new ResteasyAuthenticationException(e);
116 }
117 if (CircularRedirectException.class.equals(e.getClass()))
118 {
119 return new ResteasyCircularRedirectException(e);
120 }
121 if (CookieRestrictionViolationException.class.equals(e.getClass()))
122 {
123 return new ResteasyCookieRestrictionViolationException(e);
124 }
125 if (InvalidCredentialsException.class.equals(e.getClass()))
126 {
127 return new ResteasyInvalidCredentialsException(e);
128 }
129 if (MalformedChallengeException.class.equals(e.getClass()))
130 {
131 return new ResteasyMalformedChallengeException(e);
132 }
133 if (MalformedCookieException.class.equals(e.getClass()))
134 {
135 return new ResteasyMalformedCookieException(e);
136 }
137 if (MethodNotSupportedException.class.equals(e.getClass()))
138 {
139 return new ResteasyMethodNotSupportedException(e);
140 }
141 if (NonRepeatableRequestException.class.equals(e.getClass()))
142 {
143 return new ResteasyNonRepeatableRequestException(e);
144 }
145 if (NTLMEngineException.class.equals(e.getClass()))
146 {
147 return new ResteasyNTLMEngineException(e);
148 }
149 if (ProtocolException.class.equals(e.getClass()))
150 {
151 return new ResteasyProtocolException(e);
152 }
153 if (RedirectException.class.equals(e.getClass()))
154 {
155 return new ResteasyRedirectException(e);
156 }
157 if (TunnelRefusedException.class.equals(e.getClass()))
158 {
159 return new ResteasyTunnelRefusedException(e);
160 }
161 if (UnsupportedHttpVersionException.class.equals(e.getClass()))
162 {
163 return new ResteasyUnsupportedHttpVersionException(e);
164 }
165 return new ResteasyHttpException("HttpException", e);
166 }
167 }
0 package org.jboss.resteasy.client.exception.mapper;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public interface ClientExceptionMapper<E extends Throwable>
9 {
10 RuntimeException toException(E exception);
11 }
0 /**
1 * JAX-RS specification 1.1 ({@link <a href="https://jcp.org/en/jsr/detail?id=311">https://jcp.org/en/jsr/detail?id=311</a>})
2 * had no client framework, so Resteasy release 2.x provided one. It has two ways to access a server resource:
3 *
4 * <ol>
5 * <li>
6 * {@link org.jboss.resteasy.client.ClientRequest}
7 * </li>
8 * <li>
9 * a proxy that implements an interface implemented by the target resource
10 * </ol>
11 *
12 * JAX-RS specification 2.0
13 * ({@link <a href="https://www.jcp.org/aboutJava/communityprocess/final/jsr339/index.html">https://www.jcp.org/aboutJava/communityprocess/final/jsr339/index.html</a>})
14 * introduced an official client framework, so the older Resteasy client framework is now deprecated. However, the new JAX-RS
15 * framework does not include a proxy feature, so Resteasy extends the official client framework with a new proxy feature.
16 * A proxy can be created using {@link org.jboss.resteasy.client.jaxrs.ResteasyWebTarget}, which extends the api class
17 * javax.ws.rs.client.WebTarget
18 * <p>
19 * For more information, see the Resteasy User Guide
20 * {@link <a href="http://docs.jboss.org/resteasy/docs/">http://docs.jboss.org/resteasy/docs/</a>}.
21 */
22 package org.jboss.resteasy.client;
1919 import java.util.HashMap;
2020 import java.util.List;
2121 import java.util.Map;
22 import java.util.function.Consumer;
2223
2324 /**
2425 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
146147 this.annotations = annotations;
147148 }
148149
149 protected void completionCallbacks(Throwable throwable)
150 @Override
151 public void completionCallbacks(Throwable throwable)
150152 {
151153 for (CompletionCallback callback : completionCallbacks)
152154 {
154156 }
155157 }
156158
159 @Deprecated
157160 protected boolean internalResume(Object entity)
161 {
162 return internalResume(entity, t -> {});
163 }
164
165 protected boolean internalResume(Object entity, Consumer<Throwable> onComplete)
158166 {
159167 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
160168 Response response = null;
177185 }
178186 try
179187 {
180 dispatcher.asynchronousDelivery(this.request, this.response, response);
188 dispatcher.asynchronousDelivery(this.request, this.response, response, t -> {
189 if(t != null)
190 {
191 internalResume(t, t2 -> {
192 onComplete.accept(t);
193 // callbacks done by internalResume
194 });
195 }
196 else
197 {
198 onComplete.accept(null);
199 completionCallbacks(null);
200 }
201 });
181202 }
182203 catch (Throwable e)
183204 {
184 return internalResume(e);
185 }
186 completionCallbacks(null);
205 return internalResume(e, t -> {
206 onComplete.accept(e);
207 // callbacks done by internalResume
208 });
209 }
187210 return true;
188211 }
189212
213 @Deprecated
190214 protected boolean internalResume(Throwable exc)
191215 {
216 return internalResume(exc, t -> {});
217 }
218
219 protected boolean internalResume(Throwable exc, Consumer<Throwable> onComplete)
220 {
192221 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
193 try
194 {
195 dispatcher.asynchronousExceptionDelivery(request, response, exc);
196 }
197 finally
198 {
222 dispatcher.asynchronousExceptionDelivery(request, response, exc, t -> {
223 onComplete.accept(t);
199224 completionCallbacks(exc);
200 }
225 });
201226 return true;
202227 }
203228
0 package org.jboss.resteasy.core;
1
2 import java.io.IOException;
3 import java.lang.annotation.Annotation;
4 import java.lang.reflect.ParameterizedType;
5 import java.lang.reflect.Type;
6 import java.util.ArrayList;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.concurrent.CompletionStage;
10 import java.util.function.BiConsumer;
11 import java.util.function.Consumer;
12
13 import javax.ws.rs.core.HttpHeaders;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.core.Response;
16 import javax.ws.rs.sse.OutboundSseEvent;
17 import javax.ws.rs.sse.SseEventSink;
18
19 import org.jboss.resteasy.annotations.Stream;
20 import org.jboss.resteasy.plugins.providers.sse.SseImpl;
21 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
22 import org.jboss.resteasy.specimpl.BuiltResponse;
23 import org.jboss.resteasy.spi.AsyncResponseProvider;
24 import org.jboss.resteasy.spi.AsyncStreamProvider;
25 import org.jboss.resteasy.spi.HttpRequest;
26 import org.jboss.resteasy.spi.HttpResponse;
27 import org.jboss.resteasy.spi.ResteasyAsynchronousResponse;
28 import org.jboss.resteasy.spi.ResteasyProviderFactory;
29 import org.reactivestreams.Publisher;
30 import org.reactivestreams.Subscriber;
31 import org.reactivestreams.Subscription;
32
33 /**
34 * @author <a href="mailto:rsigal@redhat.com">Ron Sigal</a>
35 * @version $Revision: 1 $
36 */
37 public abstract class AsyncResponseConsumer
38 {
39 protected Map<Class<?>, Object> contextDataMap;
40 protected ResourceMethodInvoker method;
41 protected SynchronousDispatcher dispatcher;
42 protected ResteasyAsynchronousResponse asyncResponse;
43 protected boolean isComplete;
44
45 public AsyncResponseConsumer(ResourceMethodInvoker method)
46 {
47 this.method = method;
48 contextDataMap = ResteasyProviderFactory.getContextDataMap();
49 dispatcher = (SynchronousDispatcher) contextDataMap.get(Dispatcher.class);
50 HttpRequest httpRequest = (HttpRequest) contextDataMap.get(HttpRequest.class);
51 if(httpRequest.getAsyncContext().isSuspended())
52 asyncResponse = httpRequest.getAsyncContext().getAsyncResponse();
53 else
54 asyncResponse = httpRequest.getAsyncContext().suspend();
55 }
56
57 public static AsyncResponseConsumer makeAsyncResponseConsumer(ResourceMethodInvoker method, AsyncResponseProvider<?> asyncResponseProvider) {
58 return new CompletionStageResponseConsumer(method, asyncResponseProvider);
59 }
60
61 public static AsyncResponseConsumer makeAsyncResponseConsumer(ResourceMethodInvoker method, AsyncStreamProvider<?> asyncStreamProvider) {
62 if(method.isSse())
63 {
64 return new AsyncStreamSseResponseConsumer(method, asyncStreamProvider);
65 }
66 for (Annotation annotation : method.getMethodAnnotations())
67 {
68 if(annotation.annotationType() == Stream.class)
69 {
70 return new AsyncStreamingResponseConsumer(method, asyncStreamProvider);
71 }
72 }
73 return new AsyncStreamCollectorResponseConsumer(method, asyncStreamProvider);
74 }
75
76 protected void doComplete() {
77 asyncResponse.complete();
78 }
79
80 synchronized final public void complete(Throwable t)
81 {
82 if (!isComplete)
83 {
84 isComplete = true;
85 doComplete();
86 asyncResponse.completionCallbacks(t);
87 ResteasyProviderFactory.removeContextDataLevel();
88 }
89 }
90
91 protected void internalResume(Object entity, Consumer<Throwable> onComplete)
92 {
93 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
94 HttpRequest httpRequest = (HttpRequest) contextDataMap.get(HttpRequest.class);
95 HttpResponse httpResponse = (HttpResponse) contextDataMap.get(HttpResponse.class);
96
97 BuiltResponse builtResponse = createResponse(entity, httpRequest);
98 try
99 {
100 sendBuiltResponse(builtResponse, httpRequest, httpResponse, e -> {
101 if(e != null)
102 {
103 exceptionWhileResuming(e);
104 }
105 onComplete.accept(e);
106 });
107 }
108 catch (IOException e)
109 {
110 onComplete.accept(e);
111 exceptionWhileResuming(e);
112 }
113 }
114
115 private void exceptionWhileResuming(Throwable e)
116 {
117 try
118 {
119 // OK, not funny: if this is not a handled exception, it will just be logged and rethrown, so ignore it and move on
120 internalResume(e, t -> {});
121 }
122 catch(Throwable t2)
123 {
124 }
125 // be done with this stream
126 complete(e);
127 }
128
129 protected void sendBuiltResponse(BuiltResponse builtResponse, HttpRequest httpRequest, HttpResponse httpResponse, Consumer<Throwable> onComplete) throws IOException
130 {
131 // send headers only if we're not streaming, or if we're sending the first stream element
132 boolean sendHeaders = sendHeaders();
133 ServerResponseWriter.writeNomapResponse(builtResponse, httpRequest, httpResponse, dispatcher.getProviderFactory(), onComplete, sendHeaders);
134 }
135
136 protected abstract boolean sendHeaders();
137
138 protected void internalResume(Throwable t, Consumer<Throwable> onComplete)
139 {
140 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
141 HttpRequest httpRequest = (HttpRequest) contextDataMap.get(HttpRequest.class);
142 HttpResponse httpResponse = (HttpResponse) contextDataMap.get(HttpResponse.class);
143 dispatcher.writeException(httpRequest, httpResponse, t, onComplete);
144 }
145
146 protected BuiltResponse createResponse(Object entity, HttpRequest httpRequest)
147 {
148 BuiltResponse builtResponse = null;
149 if (entity == null)
150 {
151 builtResponse = (BuiltResponse) Response.noContent().build();
152 }
153 else if (entity instanceof BuiltResponse)
154 {
155 builtResponse = (BuiltResponse) entity;
156 }
157 else if (entity instanceof Response)
158 {
159 Response r = (Response) entity;
160 Headers<Object> metadata = new Headers<Object>();
161 metadata.putAll(r.getMetadata());
162 builtResponse = new BuiltResponse(r.getStatus(), r.getStatusInfo().getReasonPhrase(), metadata, r.getEntity(), method.getMethodAnnotations());
163 }
164 else
165 {
166 if (method == null)
167 {
168 throw new IllegalStateException(Messages.MESSAGES.unknownMediaTypeResponseEntity());
169 }
170 BuiltResponse jaxrsResponse = (BuiltResponse) Response.ok(entity).build();
171 // it has to be a Publisher<X>, so extract the X and wrap it around a List<X>
172 // FIXME: actually the provider should extract that, because it could come from another type param
173 // before conversion to Publisher
174 Type unwrappedType = ((ParameterizedType)method.getGenericReturnType()).getActualTypeArguments()[0];
175 Type newType = adaptGenericType(unwrappedType);
176
177 jaxrsResponse.setGenericType(newType);
178 jaxrsResponse.addMethodAnnotations(method.getMethodAnnotations());
179 builtResponse = jaxrsResponse;
180 }
181
182 return builtResponse;
183 }
184
185 protected Type adaptGenericType(Type unwrappedType)
186 {
187 return unwrappedType;
188 }
189
190 private static class CompletionStageResponseConsumer extends AsyncResponseConsumer implements BiConsumer<Object, Throwable>
191 {
192 private AsyncResponseProvider<?> asyncResponseProvider;
193
194 public CompletionStageResponseConsumer(ResourceMethodInvoker method, AsyncResponseProvider<?> asyncResponseProvider)
195 {
196 super(method);
197 this.asyncResponseProvider = asyncResponseProvider;
198 }
199
200 @Override
201 protected boolean sendHeaders()
202 {
203 return true;
204 }
205
206 @Override
207 public void accept(Object t, Throwable u)
208 {
209 if (t != null || u == null)
210 {
211 internalResume(t, x -> complete(null));
212 }
213 else
214 {
215 internalResume(u, x -> complete(u));
216 }
217 }
218
219 @Override
220 public void subscribe(Object rtn)
221 {
222 @SuppressWarnings({ "unchecked", "rawtypes" })
223 CompletionStage<?> stage = ((AsyncResponseProvider)asyncResponseProvider).toCompletionStage(rtn);
224 stage.whenComplete(this);
225 }
226 }
227
228 private abstract static class AsyncStreamResponseConsumer extends AsyncResponseConsumer implements Subscriber<Object>
229 {
230 protected Subscription subscription;
231 private AsyncStreamProvider<?> asyncStreamProvider;
232
233 public AsyncStreamResponseConsumer(ResourceMethodInvoker method, AsyncStreamProvider<?> asyncStreamProvider)
234 {
235 super(method);
236 this.asyncStreamProvider = asyncStreamProvider;
237 }
238
239 @Override
240 protected void doComplete()
241 {
242 // we can be done by exception before we've even subscribed
243 if(subscription != null)
244 subscription.cancel();
245 super.doComplete();
246 }
247
248 @Override
249 public void onComplete()
250 {
251 complete(null);
252 }
253
254 @Override
255 public void onError(Throwable t)
256 {
257 internalResume(t, x -> complete(t));
258 }
259
260 /**
261 * Subclass to collect the next element and inform if you want more.
262 * @param element the next element to collect
263 * @return true if you want more elements, false if not
264 */
265 protected void addNextElement(Object element)
266 {
267 internalResume(element, t -> {
268 if(t != null)
269 complete(t);
270 });
271 }
272
273 @Override
274 public void onNext(Object v)
275 {
276 addNextElement(v);
277 }
278
279 @Override
280 public void onSubscribe(Subscription subscription)
281 {
282 this.subscription = subscription;
283 subscription.request(1);
284 }
285
286 @Override
287 public void subscribe(Object rtn)
288 {
289 @SuppressWarnings({ "unchecked", "rawtypes" })
290 Publisher<?> stage = ((AsyncStreamProvider)asyncStreamProvider).toAsyncStream(rtn);
291 stage.subscribe(this);
292 }
293 }
294
295 private static class AsyncStreamingResponseConsumer extends AsyncStreamResponseConsumer
296 {
297 private boolean sentEntity;
298
299 public AsyncStreamingResponseConsumer(ResourceMethodInvoker method, AsyncStreamProvider<?> asyncStreamProvider)
300 {
301 super(method, asyncStreamProvider);
302 }
303
304 @Override
305 protected void sendBuiltResponse(BuiltResponse builtResponse, HttpRequest httpRequest, HttpResponse httpResponse, Consumer<Throwable> onComplete) throws IOException
306 {
307 super.sendBuiltResponse(builtResponse, httpRequest, httpResponse, onComplete);
308 sentEntity = true;
309 }
310
311 protected void addNextElement(Object element)
312 {
313 internalResume(element, t -> {
314 if(t != null)
315 {
316 complete(t);
317 }
318 else
319 {
320 subscription.request(1);
321 }
322 });
323 }
324
325 @Override
326 protected boolean sendHeaders()
327 {
328 return !sentEntity;
329 }
330 }
331
332 private static class AsyncStreamCollectorResponseConsumer extends AsyncStreamResponseConsumer
333 {
334 private List<Object> collector = new ArrayList<Object>();
335
336 public AsyncStreamCollectorResponseConsumer(ResourceMethodInvoker method, AsyncStreamProvider<?> asyncStreamProvider)
337 {
338 super(method, asyncStreamProvider);
339 }
340
341 @Override
342 protected boolean sendHeaders()
343 {
344 return true;
345 }
346
347 @Override
348 protected void addNextElement(Object element)
349 {
350 collector.add(element);
351 subscription.request(1);
352 }
353
354 @Override
355 public void onComplete()
356 {
357 internalResume(collector, t -> complete(t));
358 }
359
360 @Override
361 protected Type adaptGenericType(Type unwrappedType)
362 {
363 // we want a List<returnType>
364 return new ParameterizedType()
365 {
366
367 @Override
368 public Type[] getActualTypeArguments() {
369 return new Type[]{unwrappedType};
370 }
371
372 @Override
373 public Type getOwnerType() {
374 return null;
375 }
376
377 @Override
378 public Type getRawType() {
379 return List.class;
380 }
381 // FIXME: equals/hashCode/toString?
382 };
383 }
384 }
385
386 private static class AsyncStreamSseResponseConsumer extends AsyncStreamResponseConsumer
387 {
388 private SseImpl sse;
389 private SseEventSink sseEventSink;
390 private volatile boolean onCompleteReceived = false;
391 private volatile boolean sendingEvent = false;
392
393 private AsyncStreamSseResponseConsumer(ResourceMethodInvoker method, AsyncStreamProvider<?> asyncStreamProvider)
394 {
395 super(method, asyncStreamProvider);
396 sse = new SseImpl();
397 sseEventSink = ResteasyProviderFactory.getContextData(SseEventSink.class);
398 }
399
400 @Override
401 protected void doComplete()
402 {
403 // don't call super.doComplete which completes the asyncContext because Sse does that
404 subscription.cancel();
405 sseEventSink.close();
406 }
407
408 @Override
409 protected void addNextElement(Object element)
410 {
411 super.addNextElement(element);
412 }
413
414 @Override
415 public synchronized void onComplete()
416 {
417 onCompleteReceived = true;
418 if(sendingEvent == false)
419 super.onComplete();
420 }
421
422 @Override
423 protected void sendBuiltResponse(BuiltResponse builtResponse, HttpRequest httpRequest, HttpResponse httpResponse, Consumer<Throwable> onComplete)
424 {
425 ServerResponseWriter.setResponseMediaType(builtResponse, httpRequest, httpResponse, dispatcher.getProviderFactory(), method);
426 OutboundSseEvent event = sse.newEventBuilder()
427 .mediaType(builtResponse.getMediaType())
428 .data(builtResponse.getEntityClass(), builtResponse.getEntity())
429 .build();
430 sendingEvent = true;
431 // we can only get onComplete after we return from this method
432 try {
433 sseEventSink.send(event).whenComplete((val, ex) -> {
434 synchronized(this) {
435 sendingEvent = false;
436 if(onCompleteReceived)
437 super.onComplete();
438 else if(ex != null)
439 {
440 // cancel the subscription
441 complete(ex);
442 onComplete.accept(ex);
443 }
444 else
445 {
446 // we're good, ask for the next one
447 subscription.request(1);
448 onComplete.accept(ex);
449 }
450 }
451 });
452 }catch(Exception x) {
453 // most likely connection closed
454 complete(x);
455 onComplete.accept(x);
456 }
457 }
458
459 @Override
460 protected boolean sendHeaders()
461 {
462 // never actually called since we override sendBuiltResponse
463 return false;
464 }
465 }
466
467 public abstract void subscribe(Object rtn);
468 }
00 package org.jboss.resteasy.core;
11
2 import org.jboss.resteasy.plugins.providers.sse.SseImpl;
23 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
34 import org.jboss.resteasy.spi.HttpRequest;
45 import org.jboss.resteasy.spi.HttpResponse;
89 import javax.ws.rs.container.ResourceInfo;
910 import javax.ws.rs.core.Application;
1011 import javax.ws.rs.ext.Providers;
12 import javax.ws.rs.sse.Sse;
13 import javax.ws.rs.sse.SseEventSink;
1114
1215 import java.lang.reflect.InvocationHandler;
1316 import java.lang.reflect.InvocationTargetException;
3740 // we always inject a proxy for interface types just in case the per-request target is a pooled object
3841 // i.e. in the case of an SLSB
3942 if (type.equals(Providers.class)) return factory;
40 if (!type.isInterface())
43 if (!type.isInterface() || (ResteasyProviderFactory.EE8_PREVIEW_MODE && type.equals(SseEventSink.class)))
4144 {
4245 return ResteasyProviderFactory.getContextData(type);
46 }
47 else if (ResteasyProviderFactory.EE8_PREVIEW_MODE && type.equals(Sse.class))
48 {
49 return new SseImpl();
4350 }
4451 return createProxy();
4552 }
5057 {
5158 try
5259 {
60
5361 Object delegate = ResteasyProviderFactory.getContextData(type);
5462 if (delegate == null)
5563 {
5765 if (o instanceof ResourceInfo && ("getResourceMethod".equals(name) || "getResourceClass".equals(name)))
5866 {
5967 return null;
68 }
69
70 if ("getContextResolver".equals(name))
71 {
72 return method.invoke(factory, objects);
6073 }
6174 throw new LoggableFailure(Messages.MESSAGES.unableToFindContextualData(type.getName()));
6275 }
8093 public Object inject()
8194 {
8295 //if (type.equals(Providers.class)) return factory;
83 if (type.equals(Application.class))
96 if (type.equals(Application.class) || (ResteasyProviderFactory.EE8_PREVIEW_MODE && type.equals(SseEventSink.class)))
8497 {
85 return ResteasyProviderFactory.getContextData(Application.class);
98 return ResteasyProviderFactory.getContextData(type);
99 }
100 else if (ResteasyProviderFactory.EE8_PREVIEW_MODE && type.equals(Sse.class))
101 {
102 return new SseImpl();
86103 }
87104 else if (!type.isInterface())
88105 {
2828 import java.lang.reflect.AccessibleObject;
2929 import java.lang.reflect.Constructor;
3030 import java.lang.reflect.ParameterizedType;
31 import java.lang.reflect.Proxy;
3132 import java.lang.reflect.Type;
3233 import java.security.AccessController;
3334 import java.security.PrivilegedAction;
3435 import java.util.List;
3536 import java.util.Map;
37 import java.util.concurrent.ConcurrentHashMap;
3638
3739 import static org.jboss.resteasy.util.FindAnnotation.findAnnotation;
3840
4345 @SuppressWarnings("unchecked")
4446 public class InjectorFactoryImpl implements InjectorFactory
4547 {
48 private ConcurrentHashMap<Class<?>, Class<?>> contextProxyCache = new ConcurrentHashMap<Class<?>, Class<?>>();
49
50
4651 @Override
4752 public ConstructorInjector createConstructor(Constructor constructor, ResteasyProviderFactory providerFactory)
4853 {
118123 case SUSPEND:
119124 return new SuspendInjector(parameter.getSuspendTimeout(), parameter.getType());
120125 case CONTEXT:
121 return new ContextParameterInjector(null, parameter.getType(), providerFactory);
126 return createContextProxy(parameter.getType(), providerFactory);
122127 case SUSPENDED:
123128 return new AsynchronousResponseInjector();
124129 case MESSAGE_BODY:
214219 }
215220 else if (findAnnotation(annotations, Context.class) != null)
216221 {
217 return new ContextParameterInjector(null, type, providerFactory);
222 return createContextProxy(type, providerFactory);
218223 }
219224 else if ((suspended = findAnnotation(annotations, Suspended.class)) != null)
220225 {
233238 return null;
234239 }
235240 }
236 }
241
242 private ValueInjector createContextProxy(final Class type, ResteasyProviderFactory providerFactory)
243 {
244 Class proxy = null;
245 if (type.isInterface())
246 {
247 proxy = contextProxyCache.get(type);
248 if (proxy == null)
249 {
250 ClassLoader typeClassLoader;
251 if (System.getSecurityManager() == null)
252 {
253 typeClassLoader = type.getClassLoader();
254 }
255 else
256 {
257 typeClassLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
258 {
259 @Override
260 public ClassLoader run()
261 {
262 return type.getClassLoader();
263 }
264 });
265 }
266 proxy = Proxy.getProxyClass(typeClassLoader, type);
267 contextProxyCache.putIfAbsent(type, proxy);
268 }
269 }
270 return new ContextParameterInjector(proxy, type, providerFactory);
271 }
272
273 }
271271 {
272272 this.clazz = new WeakReference(clazz);
273273 this.mediaType = mediaType;
274 int result = getClazz().hashCode();
274 int result = clazz.hashCode();
275275 result = 31 * result + (mediaType.getType() != null ? mediaType.getType().hashCode() : 0) + (mediaType.getSubtype() != null ? mediaType.getSubtype().hashCode() : 0);
276276 hash = result;
277277 }
290290 CachedMediaTypeAndClass that = (CachedMediaTypeAndClass) o;
291291
292292 // WeakReference may have GC'd
293 if (getClazz() == null || that.getClazz() == null) return false;
294
295 if (!getClazz().equals(that.getClazz())) return false;
293 Class<?> clazz = getClazz();
294 if (clazz == null || that.getClazz() == null) return false;
295
296 if (!clazz.equals(that.getClazz())) return false;
296297
297298 if (mediaType.getType() != null)
298299 {
00 package org.jboss.resteasy.core;
11
2 import org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext;
3 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
4 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistryListener;
5 import org.jboss.resteasy.core.interception.ServerReaderInterceptorContext;
6 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
7 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
8 import org.jboss.resteasy.plugins.server.servlet.HttpServletInputMessage;
9 import org.jboss.resteasy.spi.BadRequestException;
10 import org.jboss.resteasy.spi.HttpRequest;
11 import org.jboss.resteasy.spi.HttpResponse;
12 import org.jboss.resteasy.spi.MarshalledEntity;
13 import org.jboss.resteasy.spi.ReaderException;
14 import org.jboss.resteasy.spi.ResteasyProviderFactory;
15 import org.jboss.resteasy.util.FindAnnotation;
16 import org.jboss.resteasy.util.InputStreamToByteArray;
17 import org.jboss.resteasy.util.ThreadLocalStack;
18 import org.jboss.resteasy.util.Types;
19
20 import javax.ws.rs.Encoded;
21 import javax.ws.rs.NotSupportedException;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.core.MultivaluedMap;
24 import javax.ws.rs.ext.MessageBodyReader;
25 import javax.ws.rs.ext.ReaderInterceptor;
26 import java.io.ByteArrayInputStream;
227 import java.io.InputStream;
328 import java.lang.annotation.Annotation;
429 import java.lang.reflect.AccessibleObject;
530 import java.lang.reflect.ParameterizedType;
631 import java.lang.reflect.Type;
7
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.MultivaluedMap;
10 import javax.ws.rs.ext.ReaderInterceptor;
11
12 import org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext;
13 import org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistry;
14 import org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistryListener;
15 import org.jboss.resteasy.core.interception.jaxrs.ServerReaderInterceptorContext;
16 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
17 import org.jboss.resteasy.spi.HttpRequest;
18 import org.jboss.resteasy.spi.HttpResponse;
19 import org.jboss.resteasy.spi.MarshalledEntity;
20 import org.jboss.resteasy.spi.ReaderException;
21 import org.jboss.resteasy.spi.ResteasyProviderFactory;
22 import org.jboss.resteasy.util.InputStreamToByteArray;
23 import org.jboss.resteasy.util.ThreadLocalStack;
24 import org.jboss.resteasy.util.Types;
32 import java.util.List;
33 import java.util.Map.Entry;
2534
2635 /**
2736 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
132141 //throw new BadRequestException("content-type was null and expecting to extract a body into " + this.target);
133142 }
134143
144 InputStream is = null;
145 if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.equals(mediaType))
146 {
147 if (request instanceof HttpServletInputMessage && ((HttpServletInputMessage) request).formParametersRead())
148 {
149 MultivaluedMap<String, String> map = request.getDecodedFormParameters();
150 if (map != null)
151 {
152 StringBuilder sb = new StringBuilder();
153 for (Entry<String, List<String>> entry : map.entrySet())
154 {
155 String key = entry.getKey();
156 sb.append(key);
157 List<String> values = entry.getValue();
158 for (String value : values)
159 {
160 if (!("".equals(value)))
161 {
162 sb.append("=").append(value);
163 }
164 sb.append("&");
165 }
166 }
167 if (sb.length() > 0 && '&' == sb.charAt(sb.length() - 1))
168 {
169 sb.deleteCharAt(sb.length() - 1);
170 }
171 String charset = "UTF-8";
172 if (mediaType.getParameters().get("charset") != null)
173 {
174 charset = mediaType.getParameters().get("charset");
175 }
176 try
177 {
178 is = new ByteArrayInputStream(sb.toString().getBytes(charset));
179 }
180 catch (Exception e)
181 {
182 LogMessages.LOGGER.charsetUnavailable(charset);
183 }
184 }
185 }
186 }
187
135188 try
136189 {
137 InputStream is = request.getInputStream();
190 if (is == null)
191 {
192 is = request.getInputStream();
193 }
138194 if (isMarshalledEntity)
139195 {
140196 is = new InputStreamToByteArray(is);
110110 List<String> list = request.getUri().getPathParameters(!encode).get(paramName);
111111 if (list == null)
112112 {
113 if (extractor.defaultValue == null) throw new InternalServerErrorException(Messages.MESSAGES.unknownPathParam(paramName, request.getUri().getPath()));
114113 if (extractor.isCollectionOrArray())
115114 {
116115 return extractor.extractValues(null);
0 package org.jboss.resteasy.core;
1
2 /**
3 *
4 * @author Nicolas NESMON
5 *
6 */
7 public interface PostResourceMethodInvoker {
8
9 void invoke();
10
11 }
0 package org.jboss.resteasy.core;
1
2 import java.util.ArrayList;
3 import java.util.Collections;
4 import java.util.List;
5
6 /**
7 *
8 * @author Nicolas NESMON
9 *
10 */
11 public class PostResourceMethodInvokers {
12
13 private final List<PostResourceMethodInvoker> invokers;
14
15 public PostResourceMethodInvokers() {
16 this.invokers = new ArrayList<>();
17 }
18
19 public List<PostResourceMethodInvoker> getInvokers() {
20 return this.invokers;
21 }
22
23 public void clear() {
24 this.invokers.clear();
25 }
26
27 public void addInvokers(PostResourceMethodInvoker... invokers) {
28 Collections.addAll(this.invokers, invokers);
29 }
30
31 }
22 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
33 import org.jboss.resteasy.specimpl.BuiltResponse;
44 import org.jboss.resteasy.spi.ApplicationException;
5 import org.jboss.resteasy.spi.Failure;
65 import org.jboss.resteasy.spi.HttpRequest;
76 import org.jboss.resteasy.spi.HttpResponse;
87 import org.jboss.resteasy.spi.InjectorFactory;
98 import org.jboss.resteasy.spi.InternalServerErrorException;
109 import org.jboss.resteasy.spi.MethodInjector;
11 import org.jboss.resteasy.spi.Registry;
1210 import org.jboss.resteasy.spi.ResourceFactory;
1311 import org.jboss.resteasy.spi.ResteasyProviderFactory;
1412 import org.jboss.resteasy.spi.ResteasyUriInfo;
15 import org.jboss.resteasy.spi.metadata.ResourceBuilder;
16 import org.jboss.resteasy.spi.metadata.ResourceClass;
1713 import org.jboss.resteasy.spi.metadata.ResourceLocator;
18 import org.jboss.resteasy.util.FindAnnotation;
1914 import org.jboss.resteasy.util.GetRestful;
2015
2116 import javax.ws.rs.NotFoundException;
2217
23 import java.lang.annotation.Annotation;
24 import java.lang.reflect.Field;
2518 import java.lang.reflect.InvocationTargetException;
2619 import java.lang.reflect.Method;
27 import java.lang.reflect.Proxy;
2820 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.regex.Pattern;
3021
3122 /**
3223 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
3324 * @version $Revision: 1 $
3425 */
35 @SuppressWarnings("unchecked")
3626 public class ResourceLocatorInvoker implements ResourceInvoker
3727 {
3828 protected InjectorFactory injector;
4030 protected ResourceFactory resource;
4131 protected ResteasyProviderFactory providerFactory;
4232 protected ResourceLocator method;
43 protected ConcurrentHashMap<Class, LocatorRegistry> cachedSubresources = new ConcurrentHashMap<Class, LocatorRegistry>();
33 protected ConcurrentHashMap<Class<?>, LocatorRegistry> cachedSubresources = new ConcurrentHashMap<Class<?>, LocatorRegistry>();
4434
4535 public ResourceLocatorInvoker(ResourceFactory resource, InjectorFactory injector, ResteasyProviderFactory providerFactory, ResourceLocator locator)
4636 {
7666 {
7767 uriInfo.pushCurrentResource(locator);
7868 Object subResource = method.getMethod().invoke(locator, args);
69 if (subResource instanceof Class)
70 {
71 subResource = this.providerFactory.injectedInstance((Class<?>)subResource);
72 }
7973 return subResource;
8074
8175 }
8781 {
8882 throw new ApplicationException(e.getCause());
8983 }
84 catch (SecurityException e)
85 {
86 throw new ApplicationException(e.getCause());
87 }
88
9089 }
9190
9291 public Method getMethod()
00 package org.jboss.resteasy.core;
11
2 import org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistry;
3 import org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistryListener;
4 import org.jboss.resteasy.core.interception.jaxrs.PostMatchContainerRequestContext;
2 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
3 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistryListener;
4 import org.jboss.resteasy.core.interception.PostMatchContainerRequestContext;
5 import org.jboss.resteasy.annotations.Stream;
56 import org.jboss.resteasy.core.registry.SegmentNode;
67 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
78 import org.jboss.resteasy.specimpl.BuiltResponse;
8 import org.jboss.resteasy.spi.ApplicationException;
9 import org.jboss.resteasy.spi.AsyncResponseProvider;
10 import org.jboss.resteasy.spi.AsyncStreamProvider;
911 import org.jboss.resteasy.spi.HttpRequest;
1012 import org.jboss.resteasy.spi.HttpResponse;
1113 import org.jboss.resteasy.spi.InjectorFactory;
1416 import org.jboss.resteasy.spi.ResteasyAsynchronousResponse;
1517 import org.jboss.resteasy.spi.ResteasyProviderFactory;
1618 import org.jboss.resteasy.spi.ResteasyUriInfo;
19 import org.jboss.resteasy.spi.UnhandledException;
20 import org.jboss.resteasy.spi.metadata.MethodParameter;
21 import org.jboss.resteasy.spi.metadata.Parameter;
1722 import org.jboss.resteasy.spi.metadata.ResourceMethod;
1823 import org.jboss.resteasy.spi.validation.GeneralValidator;
1924 import org.jboss.resteasy.spi.validation.GeneralValidatorCDI;
2025 import org.jboss.resteasy.util.FeatureContextDelegate;
2126
27 import javax.ws.rs.ProcessingException;
2228 import javax.ws.rs.container.ContainerRequestFilter;
2329 import javax.ws.rs.container.ContainerResponseFilter;
2430 import javax.ws.rs.container.DynamicFeature;
2834 import javax.ws.rs.core.Response;
2935 import javax.ws.rs.ext.ContextResolver;
3036 import javax.ws.rs.ext.WriterInterceptor;
31
32 import java.io.IOException;
37 import javax.ws.rs.sse.SseEventSink;
38
3339 import java.lang.annotation.Annotation;
3440 import java.lang.reflect.Method;
3541 import java.lang.reflect.Type;
5965 protected GeneralValidator validator;
6066 protected boolean isValidatable;
6167 protected boolean methodIsValidatable;
68 @SuppressWarnings("rawtypes")
69 protected AsyncResponseProvider asyncResponseProvider;
70 @SuppressWarnings("rawtypes")
71 AsyncStreamProvider asyncStreamProvider;
72 protected boolean isSse;
6273 protected ResourceInfo resourceInfo;
6374
6475 protected boolean expectsBody;
126137 }
127138 methodIsValidatable = validator.isMethodValidatable(getMethod());
128139 }
129 }
140
141 asyncResponseProvider = resourceMethodProviderFactory.getAsyncResponseProvider(method.getReturnType());
142 if(asyncResponseProvider == null){
143 asyncStreamProvider = resourceMethodProviderFactory.getAsyncStreamProvider(method.getReturnType());
144 }
145
146 if (isSseResourceMethod(method))
147 {
148 isSse = true;
149 method.markAsynchronous();
150 }
151 }
152
153 // spec section 9.3 Server API:
154 // A resource method that injects an SseEventSink and
155 // produces the media type text/event-stream is an SSE resource method.
156 private boolean isSseResourceMethod(ResourceMethod resourceMethod) {
157
158 // First exclusive condition to be a SSE resource method is to only
159 // produce text/event-stream
160 MediaType[] producedMediaTypes = resourceMethod.getProduces();
161 boolean onlyProduceServerSentEventsMediaType = ResteasyProviderFactory.EE8_PREVIEW_MODE
162 && producedMediaTypes != null && producedMediaTypes.length == 1
163 && MediaType.SERVER_SENT_EVENTS_TYPE.equals(producedMediaTypes[0]);
164 if (!onlyProduceServerSentEventsMediaType)
165 {
166 return false;
167 }
168
169 // Second condition to be a SSE resource method is to be injected with a
170 // SseEventSink parameter
171 MethodParameter[] resourceMethodParameters = resourceMethod.getParams();
172 if (resourceMethodParameters != null)
173 {
174 for (MethodParameter resourceMethodParameter : resourceMethodParameters)
175 {
176 if (Parameter.ParamType.CONTEXT.equals(resourceMethodParameter.getParamType())
177 && ResteasyProviderFactory.EE8_PREVIEW_MODE
178 && SseEventSink.class.equals(resourceMethodParameter.getType()))
179 {
180 return true;
181 }
182 }
183 }
184
185 // Resteasy specific:
186 // Or the given application should register a
187 // org.jboss.resteasy.spi.AsyncStreamProvider compatible with resource
188 // method return type and the resource method must not be annotated with
189 // any org.jboss.resteasy.annotations.Stream annotation
190 if (asyncStreamProvider != null)
191 {
192 for (Annotation annotation : resourceMethod.getAnnotatedMethod().getAnnotations())
193 {
194 if (annotation.annotationType() == Stream.class)
195 {
196 return false;
197 }
198 }
199 return true;
200 }
201
202 return false;
203 }
130204
131205 public void cleanup()
132206 {
226300 return method.getMethod();
227301 }
228302
303 public Object invokeDryRun(HttpRequest request, HttpResponse response) {
304 Object target = resource.createResource(request, response, resourceMethodProviderFactory);
305 return invokeDryRun(request, response, target);
306 }
229307
230308
231309 public BuiltResponse invoke(HttpRequest request, HttpResponse response)
234312 return invoke(request, response, target);
235313 }
236314
237 public BuiltResponse invoke(HttpRequest request, HttpResponse response, Object target)
315 public Object invokeDryRun(HttpRequest request, HttpResponse response, Object target)
238316 {
239317 request.setAttribute(ResourceMethodInvoker.class.getName(), this);
240318 incrementMethodCount(request.getHttpMethod());
244322 uriInfo.pushMatchedURI(uriInfo.getMatchingPath());
245323 }
246324 uriInfo.pushCurrentResource(target);
325 Object rtn = invokeOnTargetDryRun(request, response, target);
326 return rtn;
327 }
328
329 public BuiltResponse invoke(HttpRequest request, HttpResponse response, Object target)
330 {
331 request.setAttribute(ResourceMethodInvoker.class.getName(), this);
332 incrementMethodCount(request.getHttpMethod());
333 ResteasyUriInfo uriInfo = (ResteasyUriInfo) request.getUri();
334 if (method.getPath() != null)
335 {
336 uriInfo.pushMatchedURI(uriInfo.getMatchingPath());
337 }
338 uriInfo.pushCurrentResource(target);
247339 BuiltResponse rtn = invokeOnTarget(request, response, target);
248340 return rtn;
249341 }
250
251 protected BuiltResponse invokeOnTarget(HttpRequest request, HttpResponse response, Object target)
342
343 protected Object invokeOnTargetDryRun(HttpRequest request, HttpResponse response, Object target)
252344 {
253345 ResteasyProviderFactory.pushContext(ResourceInfo.class, resourceInfo); // we don't pop so writer interceptors can get at this
254
255
256 PostMatchContainerRequestContext requestContext = new PostMatchContainerRequestContext(request, this);
257 for (ContainerRequestFilter filter : requestFilters)
258 {
259 try
260 {
261 filter.filter(requestContext);
262 }
263 catch (IOException e)
264 {
265 throw new ApplicationException(e);
266 }
267 BuiltResponse serverResponse = (BuiltResponse)requestContext.getResponseAbortedWith();
268 if (serverResponse != null)
269 {
270 return serverResponse;
271 }
272 }
273
274 if (validator != null)
275 {
276 if (isValidatable)
277 {
278 validator.validate(request, target);
279 }
280 if (methodIsValidatable)
281 {
282 request.setAttribute(GeneralValidator.class.getName(), validator);
283 }
284 else if (isValidatable)
285 {
286 validator.checkViolations(request);
287 }
288 }
289346
290347 Object rtn = null;
291348 try
292349 {
293 rtn = methodInjector.invoke(request, response, target);
350 rtn = internalInvokeOnTarget(request, response, target);
294351 }
295352 catch (RuntimeException ex)
296353 {
297 if (request.getAsyncContext().isSuspended())
354 throw new ProcessingException(ex);
355
356 }
357 return rtn;
358 }
359
360 protected BuiltResponse invokeOnTarget(HttpRequest request, HttpResponse response, Object target)
361 {
362 ResteasyProviderFactory.pushContext(ResourceInfo.class, resourceInfo); // we don't pop so writer interceptors can get at this
363
364 PostMatchContainerRequestContext requestContext = new PostMatchContainerRequestContext(request, this, requestFilters,
365 () -> invokeOnTargetAfterFilter(request, response, target));
366 // let it handle the continuation
367 return requestContext.filter();
368 }
369
370 protected BuiltResponse invokeOnTargetAfterFilter(HttpRequest request, HttpResponse response, Object target)
371 {
372 if (validator != null)
373 {
374 if (isValidatable)
375 {
376 validator.validate(request, target);
377 }
378 if (methodIsValidatable)
379 {
380 request.setAttribute(GeneralValidator.class.getName(), validator);
381 }
382 else if (isValidatable)
383 {
384 validator.checkViolations(request);
385 }
386 }
387
388 AsyncResponseConsumer asyncStreamResponseConsumer = null;
389 if (asyncResponseProvider != null)
390 {
391 asyncStreamResponseConsumer = AsyncResponseConsumer.makeAsyncResponseConsumer(this, asyncResponseProvider);
392 }
393 else if (asyncStreamProvider != null)
394 {
395 asyncStreamResponseConsumer = AsyncResponseConsumer.makeAsyncResponseConsumer(this, asyncStreamProvider);
396 }
397
398 Object rtn = null;
399 try
400 {
401 rtn = internalInvokeOnTarget(request, response, target);
402 }
403 catch (RuntimeException ex)
404 {
405 if (asyncStreamResponseConsumer != null)
406 {
407 // WARNING: this can throw if the exception is not mapped by the user, in
408 // which case we haven't completed the connection and called the callbacks
409 try
410 {
411 AsyncResponseConsumer consumer = asyncStreamResponseConsumer;
412 asyncStreamResponseConsumer.internalResume(ex, t -> consumer.complete(ex));
413 }
414 catch(UnhandledException x)
415 {
416 // make sure we call the callbacks before throwing to the container
417 request.getAsyncContext().getAsyncResponse().completionCallbacks(ex);
418 throw x;
419 }
420 return null;
421 }
422 else if (request.getAsyncContext().isSuspended())
298423 {
299424 try
300425 {
313438
314439 }
315440
316
317 if (request.getAsyncContext().isSuspended() || request.wasForwarded())
441 if(asyncStreamResponseConsumer != null)
442 {
443 asyncStreamResponseConsumer.subscribe(rtn);
444 return null;
445 }
446 if (request.getAsyncContext().isSuspended())
447 {
448 if(method.isAsynchronous())
449 return null;
450 // resume a sync request that got turned async by filters
451 request.getAsyncContext().getAsyncResponse().resume(rtn);
452 return null;
453 }
454 if (request.wasForwarded())
318455 {
319456 return null;
320457 }
331468 Response r = (Response)rtn;
332469 Headers<Object> metadata = new Headers<Object>();
333470 metadata.putAll(r.getMetadata());
334 rtn = new BuiltResponse(r.getStatus(), metadata, r.getEntity(), null);
471 rtn = new BuiltResponse(r.getStatus(), r.getStatusInfo().getReasonPhrase(), metadata, r.getEntity(), null);
335472 }
336473 BuiltResponse rtn1 = (BuiltResponse) rtn;
337474 rtn1.addMethodAnnotations(getMethodAnnotations());
365502 jaxrsResponse.addMethodAnnotations(getMethodAnnotations());
366503 return jaxrsResponse;
367504 }
368
505
506 private Object internalInvokeOnTarget(HttpRequest request, HttpResponse response, Object target) {
507 PostResourceMethodInvokers postResourceMethodInvokers = ResteasyProviderFactory
508 .getContextData(PostResourceMethodInvokers.class);
509 try {
510 Object toReturn = this.methodInjector.invoke(request, response, target);
511 if (postResourceMethodInvokers != null) {
512 postResourceMethodInvokers.getInvokers().forEach(e -> e.invoke());
513 }
514 return toReturn;
515 } finally {
516 if (postResourceMethodInvokers != null) {
517 postResourceMethodInvokers.clear();
518 }
519 }
520 }
521
369522 public void initializeAsync(ResteasyAsynchronousResponse asyncResponse)
370523 {
371524 asyncResponse.setAnnotations(method.getAnnotatedMethod().getAnnotations());
475628 }
476629 return MediaType.WILDCARD_TYPE;
477630 }
631
632
633
478634
479635 public Set<String> getHttpMethods()
480636 {
490646 {
491647 return method.getConsumes();
492648 }
649
650 public boolean isSse()
651 {
652 return isSse;
653 }
654
655 public void markMethodAsAsync()
656 {
657 method.markAsynchronous();
658 }
493659 }
00 package org.jboss.resteasy.core;
11
2 import java.security.AccessController;
3 import java.security.PrivilegedActionException;
4 import java.security.PrivilegedExceptionAction;
52 import org.jboss.resteasy.core.registry.RootClassNode;
63 import org.jboss.resteasy.core.registry.RootNode;
74 import org.jboss.resteasy.plugins.server.resourcefactory.JndiResourceFactory;
2118 import org.jboss.resteasy.spi.metadata.ResourceMethod;
2219 import org.jboss.resteasy.util.GetRestful;
2320 import org.jboss.resteasy.util.IsHttpMethod;
24 import org.jboss.resteasy.util.Types;
2521
2622 import javax.ws.rs.Path;
27
2823 import java.lang.reflect.Method;
2924 import java.lang.reflect.Proxy;
25 import java.security.AccessController;
26 import java.security.PrivilegedActionException;
27 import java.security.PrivilegedExceptionAction;
3028 import java.util.List;
3129 import java.util.Map;
3230 import java.util.Set;
230228 {
231229 for (Method method : getDeclaredMethods(clazz))
232230 {
233 Method _method = findAnnotatedMethod(clazz, method);
231 Method _method = ResourceBuilder.findAnnotatedMethod(clazz, method);
234232 if (_method != null && !java.lang.reflect.Modifier.isPublic(_method.getModifiers()))
235233 {
236234 LogMessages.LOGGER.JAXRSAnnotationsFoundAtNonPublicMethod(method.getDeclaringClass().getName(), method.getName());
278276 }
279277 }
280278
279 /**
280 * Resteasy 2.x does not properly handle sub-resource and sub-resource locator
281 * endpoints with the same uri. Resteasy 3.x does handle this properly. In
282 * assisting customers identify this issue during an upgrade from Resteasy 2 to 3
283 * provides a waring when the situation is found.
284 */
285 public void checkAmbiguousUri()
286 {
287 for (Map.Entry<String, List<ResourceInvoker>> entry : this.root.getBounded().entrySet())
288 {
289 List<ResourceInvoker> values = entry.getValue();
290 if (values.size() > 1) {
291 int locatorCnt = 0;
292 int methodCnt = 0;
293 for(ResourceInvoker rInvoker : values)
294 {
295 if (rInvoker instanceof ResourceLocatorInvoker)
296 {
297 locatorCnt++;
298 } else if (rInvoker instanceof ResourceMethodInvoker)
299 {
300 methodCnt++;
301 }
302 }
303 if (methodCnt > 0 && locatorCnt > 0)
304 {
305 StringBuilder sb = new StringBuilder();
306 int cnt = values.size();
307 for (int i=0; i < cnt; i++) {
308 ResourceInvoker exp = values.get(i);
309 sb.append(exp.getMethod().getDeclaringClass().getName())
310 .append(".")
311 .append(exp.getMethod().getName());
312 if (i < cnt-1)
313 {
314 sb.append(", ");
315 }
316 }
317 LogMessages.LOGGER.uriAmbiguity(entry.getKey(), sb.toString());
318 }
319 }
320 }
321 }
322
281323 protected void processMethod(ResourceFactory rf, String base, ResourceLocator method)
282324 {
283325 ResteasyUriBuilder builder = new ResteasyUriBuilder();
313355 }
314356 }
315357
316 private Method findAnnotatedInterfaceMethod(Class<?> root, Class<?> iface, Method implementation)
317 {
318 for (Method method : iface.getMethods())
319 {
320 if (method.isSynthetic()) continue;
321
322 if (!method.getName().equals(implementation.getName())) continue;
323 if (method.getParameterTypes().length != implementation.getParameterTypes().length) continue;
324
325 Method actual = Types.getImplementingMethod(root, method);
326 if (!actual.equals(implementation)) continue;
327
328 if (method.isAnnotationPresent(Path.class) || IsHttpMethod.getHttpMethods(method) != null)
329 return method;
330
331 }
332 for (Class<?> extended : iface.getInterfaces())
333 {
334 Method m = findAnnotatedInterfaceMethod(root, extended, implementation);
335 if (m != null)
336 return m;
337 }
338 return null;
339 }
340
341 private Method findAnnotatedMethod(Class<?> root, Method implementation)
342 {
343 // check the method itself
344 if (implementation.isAnnotationPresent(Path.class) || IsHttpMethod.getHttpMethods(implementation) != null)
345 return implementation;
346
347 // Per http://download.oracle.com/auth/otn-pub/jcp/jaxrs-1.0-fr-oth-JSpec/jaxrs-1.0-final-spec.pdf
348 // Section 3.2 Annotation Inheritance
349
350 // Check possible superclass declarations
351 for (Class<?> clazz = implementation.getDeclaringClass().getSuperclass(); clazz != null; clazz = clazz.getSuperclass())
352 {
353 try
354 {
355 Method method = clazz.getDeclaredMethod(implementation.getName(), implementation.getParameterTypes());
356 if (method.isAnnotationPresent(Path.class) || IsHttpMethod.getHttpMethods(method) != null)
357 return method;
358 }
359 catch (NoSuchMethodException e)
360 {
361 // ignore
362 }
363 }
364
365 // Not found yet, so next check ALL interfaces from the root,
366 // but ensure no redefinition by peer interfaces (ambiguous) to preserve logic found in
367 // original implementation
368 for (Class<?> clazz = root; clazz != null; clazz = clazz.getSuperclass())
369 {
370 Method method = null;
371 for (Class<?> iface : clazz.getInterfaces())
372 {
373 Method m = findAnnotatedInterfaceMethod(root, iface, implementation);
374 if (m != null)
375 {
376 if (method != null && !m.equals(method))
377 throw new RuntimeException(Messages.MESSAGES.ambiguousInheritedAnnotations(implementation));
378 method = m;
379 }
380 }
381 if (method != null)
382 return method;
383 }
384 return null;
385 }
386
387358 /**
388359 * Find all endpoints reachable by clazz and unregister them
389360 *
2626 this.setMetadata(response.getMetadata());
2727 this.setEntityClass(response.getEntityClass());
2828 this.setGenericType(response.getGenericType());
29 this.setReasonPhrase(response.getReasonPhrase());
2930 }
3031 }
00 package org.jboss.resteasy.core;
11
2 import org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext;
3 import org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl;
4 import org.jboss.resteasy.core.interception.jaxrs.ResponseContainerRequestContext;
5 import org.jboss.resteasy.core.interception.jaxrs.ServerWriterInterceptorContext;
2 import org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext;
3 import org.jboss.resteasy.core.interception.ContainerResponseContextImpl;
4 import org.jboss.resteasy.core.interception.ResponseContainerRequestContext;
5 import org.jboss.resteasy.core.interception.ServerWriterInterceptorContext;
66 import org.jboss.resteasy.core.registry.SegmentNode;
7 import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
78 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
89 import org.jboss.resteasy.specimpl.BuiltResponse;
910 import org.jboss.resteasy.spi.HttpRequest;
1011 import org.jboss.resteasy.spi.HttpResponse;
12 import org.jboss.resteasy.spi.ResteasyConfiguration;
1113 import org.jboss.resteasy.spi.ResteasyDeployment;
1214 import org.jboss.resteasy.spi.ResteasyProviderFactory;
1315 import org.jboss.resteasy.util.CommitHeaderOutputStream;
2022 import javax.ws.rs.core.HttpHeaders;
2123 import javax.ws.rs.core.MediaType;
2224 import javax.ws.rs.core.NewCookie;
25 import javax.ws.rs.core.Cookie;
2326 import javax.ws.rs.core.Response;
2427 import javax.ws.rs.ext.MessageBodyWriter;
2528 import javax.ws.rs.ext.WriterInterceptor;
3639 import java.util.List;
3740 import java.util.Map;
3841 import java.util.Map.Entry;
42 import java.util.function.Consumer;
3943
4044 /**
4145 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
4347 */
4448 public class ServerResponseWriter
4549 {
46 public static void writeNomapResponse(BuiltResponse jaxrsResponse, final HttpRequest request, final HttpResponse response, final ResteasyProviderFactory providerFactory) throws IOException
50 @FunctionalInterface
51 public static interface RunnableWithIOException {
52 public void run() throws IOException;
53 }
54
55 public static void writeNomapResponse(BuiltResponse jaxrsResponse, final HttpRequest request, final HttpResponse response,
56 final ResteasyProviderFactory providerFactory, Consumer<Throwable> onComplete) throws IOException
57 {
58 writeNomapResponse(jaxrsResponse, request, response, providerFactory, onComplete, true);
59 }
60
61 @Deprecated
62 public static void writeNomapResponse(BuiltResponse jaxrsResponse, final HttpRequest request, final HttpResponse response,
63 final ResteasyProviderFactory providerFactory) throws IOException
64 {
65 writeNomapResponse(jaxrsResponse, request, response, providerFactory, t -> {}, true);
66 }
67
68 @Deprecated
69 public static void writeNomapResponse(BuiltResponse jaxrsResponse, final HttpRequest request, final HttpResponse response,
70 final ResteasyProviderFactory providerFactory, boolean sendHeaders) throws IOException
71 {
72 writeNomapResponse(jaxrsResponse, request, response, providerFactory, t -> {}, sendHeaders);
73 }
74
75 public static void writeNomapResponse(BuiltResponse jaxrsResponse, final HttpRequest request, final HttpResponse response,
76 final ResteasyProviderFactory providerFactory, Consumer<Throwable> onComplete, boolean sendHeaders) throws IOException
4777 {
4878 ResourceMethodInvoker method =(ResourceMethodInvoker) request.getAttribute(ResourceMethodInvoker.class.getName());
4979
80 // do this even if we're not sending the headers, because this sets the content type in the response,
81 // which is used by marshalling, and NPEs otherwise
82 setResponseMediaType(jaxrsResponse, request, response, providerFactory, method);
83
84 executeFilters(jaxrsResponse, request, response, providerFactory, method, onComplete, () -> {
85 //[RESTEASY-1627] check on response.getOutputStream() to avoid resteasy-netty4 trying building a chunked response body for HEAD requests
86 if (jaxrsResponse.getEntity() == null || response.getOutputStream() == null)
87 {
88 response.setStatus(jaxrsResponse.getStatus());
89 commitHeaders(jaxrsResponse, response);
90 return;
91 }
92
93 Class type = jaxrsResponse.getEntityClass();
94 Object ent = jaxrsResponse.getEntity();
95 Type generic = jaxrsResponse.getGenericType();
96 Annotation[] annotations = jaxrsResponse.getAnnotations();
97 @SuppressWarnings(value = "unchecked")
98 final MediaType mt = jaxrsResponse.getMediaType();
99 MessageBodyWriter writer = providerFactory.getMessageBodyWriter(
100 type, generic, annotations, mt);
101 if (writer!=null)
102 LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName());
103
104 if (writer == null)
105 {
106 throw new NoMessageBodyWriterFoundFailure(type, mt);
107 }
108
109 if(sendHeaders)
110 response.setStatus(jaxrsResponse.getStatus());
111 final BuiltResponse built = jaxrsResponse;
112 CommitHeaderOutputStream.CommitCallback callback = new CommitHeaderOutputStream.CommitCallback()
113 {
114 private boolean committed;
115
116 @Override
117 public void commit()
118 {
119 if (committed) return;
120 committed = true;
121 commitHeaders(built, response);
122 }
123 };
124 OutputStream os = sendHeaders ? new CommitHeaderOutputStream(response.getOutputStream(), callback) : response.getOutputStream();
125
126 WriterInterceptor[] writerInterceptors = null;
127 if (method != null)
128 {
129 writerInterceptors = method.getWriterInterceptors();
130 }
131 else
132 {
133 writerInterceptors = providerFactory.getServerWriterInterceptorRegistry().postMatch(null, null);
134 }
135
136 AbstractWriterInterceptorContext writerContext = new ServerWriterInterceptorContext(writerInterceptors,
137 providerFactory, ent, type, generic, annotations, mt,
138 jaxrsResponse.getMetadata(), os, request);
139 writerContext.proceed();
140 if(sendHeaders) {
141 response.setOutputStream(writerContext.getOutputStream()); //propagate interceptor changes on the outputstream to the response
142 callback.commit(); // just in case the output stream is never used
143 }
144 });
145 }
146
147 public static void setResponseMediaType(BuiltResponse jaxrsResponse, HttpRequest request, HttpResponse response, ResteasyProviderFactory providerFactory, ResourceMethodInvoker method)
148 {
50149 if (jaxrsResponse.getEntity() != null)
51150 {
52151 if (jaxrsResponse.getMediaType() == null)
81180 }
82181 }
83182 }
84
85 executeFilters(jaxrsResponse, request, response, providerFactory, method);
86
87 //[RESTEASY-1627] check on response.getOutputStream() to avoid resteasy-netty4 trying building a chunked response body for HEAD requests
88 if (jaxrsResponse.getEntity() == null || response.getOutputStream() == null)
89 {
90 response.setStatus(jaxrsResponse.getStatus());
91 commitHeaders(jaxrsResponse, response);
92 return;
93 }
94
95 Class type = jaxrsResponse.getEntityClass();
96 Object ent = jaxrsResponse.getEntity();
97 Type generic = jaxrsResponse.getGenericType();
98 Annotation[] annotations = jaxrsResponse.getAnnotations();
99 @SuppressWarnings(value = "unchecked")
100 final MediaType mt = jaxrsResponse.getMediaType();
101 MessageBodyWriter writer = providerFactory.getMessageBodyWriter(
102 type, generic, annotations, mt);
103 if (writer!=null)
104 LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName());
105
106 if (writer == null)
107 {
108 throw new NoMessageBodyWriterFoundFailure(type, mt);
109 }
110
111 response.setStatus(jaxrsResponse.getStatus());
112 final BuiltResponse built = jaxrsResponse;
113 CommitHeaderOutputStream.CommitCallback callback = new CommitHeaderOutputStream.CommitCallback()
114 {
115 private boolean committed;
116
117 @Override
118 public void commit()
119 {
120 if (committed) return;
121 committed = true;
122 commitHeaders(built, response);
123 }
124 };
125 OutputStream os = new CommitHeaderOutputStream(response.getOutputStream(), callback);
126
127 WriterInterceptor[] writerInterceptors = null;
183 }
184
185 private static void executeFilters(BuiltResponse jaxrsResponse, HttpRequest request, HttpResponse response,
186 ResteasyProviderFactory providerFactory,
187 ResourceMethodInvoker method, Consumer<Throwable> onComplete, RunnableWithIOException continuation) throws IOException
188 {
189 ContainerResponseFilter[] responseFilters = null;
190
128191 if (method != null)
129192 {
130 writerInterceptors = method.getWriterInterceptors();
193 responseFilters = method.getResponseFilters();
131194 }
132195 else
133196 {
134 writerInterceptors = providerFactory.getServerWriterInterceptorRegistry().postMatch(null, null);
135 }
136
137 AbstractWriterInterceptorContext writerContext = new ServerWriterInterceptorContext(writerInterceptors,
138 providerFactory, ent, type, generic, annotations, mt,
139 jaxrsResponse.getMetadata(), os, request);
140 writerContext.proceed();
141 response.setOutputStream(writerContext.getOutputStream()); //propagate interceptor changes on the outputstream to the response
142 callback.commit(); // just in case the output stream is never used
143 }
144
145 private static void executeFilters(BuiltResponse jaxrsResponse, HttpRequest request, HttpResponse response, ResteasyProviderFactory providerFactory, ResourceMethodInvoker method) throws IOException
146 {
147 ContainerResponseFilter[] responseFilters = null;
148
149 if (method != null)
150 {
151 responseFilters = method.getResponseFilters();
197 responseFilters = providerFactory.getContainerResponseFilterRegistry().postMatch(null, null);
198 }
199
200 if (responseFilters != null)
201 {
202 ResponseContainerRequestContext requestContext = new ResponseContainerRequestContext(request);
203 ContainerResponseContextImpl responseContext = new ContainerResponseContextImpl(request, response, jaxrsResponse,
204 requestContext, responseFilters, onComplete, continuation);
205 // filter calls the continuation
206 responseContext.filter();
152207 }
153208 else
154209 {
155 responseFilters = providerFactory.getContainerResponseFilterRegistry().postMatch(null, null);
156 }
157
158 if (responseFilters != null)
159 {
160 ResponseContainerRequestContext requestContext = new ResponseContainerRequestContext(request);
161 ContainerResponseContextImpl responseContext = new ContainerResponseContextImpl(request, response, jaxrsResponse);
162 for (ContainerResponseFilter filter : responseFilters)
163 {
164 filter.filter(requestContext, responseContext);
210 try
211 {
212 continuation.run();
213 onComplete.accept(null);
214 }
215 catch(Throwable t)
216 {
217 onComplete.accept(t);
218 SynchronousDispatcher.rethrow(t);
165219 }
166220 }
167221 }
306360 map.remove(SegmentNode.RESTEASY_SERVER_HAS_PRODUCES.toLowerCase());
307361 chosen = new MediaType(chosen.getType(), chosen.getSubtype(), map);
308362 }
363 boolean hasQ = chosen.getParameters().containsKey("q");
364 boolean hasQs = chosen.getParameters().containsKey("qs");
365 if (hasQ || hasQs)
366 {
367 Map<String, String> map = new HashMap<String, String>(chosen.getParameters());
368 if (hasQ)
369 {
370 map.remove("q");
371 }
372 if (hasQs)
373 {
374 map.remove("qs");
375 }
376 chosen = new MediaType(chosen.getType(), chosen.getSubtype(), map);
377 }
309378 jaxrsResponse.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, chosen);
310379 }
311380
385454 response.addNewCookie(cookie);
386455 it.remove();
387456 }
388 }
389 if (cookies.size() < 1)
390 jaxrsResponse.getMetadata().remove(HttpHeaderNames.SET_COOKIE);
457 else
458 {
459 response.getOutputHeaders().add(javax.ws.rs.core.HttpHeaders.SET_COOKIE, next);
460 it.remove();
461 }
462 }
463
464 jaxrsResponse.getMetadata().remove(HttpHeaderNames.SET_COOKIE);
391465 }
392466 }
393467 if (jaxrsResponse.getMetadata() != null
00 package org.jboss.resteasy.core;
1
2 import org.jboss.resteasy.annotations.StringParameterUnmarshallerBinder;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.jboss.resteasy.spi.StringConverter;
6 import org.jboss.resteasy.spi.StringParameterUnmarshaller;
7 import org.jboss.resteasy.util.StringToPrimitive;
8 import org.jboss.resteasy.util.Types;
9
10 import javax.ws.rs.BadRequestException;
11 import javax.ws.rs.HeaderParam;
12 import javax.ws.rs.WebApplicationException;
13 import javax.ws.rs.ext.ParamConverter;
14 import javax.ws.rs.ext.RuntimeDelegate;
151
162 import java.lang.annotation.Annotation;
173 import java.lang.reflect.AccessibleObject;
2511 import java.util.ArrayList;
2612 import java.util.Collection;
2713 import java.util.Collections;
14 import java.util.Comparator;
2815 import java.util.HashSet;
16 import java.util.Iterator;
2917 import java.util.List;
18 import java.util.ListIterator;
19 import java.util.NavigableSet;
3020 import java.util.Set;
3121 import java.util.SortedSet;
3222 import java.util.TreeSet;
23 import java.util.function.Consumer;
24 import java.util.function.Predicate;
25 import java.util.function.UnaryOperator;
26
27 import javax.ws.rs.BadRequestException;
28 import javax.ws.rs.HeaderParam;
29 import javax.ws.rs.WebApplicationException;
30 import javax.ws.rs.ext.ParamConverter;
31 import javax.ws.rs.ext.RuntimeDelegate;
32
33 import org.jboss.resteasy.annotations.StringParameterUnmarshallerBinder;
34 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
35 import org.jboss.resteasy.spi.ResteasyProviderFactory;
36 import org.jboss.resteasy.spi.StringConverter;
37 import org.jboss.resteasy.spi.StringParameterUnmarshaller;
38 import org.jboss.resteasy.util.StringToPrimitive;
39 import org.jboss.resteasy.util.Types;
3340
3441 /**
3542 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
43 * @author Nicolas NESMON
3644 * @version $Revision: 1 $
3745 */
38 @SuppressWarnings(value = "unchecked")
46 @SuppressWarnings(value = { "unchecked", "deprecation" })
3947 public class StringParameterInjector
4048 {
4149 private static final ParamConverter<Character> characterParamConverter = new ParamConverter<Character>() {
5664
5765 };
5866
59 protected Class type;
60 protected Class baseType;
67 private static final class UnmodifiableArrayList<E> extends ArrayList<E>{
68
69 private static final long serialVersionUID = -4912938596876802150L;
70 private UnmodifiableArrayList(Collection<E>collection) {
71 super(collection);
72 }
73
74 @Override
75 public boolean add(E e) {throw new UnsupportedOperationException();}
76 @Override
77 public void add(int index, E element) {throw new UnsupportedOperationException();}
78 @Override
79 public boolean addAll(Collection<? extends E> c) {throw new UnsupportedOperationException();}
80 @Override
81 public void clear() {throw new UnsupportedOperationException();}
82 @Override
83 public boolean remove(Object o) {throw new UnsupportedOperationException();}
84 @Override
85 public boolean addAll(int index, Collection<? extends E> c) {throw new UnsupportedOperationException();}
86 @Override
87 public E remove(int index) {throw new UnsupportedOperationException();}
88 @Override
89 public boolean removeAll(Collection<?> c) {throw new UnsupportedOperationException();}
90 @Override
91 public boolean removeIf(Predicate<? super E> filter) {throw new UnsupportedOperationException();}
92 @Override
93 public void replaceAll(UnaryOperator<E> operator) {throw new UnsupportedOperationException();}
94 @Override
95 public boolean retainAll(Collection<?> c) {throw new UnsupportedOperationException();}
96 @Override
97 public E set(int index, E element) {throw new UnsupportedOperationException();}
98 @Override
99 public void sort(Comparator<? super E> c) {throw new UnsupportedOperationException();}
100
101 @Override
102 public List<E> subList(int fromIndex, int toIndex) {
103 return new UnmodifiableArrayList<>(super.subList(fromIndex, toIndex));
104 }
105
106 @Override
107 public Iterator<E> iterator() {
108 return new Iterator<E>() {
109 private final Iterator<? extends E> iterator = UnmodifiableArrayList.super.iterator();
110
111 @Override
112 public boolean hasNext() {
113 return iterator.hasNext();
114 }
115 @Override
116 public E next() {
117 return iterator.next();
118 }
119 @Override
120 public void remove() {throw new UnsupportedOperationException();}
121 @Override
122 public void forEachRemaining(Consumer<? super E> action) {
123 iterator.forEachRemaining(action);
124 }
125 };
126 }
127
128 @Override
129 public ListIterator<E> listIterator() {
130 return listIterator(0);
131 }
132
133 @Override
134 public ListIterator<E> listIterator(int index) {
135 return new ListIterator<E>() {
136 private final ListIterator<? extends E> iterator = UnmodifiableArrayList.super.listIterator(index);
137
138 @Override
139 public boolean hasNext() {
140 return iterator.hasNext();
141 }
142 @Override
143 public E next() {
144 return iterator.next();
145 }
146 @Override
147 public boolean hasPrevious() {
148 return iterator.hasPrevious();
149 }
150 @Override
151 public E previous() {
152 return iterator.previous();
153 }
154 @Override
155 public int nextIndex() {
156 return iterator.nextIndex();
157 }
158 @Override
159 public int previousIndex() {
160 return iterator.previousIndex();
161 }
162 @Override
163 public void remove() {throw new UnsupportedOperationException();}
164 @Override
165 public void set(E e) {throw new UnsupportedOperationException();}
166 @Override
167 public void add(E e) {throw new UnsupportedOperationException();}
168 @Override
169 public void forEachRemaining(Consumer<? super E> action) {
170 iterator.forEachRemaining(action);
171 }
172 };
173
174 }
175
176 }
177
178 private static final class UnmodifiableHashSet<E> extends HashSet<E>{
179
180 private static final long serialVersionUID = 9175388977415467750L;
181 private final boolean initialized;
182
183 private UnmodifiableHashSet(Collection<E>collection) {
184 super(collection);
185 this.initialized=true;
186 }
187
188 @Override
189 public boolean remove(Object o) {throw new UnsupportedOperationException();}
190 @Override
191 public void clear() {throw new UnsupportedOperationException();}
192 @Override
193 public boolean removeAll(Collection<?> c) {throw new UnsupportedOperationException();}
194 @Override
195 public boolean retainAll(Collection<?> c) {throw new UnsupportedOperationException();}
196 @Override
197 public boolean removeIf(Predicate<? super E> filter) {throw new UnsupportedOperationException();}
198
199 @Override
200 public boolean add(E e) {
201 //Called by constructor
202 if(initialized){
203 throw new UnsupportedOperationException();
204 }
205 return super.add(e);
206 }
207
208 @Override
209 public boolean addAll(Collection<? extends E> c) {
210 //Called by constructor
211 if(initialized){
212 throw new UnsupportedOperationException();
213 }
214 return super.addAll(c);
215 }
216
217 @Override
218 public Iterator<E> iterator() {
219 return new Iterator<E>() {
220 private final Iterator<? extends E> iterator = UnmodifiableHashSet.super.iterator();
221
222 @Override
223 public boolean hasNext() {
224 return iterator.hasNext();
225 }
226 @Override
227 public E next() {
228 return iterator.next();
229 }
230 @Override
231 public void remove() {throw new UnsupportedOperationException();}
232 @Override
233 public void forEachRemaining(Consumer<? super E> action) {
234 iterator.forEachRemaining(action);
235 }
236 };
237 }
238
239 }
240
241 private static final class UnmodifiableTreeSet<E> extends TreeSet<E>{
242
243 private static final long serialVersionUID = 6337958351217117300L;
244 private final boolean initialized;
245
246 private UnmodifiableTreeSet(Collection<E>collection) {
247 super(collection);
248 this.initialized=true;
249 }
250
251 private UnmodifiableTreeSet(Comparator<? super E> comparator,Collection<E>collection) {
252 super(comparator);
253 addAll(collection);
254 this.initialized=true;
255 }
256
257 @Override
258 public boolean remove(Object o) {throw new UnsupportedOperationException();}
259 @Override
260 public void clear() {throw new UnsupportedOperationException();}
261 @Override
262 public boolean removeAll(Collection<?> c) {throw new UnsupportedOperationException();}
263 @Override
264 public boolean retainAll(Collection<?> c) {throw new UnsupportedOperationException();}
265 @Override
266 public boolean removeIf(Predicate<? super E> filter) {throw new UnsupportedOperationException();}
267 @Override
268 public E pollFirst() {throw new UnsupportedOperationException();}
269 @Override
270 public E pollLast() {throw new UnsupportedOperationException();}
271
272 @Override
273 public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
274 return new UnmodifiableTreeSet<>(super.subSet(fromElement, fromInclusive, toElement, toInclusive));
275 }
276
277 @Override
278 public SortedSet<E> subSet(E fromElement, E toElement) {
279 return new UnmodifiableTreeSet<>(super.subSet(fromElement, toElement));
280 }
281
282 @Override
283 public NavigableSet<E> descendingSet() {
284 NavigableSet<E> descendingSet = super.descendingSet();
285 return new UnmodifiableTreeSet<>(descendingSet.comparator(), descendingSet);
286 }
287
288 @Override
289 public SortedSet<E> headSet(E toElement) {
290 return new UnmodifiableTreeSet<>(super.headSet(toElement));
291 }
292
293 @Override
294 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
295 return new UnmodifiableTreeSet<>(super.headSet(toElement, inclusive));
296 }
297
298 @Override
299 public SortedSet<E> tailSet(E fromElement) {
300 return new UnmodifiableTreeSet<>(super.tailSet(fromElement));
301 }
302
303 @Override
304 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
305 return new UnmodifiableTreeSet<>(super.tailSet(fromElement, inclusive));
306 }
307
308 @Override
309 public boolean add(E e) {
310 //Called by constructor
311 if(initialized){
312 throw new UnsupportedOperationException();
313 }
314 return super.add(e);
315 }
316
317 @Override
318 public boolean addAll(Collection<? extends E> c) {
319 //Called by constructor
320 if(initialized){
321 throw new UnsupportedOperationException();
322 }
323 return super.addAll(c);
324 }
325
326 @Override
327 public Iterator<E> iterator() {
328 return new Iterator<E>() {
329 private final Iterator<? extends E> iterator = UnmodifiableTreeSet.super.iterator();
330
331 @Override
332 public boolean hasNext() {
333 return iterator.hasNext();
334 }
335 @Override
336 public E next() {
337 return iterator.next();
338 }
339 @Override
340 public void remove() {throw new UnsupportedOperationException();}
341 @Override
342 public void forEachRemaining(Consumer<? super E> action) {
343 iterator.forEachRemaining(action);
344 }
345 };
346 }
347
348 @Override
349 public Iterator<E> descendingIterator() {
350 return new Iterator<E>() {
351 private final Iterator<? extends E> iterator = UnmodifiableTreeSet.super.descendingIterator();
352
353 @Override
354 public boolean hasNext() {
355 return iterator.hasNext();
356 }
357 @Override
358 public E next() {
359 return iterator.next();
360 }
361 @Override
362 public void remove() {throw new UnsupportedOperationException();}
363 @Override
364 public void forEachRemaining(Consumer<? super E> action) {
365 iterator.forEachRemaining(action);
366 }
367 };
368 }
369
370
371 }
372
373 protected Class<?> type;
374 protected Class<?> baseType;
61375 protected Type baseGenericType;
62 protected Constructor constructor;
376 protected Constructor<?> constructor;
63377 protected Method valueOf;
64378 protected String defaultValue;
65379 protected String paramName;
66 protected Class paramType;
380 protected Class<?> paramType;
67381 protected boolean isCollection;
382 protected boolean isArray;
383 @SuppressWarnings("rawtypes")
68384 protected Class<? extends Collection> collectionType;
69385 protected AccessibleObject target;
70 protected ParamConverter paramConverter;
71 protected StringConverter converter;
72 protected StringParameterUnmarshaller unmarshaller;
73 protected RuntimeDelegate.HeaderDelegate delegate;
386 protected ParamConverter<?> paramConverter;
387 protected StringConverter<?> converter;
388 protected StringParameterUnmarshaller<?> unmarshaller;
389 protected RuntimeDelegate.HeaderDelegate<?> delegate;
74390
75391 public StringParameterInjector()
76392 {
77393
78394 }
79395
80 public StringParameterInjector(Class type, Type genericType, String paramName, Class paramType, String defaultValue, AccessibleObject target, Annotation[] annotations, ResteasyProviderFactory factory)
396 public StringParameterInjector(Class<?> type, Type genericType, String paramName, Class<?> paramType, String defaultValue, AccessibleObject target, Annotation[] annotations, ResteasyProviderFactory factory)
81397 {
82398 initialize(type, genericType, paramName, paramType, defaultValue, target, annotations, factory);
83399 }
84400
85401 public boolean isCollectionOrArray()
86402 {
87 return isCollection || type.isArray();
403 return isCollection || isArray;
88404 }
89405
90 protected void initialize(Class type, Type genericType, String paramName, Class paramType, String defaultValue, AccessibleObject target, Annotation[] annotations, ResteasyProviderFactory factory)
406 protected void initialize(Class<?> type, Type genericType, String paramName, Class<?> paramType, String defaultValue, AccessibleObject target, Annotation[] annotations, ResteasyProviderFactory factory)
91407 {
92408 this.type = type;
93409 this.paramName = paramName;
96412 this.target = target;
97413 baseType = type;
98414 baseGenericType = genericType;
99
100 if (type.isArray()) baseType = type.getComponentType();
101 if (List.class.isAssignableFrom(type))
102 {
103 isCollection = true;
104 collectionType = ArrayList.class;
105 }
106 else if (SortedSet.class.isAssignableFrom(type))
107 {
108 isCollection = true;
109 collectionType = TreeSet.class;
110 }
111 else if (Set.class.isAssignableFrom(type))
112 {
113 isCollection = true;
114 collectionType = HashSet.class;
115 }
116 if (isCollection)
117 {
118 if (genericType != null && genericType instanceof ParameterizedType)
119 {
120 ParameterizedType zType = (ParameterizedType) genericType;
415
416 //Step 1: try to find a conversion mechanism using the type as it is
417 if(initialize(annotations, factory))
418 {
419 return;
420 }
421
422 //Step2: try to find a conversion mechanism if the type is an array type
423 if (type.isArray())
424 {
425 isArray = true;
426 baseType = type.getComponentType();
427 if(initialize(annotations, factory))
428 {
429 return ;
430 }
431 }
432
433 //Step 3: try to find a conversion mechanism if the type is a collection type
434 collectionType = convertParameterTypeToCollectionType();
435 if (collectionType != null)
436 {
437 isCollection = true;
438 if (genericType instanceof ParameterizedType)
439 {
440 ParameterizedType zType = (ParameterizedType) baseGenericType;
121441 baseType = Types.getRawType(zType.getActualTypeArguments()[0]);
122442 baseGenericType = zType.getActualTypeArguments()[0];
123443 }
126446 baseType = String.class;
127447 baseGenericType = null;
128448 }
129 }
130 if (!baseType.isPrimitive())
131 {
132 paramConverter = factory.getParamConverter(baseType, baseGenericType, annotations);
133 if (paramConverter != null) return;
134
135 unmarshaller = factory.createStringParameterUnmarshaller(baseType);
136 if (unmarshaller != null)
137 {
138 unmarshaller.setAnnotations(annotations);
139 return;
140 }
141
142 for (Annotation annotation : annotations)
143 {
144 StringParameterUnmarshallerBinder binder = annotation.annotationType().getAnnotation(StringParameterUnmarshallerBinder.class);
145 if (binder != null)
449 if(initialize(annotations, factory))
450 {
451 return;
452 }
453 }
454
455 throw new RuntimeException(Messages.MESSAGES.unableToFindConstructor(getParamSignature(), target, baseType.getName()));
456
457 }
458
459
460 private boolean initialize(Annotation[] annotations, ResteasyProviderFactory factory){
461
462 //No need to find any conversion mechanism if we are dealing with primitive type
463 if(baseType.isPrimitive())
464 {
465 return true;
466 }
467
468 // First try to find a ParamConverter if any
469 paramConverter = factory.getParamConverter(baseType, baseGenericType, annotations);
470 if (paramConverter != null)
471 {
472 return true;
473 }
474
475 // Else try to find a StringParameterUnmarshaller if any
476 unmarshaller = factory.createStringParameterUnmarshaller(baseType);
477 if (unmarshaller != null)
478 {
479 unmarshaller.setAnnotations(annotations);
480 return true;
481 }
482 for (Annotation annotation : annotations)
483 {
484 StringParameterUnmarshallerBinder binder = annotation.annotationType().getAnnotation(StringParameterUnmarshallerBinder.class);
485 if (binder != null)
486 {
487 try
488 {
489 unmarshaller = binder.value().newInstance();
490 }
491 catch (InstantiationException e)
492 {
493 throw new RuntimeException(e.getCause());
494 }
495 catch (IllegalAccessException e)
496 {
497 throw new RuntimeException(e);
498 }
499 factory.injectProperties(unmarshaller);
500 unmarshaller.setAnnotations(annotations);
501 return true;
502 }
503 }
504
505 // Else try to find a StringConverter if any
506 converter = factory.getStringConverter(baseType);
507 if (converter != null)
508 {
509 return true;
510 }
511
512 // Else try to find a RuntimeDelegate.HeaderDelegate if any
513 if (paramType.equals(HeaderParam.class))
514 {
515 delegate = factory.getHeaderDelegate(baseType);
516 if (delegate != null)
517 {
518 return true;
519 }
520 }
521
522 // Else try to find a public Constructor that accepts a single String argument if any
523 try
524 {
525 constructor = baseType.getConstructor(String.class);
526 if (!Modifier.isPublic(constructor.getModifiers()))
527 {
528 constructor = null;
529 }
530 else
531 {
532 return true;
533 }
534 }
535 catch (NoSuchMethodException ignored)
536 {
537
538 }
539
540 // Else try to find a public fromValue (JAXB enum) or valueOf or fromString method that accepts a single String argument if any.
541 try
542 {
543 // this is for JAXB generated enums.
544 Method fromValue = baseType.getDeclaredMethod("fromValue", String.class);
545 if (Modifier.isPublic(fromValue.getModifiers()))
546 {
547 for (Annotation ann : baseType.getAnnotations())
146548 {
147 try
549 if (ann.annotationType().getName().equals("javax.xml.bind.annotation.XmlEnum"))
148550 {
149 unmarshaller = binder.value().newInstance();
150 }
151 catch (InstantiationException e)
152 {
153 throw new RuntimeException(e.getCause());
154 }
155 catch (IllegalAccessException e)
156 {
157 throw new RuntimeException(e);
158 }
159 factory.injectProperties(unmarshaller);
160 unmarshaller.setAnnotations(annotations);
161 return;
162 }
163 }
164
165 converter = factory.getStringConverter(baseType);
166 if (converter != null) return;
167
168 if (paramType.equals(HeaderParam.class))
169 {
170 delegate = factory.getHeaderDelegate(baseType);
171 if (delegate != null) return;
172 }
173
174
175 try
176 {
177 constructor = baseType.getConstructor(String.class);
178 if (!Modifier.isPublic(constructor.getModifiers())) constructor = null;
179 }
180 catch (NoSuchMethodException ignored)
181 {
182
183 }
184 if (constructor == null)
185 {
186 try
187 {
188 // this is for JAXB generated enums.
189 Method fromValue = baseType.getDeclaredMethod("fromValue", String.class);
190 if (Modifier.isPublic(fromValue.getModifiers()))
191 {
192 for (Annotation ann : baseType.getAnnotations())
193 {
194 if (ann.annotationType().getName().equals("javax.xml.bind.annotation.XmlEnum"))
195 {
196 valueOf = fromValue;
197 }
198 }
551 valueOf = fromValue;
199552 }
200553 }
201 catch (NoSuchMethodException e)
554 }
555 }
556 catch (NoSuchMethodException e)
557 {
558 }
559 if (valueOf == null)
560 {
561 Method fromString = null;
562
563 try
564 {
565 fromString = baseType.getDeclaredMethod("fromString", String.class);
566 if (Modifier.isStatic(fromString.getModifiers()) == false) fromString = null;
567 }
568 catch (NoSuchMethodException ignored)
569 {
570 }
571 try
572 {
573 valueOf = baseType.getDeclaredMethod("valueOf", String.class);
574 if (Modifier.isStatic(valueOf.getModifiers()) == false) valueOf = null;
575 }
576 catch (NoSuchMethodException ignored)
577 {
578 }
579 // If enum use fromString if it exists: as defined in JAX-RS spec
580 if (baseType.isEnum())
581 {
582 if (fromString != null)
202583 {
584 valueOf = fromString;
203585 }
204 if (valueOf == null)
205 {
206 Method fromString = null;
207
208 try
209 {
210 fromString = baseType.getDeclaredMethod("fromString", String.class);
211 if (Modifier.isStatic(fromString.getModifiers()) == false) fromString = null;
212 }
213 catch (NoSuchMethodException ignored)
214 {
215 }
216 try
217 {
218 valueOf = baseType.getDeclaredMethod("valueOf", String.class);
219 if (Modifier.isStatic(valueOf.getModifiers()) == false) valueOf = null;
220 }
221 catch (NoSuchMethodException ignored)
222 {
223 }
224 // If enum use fromString if it exists: as defined in JAX-RS spec
225 if (baseType.isEnum())
226 {
227 if (fromString != null)
228 {
229 valueOf = fromString;
230 }
231 }
232 else if (valueOf == null)
233 {
234 valueOf = fromString;
235 }
236 if (valueOf == null)
237 {
238 if(Character.class.equals(baseType))
239 {
240 paramConverter = characterParamConverter;
241 }
242 else
243 {
244 throw new RuntimeException(Messages.MESSAGES.unableToFindConstructor(getParamSignature(), target, baseType.getName()));
245 }
246 }
247 }
248
249 }
250 }
586 }
587 else if (valueOf == null)
588 {
589 valueOf = fromString;
590 }
591 if (valueOf == null)
592 {
593 if(Character.class.equals(baseType))
594 {
595 paramConverter = characterParamConverter;
596 return true;
597 }
598 }
599 }
600
601 return valueOf != null;
251602 }
603
604 @SuppressWarnings("rawtypes")
605 private Class<? extends Collection> convertParameterTypeToCollectionType() {
606 if (List.class.equals(type) || ArrayList.class.equals(type)) {
607 return ArrayList.class;
608 } else if (SortedSet.class.equals(type) || TreeSet.class.equals(type)) {
609 return TreeSet.class;
610 } else if (Set.class.equals(type) || HashSet.class.equals(type)) {
611 return HashSet.class;
612 }
613 return null;
614 }
252615
253616 public String getParamSignature()
254617 {
257620
258621 public Object extractValues(List<String> values)
259622 {
260 if (values == null && (type.isArray() || isCollection) && defaultValue != null)
623 if (values == null && (isArray || isCollection) && defaultValue != null)
261624 {
262625 values = new ArrayList<String>(1);
263626 values.add(defaultValue);
266629 {
267630 values = Collections.emptyList();
268631 }
269 if (type.isArray())
632 if (isArray)
270633 {
271634 if (values == null) return null;
272635 Object vals = Array.newInstance(type.getComponentType(), values.size());
276639 else if (isCollection)
277640 {
278641 if (values == null) return null;
642 @SuppressWarnings("rawtypes")
279643 Collection collection = null;
280644 try
281645 {
289653 {
290654 collection.add(extractValue(str));
291655 }
292 return collection;
656 if (ArrayList.class.equals(collectionType)) {
657 return new UnmodifiableArrayList<>(collection);
658 } else if (TreeSet.class.equals(collectionType)) {
659 return new UnmodifiableTreeSet<>(collection);
660 } else if (HashSet.class.equals(collectionType)) {
661 return new UnmodifiableHashSet<>(collection);
662 }
663 throw new RuntimeException("Unable to handle "+collectionType);
293664 }
294665 else
295666 {
0 package org.jboss.resteasy.core;
1
2 import org.jboss.resteasy.annotations.Suspend;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
4 import org.jboss.resteasy.spi.AsynchronousResponse;
5 import org.jboss.resteasy.spi.HttpRequest;
6 import org.jboss.resteasy.spi.HttpResponse;
7 import org.jboss.resteasy.spi.ResteasyAsynchronousContext;
8 import org.jboss.resteasy.spi.ResteasyAsynchronousResponse;
9
10 import javax.ws.rs.core.Response;
11
12 /**
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 *
16 * @deprecated Replaced by org.jboss.resteasy.core.AsynchronousResponseInjector
17 *
18 * @see org.jboss.resteasy.core.AsynchronousResponseInjector
19 */
20 @Deprecated
21 public class SuspendInjector implements ValueInjector
22 {
23 private long suspend;
24
25 public SuspendInjector(long suspend, Class type)
26 {
27 if (!type.equals(AsynchronousResponse.class))
28 throw new IllegalArgumentException(Messages.MESSAGES.notValidInjectableType(type.getName()));
29 this.suspend = suspend;
30 }
31
32 public Object inject()
33 {
34 throw new IllegalStateException(Messages.MESSAGES.cannotInjectIntoForm());
35 }
36
37 public Object inject(HttpRequest request, HttpResponse response)
38 {
39 final ResteasyAsynchronousContext asynchronousContext = request.getAsyncContext();
40 final ResteasyAsynchronousResponse asynchronousResponse = asynchronousContext.suspend(suspend);
41 ResourceMethodInvoker invoker = (ResourceMethodInvoker)request.getAttribute(ResourceMethodInvoker.class.getName());
42 invoker.initializeAsync(asynchronousResponse);
43 return new AsynchronousResponse()
44 {
45 @Override
46 public void setResponse(Response response)
47 {
48 asynchronousResponse.resume(response);
49 }
50 };
51 }
0 package org.jboss.resteasy.core;
1
2 import org.jboss.resteasy.annotations.Suspend;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
4 import org.jboss.resteasy.spi.AsynchronousResponse;
5 import org.jboss.resteasy.spi.HttpRequest;
6 import org.jboss.resteasy.spi.HttpResponse;
7 import org.jboss.resteasy.spi.ResteasyAsynchronousContext;
8 import org.jboss.resteasy.spi.ResteasyAsynchronousResponse;
9
10 import javax.ws.rs.core.Response;
11
12 /**
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 *
16 * @deprecated Replaced by org.jboss.resteasy.core.AsynchronousResponseInjector
17 *
18 * @see org.jboss.resteasy.core.AsynchronousResponseInjector
19 */
20 @Deprecated
21 public class SuspendInjector implements ValueInjector
22 {
23 private long suspend;
24
25 public SuspendInjector(long suspend, Class type)
26 {
27 if (!type.equals(AsynchronousResponse.class))
28 throw new IllegalArgumentException(Messages.MESSAGES.notValidInjectableType(type.getName()));
29 this.suspend = suspend;
30 }
31
32 public Object inject()
33 {
34 throw new IllegalStateException(Messages.MESSAGES.cannotInjectIntoForm());
35 }
36
37 public Object inject(HttpRequest request, HttpResponse response)
38 {
39 final ResteasyAsynchronousContext asynchronousContext = request.getAsyncContext();
40 final ResteasyAsynchronousResponse asynchronousResponse = asynchronousContext.suspend(suspend);
41 ResourceMethodInvoker invoker = (ResourceMethodInvoker)request.getAttribute(ResourceMethodInvoker.class.getName());
42 invoker.initializeAsync(asynchronousResponse);
43 return new AsynchronousResponse()
44 {
45 @Override
46 public void setResponse(Response response)
47 {
48 asynchronousResponse.resume(response);
49 }
50 };
51 }
5252 }
00 package org.jboss.resteasy.core;
11
2 import java.io.IOException;
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.HashSet;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.Set;
10
11 import javax.ws.rs.NotFoundException;
12 import javax.ws.rs.container.ContainerRequestFilter;
13 import javax.ws.rs.container.ResourceContext;
14 import javax.ws.rs.core.HttpHeaders;
15 import javax.ws.rs.core.Request;
16 import javax.ws.rs.core.Response;
17 import javax.ws.rs.core.UriInfo;
18 import javax.ws.rs.ext.Providers;
19
20 import org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext;
2 import org.jboss.resteasy.core.interception.PreMatchContainerRequestContext;
213 import org.jboss.resteasy.plugins.server.servlet.Cleanable;
224 import org.jboss.resteasy.plugins.server.servlet.Cleanables;
235 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
3517 import org.jboss.resteasy.spi.ResteasyConfiguration;
3618 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3719 import org.jboss.resteasy.spi.UnhandledException;
20 import org.jboss.resteasy.util.HttpHeaderNames;
21
22 import javax.ws.rs.NotFoundException;
23 import javax.ws.rs.container.ContainerRequestFilter;
24 import javax.ws.rs.container.ResourceContext;
25 import javax.ws.rs.core.GenericEntity;
26 import javax.ws.rs.core.HttpHeaders;
27 import javax.ws.rs.core.MediaType;
28 import javax.ws.rs.core.Request;
29 import javax.ws.rs.core.Response;
30 import javax.ws.rs.core.UriInfo;
31 import javax.ws.rs.ext.Providers;
32
33 import java.io.IOException;
34 import java.lang.reflect.Type;
35 import java.util.function.Consumer;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Iterator;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Set;
3843
3944 /**
4045 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
98103 preprocessor.preProcess(request);
99104 }
100105 ContainerRequestFilter[] requestFilters = providerFactory.getContainerRequestFilterRegistry().preMatch();
101 PreMatchContainerRequestContext requestContext = new PreMatchContainerRequestContext(request);
102 for (ContainerRequestFilter filter : requestFilters)
103 {
104 filter.filter(requestContext);
105 aborted = requestContext.getResponseAbortedWith();
106 if (aborted != null) break;
107 }
106 // FIXME: support async
107 PreMatchContainerRequestContext requestContext = new PreMatchContainerRequestContext(request, requestFilters, null);
108 aborted = requestContext.filter();
108109 }
109110 catch (Exception e)
110111 {
119120 *
120121 * @return true if request should continue
121122 */
122 protected boolean preprocess(HttpRequest request, HttpResponse response)
123 protected void preprocess(HttpRequest request, HttpResponse response, Runnable continuation)
123124 {
124125 Response aborted = null;
126 PreMatchContainerRequestContext requestContext = null;
125127 try
126128 {
127129 for (HttpRequestPreprocessor preprocessor : this.requestPreprocessors)
129131 preprocessor.preProcess(request);
130132 }
131133 ContainerRequestFilter[] requestFilters = providerFactory.getContainerRequestFilterRegistry().preMatch();
132 PreMatchContainerRequestContext requestContext = new PreMatchContainerRequestContext(request);
133 for (ContainerRequestFilter filter : requestFilters)
134 {
135 filter.filter(requestContext);
136 aborted = requestContext.getResponseAbortedWith();
137 if (aborted != null) break;
138 }
134 requestContext = new PreMatchContainerRequestContext(request, requestFilters,
135 () -> {
136 continuation.run();
137 return null;
138 });
139 aborted = requestContext.filter();
139140 }
140141 catch (Exception e)
141142 {
142143 //logger.error("Failed in preprocess, mapping exception", e);
143 writeException(request, response, e);
144 return false;
144 // we only want to catch exceptions happening in the filters, not in the continuation
145 if(requestContext == null || !requestContext.startedContinuation())
146 {
147 writeException(request, response, e, t -> {});
148 return;
149 }
150 else
151 {
152 rethrow(e);
153 }
145154 }
146155 if (aborted != null)
147156 {
148157 writeResponse(request, response, aborted);
149 return false;
150 }
151 return true;
152 }
153
158 return;
159 }
160 }
161
162 public static <T extends Throwable> void rethrow(Throwable t) throws T
163 {
164 throw (T)t;
165 }
166
167 @Deprecated
154168 public void writeException(HttpRequest request, HttpResponse response, Throwable e)
169 {
170 writeException(request, response, e, t -> {});
171 }
172
173 public void writeException(HttpRequest request, HttpResponse response, Throwable e, Consumer<Throwable> onComplete)
155174 {
156175 if (!bufferExceptionEntityRead)
157176 {
169188 if (response.isCommitted())
170189 {
171190 LogMessages.LOGGER.debug(Messages.MESSAGES.responseIsCommitted());
191 onComplete.accept(null);
172192 return;
173193 }
174194 Response handledResponse = new ExceptionHandler(providerFactory, unwrappedExceptions).handleException(request, e);
179199 }
180200 try
181201 {
182 ServerResponseWriter.writeNomapResponse(((BuiltResponse) handledResponse), request, response, providerFactory);
202 ServerResponseWriter.writeNomapResponse(((BuiltResponse) handledResponse), request, response, providerFactory, onComplete);
183203 }
184204 catch (Exception e1)
185205 {
193213 try
194214 {
195215 pushContextObjects(request, response);
196 if (!preprocess(request, response)) return;
197 ResourceInvoker invoker = null;
198 try
199 {
200 invoker = getInvoker(request);
201 }
202 catch (Exception exception)
203 {
204 //logger.error("getInvoker() failed mapping exception", exception);
205 writeException(request, response, exception);
206 return;
207 }
208 invoke(request, response, invoker);
216 preprocess(request, response, () -> {
217 ResourceInvoker invoker = null;
218 try
219 {
220 try
221 {
222 invoker = getInvoker(request);
223 }
224 catch (Exception exception)
225 {
226 //logger.error("getInvoker() failed mapping exception", exception);
227 writeException(request, response, exception, t -> {});
228 return;
229 }
230 invoke(request, response, invoker);
231 }
232 finally
233 {
234 // we're probably clearing it twice but still required
235 clearContextData();
236 }
237 });
209238 }
210239 finally
211240 {
224253 try
225254 {
226255 pushContextObjects(request, response);
227 if (!preprocess(request, response)) return;
228 ResourceInvoker invoker = null;
229 try
230 {
231 invoker = getInvoker(request);
232 }
233 catch (Exception failure)
234 {
235 if (failure instanceof NotFoundException)
256 preprocess(request, response, () -> {
257 ResourceInvoker invoker = null;
258 try
236259 {
237 throw ((NotFoundException) failure);
260 try
261 {
262 invoker = getInvoker(request);
263 }
264 catch (Exception failure)
265 {
266 if (failure instanceof NotFoundException)
267 {
268 throw ((NotFoundException) failure);
269 }
270 else
271 {
272 //logger.error("getInvoker() failed mapping exception", failure);
273 writeException(request, response, failure, t->{});
274 return;
275 }
276 }
277 invoke(request, response, invoker);
238278 }
239 else
279 finally
240280 {
241 //logger.error("getInvoker() failed mapping exception", failure);
242 writeException(request, response, failure);
243 return;
281 // we're probably clearing it twice but still required
282 clearContextData();
244283 }
245 }
246 invoke(request, response, invoker);
284 });
247285 }
248286 finally
249287 {
296334
297335 contextDataMap.putAll(defaultContextObjects);
298336 contextDataMap.put(Cleanables.class, new Cleanables());
337 contextDataMap.put(PostResourceMethodInvokers.class, new PostResourceMethodInvokers());
299338 }
300339
301340 public Response internalInvocation(HttpRequest request, HttpResponse response, Object entity)
414453 catch (Exception e)
415454 {
416455 //logger.error("invoke() failed mapping exception", e);
417 writeException(request, response, e);
456 writeException(request, response, e, t->{});
418457 return;
419458 }
420459
421460 if (jaxrsResponse != null) writeResponse(request, response, jaxrsResponse);
422461 }
423462
463 @Deprecated
424464 public void asynchronousDelivery(HttpRequest request, HttpResponse response, Response jaxrsResponse) throws IOException
425465 {
466 asynchronousDelivery(request, response, jaxrsResponse, t -> {});
467 }
468
469 public void asynchronousDelivery(HttpRequest request, HttpResponse response, Response jaxrsResponse, Consumer<Throwable> onComplete) throws IOException
470 {
426471 if (jaxrsResponse == null) return;
427472 try
428473 {
429474 pushContextObjects(request, response);
430 ServerResponseWriter.writeNomapResponse((BuiltResponse) jaxrsResponse, request, response, providerFactory);
475 ServerResponseWriter.writeNomapResponse((BuiltResponse) jaxrsResponse, request, response, providerFactory, onComplete);
431476 }
432477 finally
433478 {
435480 }
436481 }
437482
483 public void unhandledAsynchronousException(HttpResponse response, Throwable ex) {
484 LogMessages.LOGGER.unhandledAsynchronousException(ex);
485 // unhandled exceptions need to be processed as they can't be thrown back to the servlet container
486 if (!response.isCommitted()) {
487 try
488 {
489 response.reset();
490 response.sendError(500);
491 }
492 catch (IOException e)
493 {
494
495 }
496 }
497 }
498
499 @Deprecated
438500 public void asynchronousExceptionDelivery(HttpRequest request, HttpResponse response, Throwable exception)
439501 {
502 asynchronousExceptionDelivery(request, response, exception, t -> {});
503 }
504
505 public void asynchronousExceptionDelivery(HttpRequest request, HttpResponse response, Throwable exception, Consumer<Throwable> onComplete)
506 {
440507 try
441508 {
442509 pushContextObjects(request, response);
443 writeException(request, response, exception);
510 writeException(request, response, exception, t -> {
511 if(t != null)
512 unhandledAsynchronousException(response, t);
513 onComplete.accept(null);
514 ResteasyProviderFactory.removeContextDataLevel();
515 });
444516 }
445517 catch (Throwable ex)
446518 {
447 LogMessages.LOGGER.unhandledAsynchronousException(ex);
448 // unhandled exceptions need to be processed as they can't be thrown back to the servlet container
449 if (!response.isCommitted()) {
450 try
451 {
452 response.reset();
453 response.sendError(500);
454 }
455 catch (IOException e)
456 {
457
458 }
459 }
460 }
461 finally
462 {
463 ResteasyProviderFactory.removeContextDataLevel();
519 onComplete.accept(ex);
520 unhandledAsynchronousException(response, ex);
464521 }
465522 }
466523
469526 {
470527 try
471528 {
472 ServerResponseWriter.writeNomapResponse((BuiltResponse) jaxrsResponse, request, response, providerFactory);
529 ServerResponseWriter.writeNomapResponse((BuiltResponse) jaxrsResponse, request, response, providerFactory,
530 t -> {
531 if(t != null)
532 writeException(request, response, t, t2 -> {});
533 });
473534 }
474535 catch (Exception e)
475536 {
476537 //logger.error("writeResponse() failed mapping exception", e);
477 writeException(request, response, e);
538 writeException(request, response, e, t -> {});
478539 }
479540 }
480541
483544 requestPreprocessors.add(httpPreprocessor);
484545 }
485546
486 }
547 }
44 import org.jboss.resteasy.spi.ResteasyAsynchronousResponse;
55 import org.jboss.resteasy.spi.UnhandledException;
66
7 import javax.ws.rs.container.AsyncResponse;
87 import javax.ws.rs.core.HttpHeaders;
98 import javax.ws.rs.core.Response;
109 import java.util.Date;
7271 super(dispatcher, request, response);
7372 }
7473
75
74 @Override
75 public void complete()
76 {
77 synchronized (responseLock)
78 {
79 if (done) return;
80 if (cancelled) return;
81 done = true;
82 syncLatch.countDown();
83 }
84 }
7685
7786 @Override
7887 public boolean resume(Object entity)
8190 {
8291 if (done) return false;
8392 if (cancelled) return false;
84 try
85 {
86 return internalResume(entity);
87 }
88 finally
89 {
90 done = true;
91 syncLatch.countDown();
92 }
93 done = true;
94 return internalResume(entity, t -> syncLatch.countDown());
9395 }
9496 }
9597
101103 {
102104 if (done) return false;
103105 if (cancelled) return false;
104 try
105 {
106 return internalResume(exc);
107 }
108 finally
109 {
110 done = true;
111 syncLatch.countDown();
112 }
106 done = true;
107 return internalResume(exc, t -> syncLatch.countDown());
113108 }
114109 }
115110
147142 }
148143 if (!done)
149144 {
150 try
151 {
152 internalResume(Response.status(503).build());
153 }
154 catch (Exception e)
155 {
156 throw new UnhandledException(e);
157 }
158 finally
159 {
160 done = true;
161 }
145 done = true;
146 internalResume(Response.status(503).build(), t -> {});
147 // FIXME: what to do here?
148 // throw new UnhandledException(e);
162149 }
163150 }
164151 }
184171 done = true;
185172 cancelled = true;
186173 }
187 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).build());
174 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).build(), t -> syncLatch.countDown());
188175 }
189176
190177 @Override
197184 done = true;
198185 cancelled = true;
199186 }
200 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build());
187 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(), t -> syncLatch.countDown());
201188 }
202189
203190 @Override
210197 done = true;
211198 cancelled = true;
212199 }
213 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build());
200 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(), t -> syncLatch.countDown());
214201 }
215202
216203 @Override
00 package org.jboss.resteasy.core;
11
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4 import java.util.Collection;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.Set;
8 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
2 import org.jboss.resteasy.client.core.ClientErrorInterceptor;
3 import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper;
4 import org.jboss.resteasy.core.interception.jaxrs.ClientRequestFilterRegistry;
5 import org.jboss.resteasy.core.interception.ClientResponseFilterRegistry;
6 import org.jboss.resteasy.core.interception.ContainerRequestFilterRegistry;
7 import org.jboss.resteasy.core.interception.ContainerResponseFilterRegistry;
8 import org.jboss.resteasy.core.interception.InterceptorRegistry;
9 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
10 import org.jboss.resteasy.core.interception.ReaderInterceptorRegistry;
11 import org.jboss.resteasy.core.interception.WriterInterceptorRegistry;
12 import org.jboss.resteasy.spi.ConstructorInjector;
13 import org.jboss.resteasy.spi.HttpRequest;
14 import org.jboss.resteasy.spi.HttpResponse;
15 import org.jboss.resteasy.spi.InjectorFactory;
16 import org.jboss.resteasy.spi.ProviderFactoryDelegate;
17 import org.jboss.resteasy.spi.ResteasyProviderFactory;
18 import org.jboss.resteasy.spi.StringConverter;
19 import org.jboss.resteasy.spi.StringParameterUnmarshaller;
20 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
21 import org.jboss.resteasy.util.ThreadLocalStack;
922
1023 import javax.ws.rs.RuntimeType;
1124 import javax.ws.rs.client.ClientRequestFilter;
25 import javax.ws.rs.client.ClientResponseFilter;
1226 import javax.ws.rs.container.DynamicFeature;
1327 import javax.ws.rs.core.Application;
1428 import javax.ws.rs.core.Configuration;
2337 import javax.ws.rs.ext.MessageBodyReader;
2438 import javax.ws.rs.ext.MessageBodyWriter;
2539 import javax.ws.rs.ext.ParamConverter;
26
27 import org.jboss.resteasy.core.interception.jaxrs.ClientResponseFilterRegistry;
28 import org.jboss.resteasy.core.interception.jaxrs.ContainerRequestFilterRegistry;
29 import org.jboss.resteasy.core.interception.jaxrs.ContainerResponseFilterRegistry;
30 import org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistry;
31 import org.jboss.resteasy.core.interception.jaxrs.ReaderInterceptorRegistry;
32 import org.jboss.resteasy.core.interception.jaxrs.WriterInterceptorRegistry;
40 import javax.ws.rs.ext.RuntimeDelegate;
41 import java.lang.annotation.Annotation;
42 import java.lang.reflect.Type;
43 import java.util.Collection;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
48 import org.jboss.resteasy.core.interception.ClientResponseFilterRegistry;
49 import org.jboss.resteasy.core.interception.ContainerRequestFilterRegistry;
50 import org.jboss.resteasy.core.interception.ContainerResponseFilterRegistry;
51 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
52 import org.jboss.resteasy.core.interception.ReaderInterceptorRegistry;
53 import org.jboss.resteasy.core.interception.WriterInterceptorRegistry;
54 import org.jboss.resteasy.spi.AsyncResponseProvider;
55 import org.jboss.resteasy.spi.AsyncStreamProvider;
3356 import org.jboss.resteasy.spi.ConstructorInjector;
3457 import org.jboss.resteasy.spi.HttpRequest;
3558 import org.jboss.resteasy.spi.HttpResponse;
136159 }
137160
138161 @Override
162 public <T extends Throwable> ClientExceptionMapper<T> getClientExceptionMapper(Class<T> type)
163 {
164 return getDelegate().getClientExceptionMapper(type);
165 }
166
167 @Override
139168 public Set<Class<?>> getFeatureClasses()
140169 {
141170 return getDelegate().getFeatureClasses();
160189 }
161190
162191 @Override
192 public void addClientExceptionMapper(Class<? extends ClientExceptionMapper<?>> providerClass)
193 {
194 getDelegate().addClientExceptionMapper(providerClass);
195 }
196
197 @Override
163198 public ResteasyProviderFactory register(Class<?> componentClass, Map<Class<?>, Integer> contracts)
164199 {
165200 return getDelegate().register(componentClass, contracts);
182217 {
183218 getDelegate().registerProviderInstance(provider);
184219 }
185
220
221 @Override
222 public void addClientExceptionMapper(ClientExceptionMapper<?> provider, Type exceptionType)
223 {
224 getDelegate().addClientExceptionMapper(provider, exceptionType);
225 }
226
186227 @Override
187228 public StringConverter getStringConverter(Class<?> clazz)
188229 {
202243 }
203244
204245 @Override
246 public void addClientExceptionMapper(ClientExceptionMapper<?> provider)
247 {
248 getDelegate().addClientExceptionMapper(provider);
249 }
250
251 @Override
205252 public void setInjectorFactory(InjectorFactory injectorFactory)
206253 {
207254 getDelegate().setInjectorFactory(injectorFactory);
229276 public <T> ContextResolver<T> getContextResolver(Class<T> contextType, MediaType mediaType)
230277 {
231278 return getDelegate().getContextResolver(contextType, mediaType);
279 }
280
281 @Override
282 public InterceptorRegistry<ClientExecutionInterceptor> getClientExecutionInterceptorRegistry()
283 {
284 return getDelegate().getClientExecutionInterceptorRegistry();
232285 }
233286
234287 @Override
241294 }
242295
243296 @Override
297 public void addClientErrorInterceptor(ClientErrorInterceptor handler)
298 {
299 getDelegate().addClientErrorInterceptor(handler);
300 }
301
302 @Override
244303 public void registerProvider(Class provider, Integer priorityOverride, boolean isBuiltin, Map<Class<?>, Integer> contracts)
245304 {
246305 getDelegate().registerProvider(provider, priorityOverride, isBuiltin, contracts);
301360 }
302361
303362 @Override
363 public void addClientExceptionMapper(ClientExceptionMapper<?> provider, Class<?> providerClass)
364 {
365 getDelegate().addClientExceptionMapper(provider, providerClass);
366 }
367
368 @Override
369 public void insertInterceptorPrecedenceAfter(String after, String newPrecedence)
370 {
371 getDelegate().insertInterceptorPrecedenceAfter(after, newPrecedence);
372 }
373
374 @Override
304375 public ResteasyProviderFactory register(Object provider)
305376 {
306377 return getDelegate().register(provider);
325396 }
326397
327398 @Override
399 public void insertInterceptorPrecedenceBefore(String before, String newPrecedence)
400 {
401 getDelegate().insertInterceptorPrecedenceBefore(before, newPrecedence);
402 }
403
404 @Override
328405 public <T> T createEndpoint(Application applicationConfig, Class<T> endpointType) throws IllegalArgumentException, UnsupportedOperationException
329406 {
330407 return getDelegate().createEndpoint(applicationConfig, endpointType);
367444 }
368445
369446 @Override
447 public List<ClientErrorInterceptor> getClientErrorInterceptors()
448 {
449 return getDelegate().getClientErrorInterceptors();
450 }
451
452 @Override
370453 public void injectProperties(Class declaring, Object obj)
371454 {
372455 getDelegate().injectProperties(declaring, obj);
391474 }
392475
393476 @Override
477 public void appendInterceptorPrecedence(String precedence)
478 {
479 getDelegate().appendInterceptorPrecedence(precedence);
480 }
481
482 @Override
394483 public ResteasyProviderFactory getParent()
395484 {
396485 return getDelegate().getParent();
498587 return getDelegate().toString(object, clazz, genericType, annotations);
499588 }
500589
590 @Override
591 public ClientRequestFilterRegistry getClientRequestFilterRegistry()
592 {
593 return getDelegate().getClientRequestFilterRegistry();
594 }
595
596 /**
597 * This method retailed for backward compatibility for jaxrs-legacy code.
598 * Method, getClientRequestFilterRegistry, replaces it.
599 * @return
600 */
601 @Deprecated
501602 @Override
502603 public JaxrsInterceptorRegistry<ClientRequestFilter> getClientRequestFilters()
503604 {
556657 }
557658
558659 @Override
660 public <T> AsyncResponseProvider<T> getAsyncResponseProvider(Class<T> type)
661 {
662 return getDelegate().getAsyncResponseProvider(type);
663 }
664
665 @Override
666 public Map<Class<?>, AsyncResponseProvider> getAsyncResponseProviders()
667 {
668 return getDelegate().getAsyncResponseProviders();
669 }
670
671 @Override
672 public <T> AsyncStreamProvider<T> getAsyncStreamProvider(Class<T> type)
673 {
674 return getDelegate().getAsyncStreamProvider(type);
675 }
676
677 @Override
678 public Map<Class<?>, AsyncStreamProvider> getAsyncStreamProviders()
679 {
680 return getDelegate().getAsyncStreamProviders();
681 }
682
683 @Override
559684 public <T> HeaderDelegate<T> createHeaderDelegate(Class<T> tClass)
560685 {
561686 return getDelegate().createHeaderDelegate(tClass);
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.NotSupportedException;
6 import javax.ws.rs.core.HttpHeaders;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyReader;
10 import javax.ws.rs.ext.ReaderInterceptor;
11 import javax.ws.rs.ext.ReaderInterceptorContext;
12
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17
18 /**
19 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
20 * @version $Revision: 1 $
21 */
22 public abstract class AbstractReaderInterceptorContext implements ReaderInterceptorContext
23 {
24 protected ReaderInterceptor[] interceptors;
25 protected ResteasyProviderFactory providerFactory;
26 protected Class type;
27 protected Type genericType;
28 protected Annotation[] annotations;
29 protected MediaType mediaType;
30 protected MultivaluedMap<String, String> headers;
31 protected InputStream inputStream;
32 protected int index = 0;
33
34 public AbstractReaderInterceptorContext(MediaType mediaType, ResteasyProviderFactory providerFactory, Annotation[] annotations, ReaderInterceptor[] interceptors, MultivaluedMap<String, String> headers, Type genericType, Class type, InputStream inputStream)
35 {
36 this.mediaType = mediaType;
37 this.annotations = annotations;
38 this.interceptors = interceptors;
39 this.headers = headers;
40 this.genericType = genericType;
41 this.type = type;
42 this.inputStream = inputStream;
43 this.providerFactory = providerFactory;
44 }
45
46 @Override
47 public Object proceed() throws IOException
48 {
49 LogMessages.LOGGER.debugf("Interceptor Context: %s, Method : proceed", getClass().getName());
50 if (interceptors == null || index >= interceptors.length)
51 {
52 MessageBodyReader reader = getReader();
53 if (reader!=null)
54 LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName());
55 return readFrom(reader);
56 }
57 LogMessages.LOGGER.debugf("ReaderInterceptor: %s", interceptors[index].getClass().getName());
58 return interceptors[index++].aroundReadFrom(this);
59 // index--; we used to pop the index, but the TCK does not like this
60 }
61
62 @SuppressWarnings(value = "unchecked")
63 protected Object readFrom(MessageBodyReader reader) throws IOException
64 {
65 return reader.readFrom(type, genericType, annotations, mediaType, headers, inputStream);
66 }
67
68 protected MessageBodyReader getReader()
69 {
70 MediaType mediaType = this.mediaType;
71 // spec says set to octet stream
72 if (getHeaders() != null && getHeaders().getFirst(HttpHeaders.CONTENT_TYPE) == null && mediaType.isWildcardType())
73 {
74 mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
75 }
76 MessageBodyReader reader = resolveReader(mediaType);
77 if (reader == null)
78 {
79 throwReaderNotFound();
80 }
81 return reader;
82 }
83
84 protected abstract MessageBodyReader resolveReader(MediaType mediaType);
85
86 abstract protected void throwReaderNotFound();
87
88 @Override
89 public InputStream getInputStream()
90 {
91 return inputStream;
92 }
93
94 @Override
95 public void setInputStream(InputStream is)
96 {
97 this.inputStream = is;
98 }
99
100 @Override
101 public MultivaluedMap<String, String> getHeaders()
102 {
103 return headers;
104 }
105
106 @Override
107 public Annotation[] getAnnotations()
108 {
109 return annotations;
110 }
111
112 @Override
113 public void setAnnotations(Annotation[] annotations)
114 {
115 if (annotations == null) throw new NullPointerException(Messages.MESSAGES.annotationsParamNull());
116 this.annotations = annotations;
117 }
118
119 @Override
120 public Class getType()
121 {
122 return type;
123 }
124
125 @Override
126 public void setType(Class type)
127 {
128 this.type = type;
129 }
130
131 @Override
132 public Type getGenericType()
133 {
134 return genericType;
135 }
136
137 @Override
138 public void setGenericType(Type genericType)
139 {
140 this.genericType = genericType;
141 }
142
143 @Override
144 public MediaType getMediaType()
145 {
146 return mediaType;
147 }
148
149 @Override
150 public void setMediaType(MediaType mediaType)
151 {
152 this.mediaType = mediaType;
153 }
154 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyWriter;
10 import javax.ws.rs.ext.WriterInterceptor;
11 import javax.ws.rs.ext.WriterInterceptorContext;
12
13 import java.io.IOException;
14 import java.io.OutputStream;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17
18 /**
19 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
20 * @version $Revision: 1 $
21 */
22 public abstract class AbstractWriterInterceptorContext implements WriterInterceptorContext
23 {
24 protected WriterInterceptor[] interceptors;
25 protected Object entity;
26 protected Class type;
27 protected Type genericType;
28 protected Annotation[] annotations;
29 protected MediaType mediaType;
30 protected MultivaluedMap<String, Object> headers;
31 protected OutputStream outputStream;
32 protected int index = 0;
33 protected ResteasyProviderFactory providerFactory;
34
35 public AbstractWriterInterceptorContext(WriterInterceptor[] interceptors, Annotation[] annotations, Object entity, Type genericType, MediaType mediaType, Class type, OutputStream outputStream, ResteasyProviderFactory providerFactory, MultivaluedMap<String, Object> headers)
36 {
37 this.providerFactory = providerFactory;
38 this.interceptors = interceptors;
39 this.annotations = annotations;
40 this.entity = entity;
41 this.genericType = genericType;
42 this.mediaType = mediaType;
43 this.type = type;
44 this.outputStream = outputStream;
45 this.headers = headers;
46 }
47
48 public Object getEntity()
49 {
50 return entity;
51 }
52
53 public void setEntity(Object entity)
54 {
55 this.entity = entity;
56 }
57
58 public Class getType()
59 {
60 return type;
61 }
62
63 public void setType(Class type)
64 {
65 this.type = type;
66 }
67
68 public Type getGenericType()
69 {
70 return genericType;
71 }
72
73 public void setGenericType(Type genericType)
74 {
75 this.genericType = genericType;
76 }
77
78 public Annotation[] getAnnotations()
79 {
80 return annotations;
81 }
82
83 public void setAnnotations(Annotation[] annotations)
84 {
85 if (annotations == null) throw new NullPointerException(Messages.MESSAGES.annotationsParamNull());
86 this.annotations = annotations;
87 }
88
89 public MediaType getMediaType()
90 {
91 return mediaType;
92 }
93
94 public void setMediaType(MediaType mediaType)
95 {
96 this.mediaType = mediaType;
97 }
98
99 public MultivaluedMap<String, Object> getHeaders()
100 {
101 return headers;
102 }
103
104 public OutputStream getOutputStream()
105 {
106 return outputStream;
107 }
108
109 public void setOutputStream(OutputStream outputStream)
110 {
111 this.outputStream = outputStream;
112 }
113
114 public void proceed() throws IOException, WebApplicationException
115 {
116 LogMessages.LOGGER.debugf("Interceptor Context: %s, Method : proceed", getClass().getName());
117
118 if (interceptors == null || index >= interceptors.length)
119 {
120 MessageBodyWriter writer = getWriter();
121 if (writer!=null)
122 LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName());
123 writeTo(writer);
124 }
125 else
126 {
127 LogMessages.LOGGER.debugf("WriterInterceptor: %s", interceptors[index].getClass().getName());
128 interceptors[index++].aroundWriteTo(this);
129 // we used to pop the index, but the TCK doesn't like this
130 }
131 }
132
133 @SuppressWarnings(value = "unchecked")
134 protected void writeTo(MessageBodyWriter writer) throws IOException
135 {
136 writer.writeTo(entity, type, genericType, annotations, mediaType, headers, outputStream);
137 }
138
139 protected MessageBodyWriter getWriter()
140 {
141 MessageBodyWriter writer = resolveWriter();
142
143 if (writer == null)
144 {
145 throwWriterNotFoundException();
146 }
147 return writer;
148
149 }
150
151 abstract protected MessageBodyWriter resolveWriter();
152
153 abstract void throwWriterNotFoundException();
154 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.spi.interception.ClientExecutionContext;
6 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
7
8 import java.util.List;
9
10 /**
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @version $Revision: 1 $
13 *
14 * @deprecated The Resteasy interceptor facility introduced in release 2.x
15 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
16 *
17 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
18 *
19 */
20 @Deprecated
21 public class ClientExecutionContextImpl implements ClientExecutionContext
22 {
23 protected List<ClientExecutionInterceptor> interceptors;
24 protected ClientExecutor executor;
25 protected ClientRequest request;
26 protected int index = 0;
27
28 public ClientExecutionContextImpl(List<ClientExecutionInterceptor> interceptors, ClientExecutor executor, ClientRequest request)
29 {
30 this.interceptors = interceptors;
31 this.executor = executor;
32 this.request = request;
33 }
34
35 public ClientRequest getRequest()
36 {
37 return request;
38 }
39
40 @SuppressWarnings("unchecked")
41 public ClientResponse proceed() throws Exception
42 {
43 if (index >= interceptors.size())
44 {
45 return executor.execute(request);
46 }
47 else
48 {
49 try
50 {
51 return interceptors.get(index++).execute(this);
52 }
53 finally
54 {
55 index--;
56 }
57 }
58 }
59 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.NotSupportedException;
6 import javax.ws.rs.ProcessingException;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyReader;
10 import javax.ws.rs.ext.ReaderInterceptor;
11
12 import java.io.InputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.Type;
15 import java.util.Collection;
16 import java.util.Enumeration;
17 import java.util.Iterator;
18 import java.util.Map;
19
20 import static java.lang.String.format;
21
22 /**
23 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
24 * @version $Revision: 1 $
25 */
26 public class ClientReaderInterceptorContext extends AbstractReaderInterceptorContext
27 {
28 protected Map<String, Object> properties;
29
30 public ClientReaderInterceptorContext(ReaderInterceptor[] interceptors, ResteasyProviderFactory providerFactory, Class type,
31 Type genericType, Annotation[] annotations, MediaType mediaType,
32 MultivaluedMap<String, String> headers, InputStream inputStream,
33 Map<String, Object> properties)
34 {
35 super(mediaType, providerFactory, annotations, interceptors, headers, genericType, type, inputStream);
36 this.properties = properties;
37 }
38
39 protected void throwReaderNotFound()
40 {
41 throw new ProcessingException(Messages.MESSAGES.clientResponseFailureMediaType(mediaType, type));
42 }
43
44 @SuppressWarnings(value = "unchecked")
45 @Override
46 protected MessageBodyReader resolveReader(MediaType mediaType)
47 {
48 return providerFactory.getClientMessageBodyReader(type,
49 genericType, annotations, mediaType);
50 }
51
52 @Override
53 public Object getProperty(String name)
54 {
55 return properties.get(name);
56 }
57
58 @Override
59 public Collection<String> getPropertyNames()
60 {
61 return properties.keySet();
62 }
63
64 @Override
65 public void setProperty(String name, Object object)
66 {
67 if (object == null)
68 {
69 properties.remove(name);
70 }
71 else
72 {
73 properties.put(name, object);
74 }
75 }
76
77 @Override
78 public void removeProperty(String name)
79 {
80 properties.remove(name);
81 }
82 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3
4 import javax.ws.rs.client.ClientResponseFilter;
5 import java.util.Collections;
6 import java.util.List;
7
8 /**
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @version $Revision: 1 $
11 */
12 public class ClientResponseFilterRegistry extends JaxrsInterceptorRegistry<ClientResponseFilter>
13 {
14 public ClientResponseFilterRegistry(ResteasyProviderFactory providerFactory)
15 {
16 super(providerFactory, ClientResponseFilter.class);
17 }
18
19 @Override
20 protected void sort(List<Match> matches)
21 {
22 Collections.sort(matches, new DescendingPrecedenceComparator());
23
24 }
25
26 @Override
27 public ClientResponseFilterRegistry clone(ResteasyProviderFactory factory)
28 {
29 ClientResponseFilterRegistry clone = new ClientResponseFilterRegistry(factory);
30 clone.interceptors.addAll(interceptors);
31 return clone;
32 }
33 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.ProcessingException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.WriterInterceptor;
10
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14 import java.util.Collection;
15 import java.util.Enumeration;
16 import java.util.Iterator;
17 import java.util.Map;
18
19 /**
20 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
21 * @version $Revision: 1 $
22 */
23 public class ClientWriterInterceptorContext extends AbstractWriterInterceptorContext
24 {
25 protected Map<String, Object> properties;
26
27 public ClientWriterInterceptorContext(WriterInterceptor[] interceptors, ResteasyProviderFactory providerFactory,
28 Object entity, Class type, Type genericType, Annotation[] annotations,
29 MediaType mediaType, MultivaluedMap<String, Object> headers,
30 OutputStream outputStream, Map<String, Object> properties)
31 {
32 super(interceptors, annotations, entity, genericType, mediaType, type, outputStream, providerFactory, headers);
33 this.properties = properties;
34 }
35
36 @Override
37 void throwWriterNotFoundException()
38 {
39 throw new ProcessingException(Messages.MESSAGES.couldNotFindWriterForContentType(mediaType, type.getName()));
40 }
41
42 @Override
43 protected MessageBodyWriter resolveWriter()
44 {
45 @SuppressWarnings(value = "unchecked")
46 MessageBodyWriter writer = providerFactory.getClientMessageBodyWriter(
47 type, genericType, annotations, mediaType);
48 //logger.info("********* WRITER: " + writer.getClass().getName());
49 return writer;
50 }
51
52 @Override
53 public Object getProperty(String name)
54 {
55 return properties.get(name);
56 }
57
58 @Override
59 public Collection<String> getPropertyNames()
60 {
61 return properties.keySet();
62 }
63
64 @Override
65 public void setProperty(String name, Object object)
66 {
67 if (object == null)
68 {
69 properties.remove(name);
70 }
71 else
72 {
73 properties.put(name, object);
74 }
75 }
76
77 @Override
78 public void removeProperty(String name)
79 {
80 properties.remove(name);
81 }
82 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.core.ServerResponse;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
5
6 import javax.ws.rs.container.ContainerRequestContext;
7 import javax.ws.rs.container.ContainerRequestFilter;
8 import java.io.IOException;
9 import java.lang.reflect.AccessibleObject;
10
11 /**
12 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
13 * @version $Revision: 1 $
14 */
15 public class ContainerRequestFilterRegistry extends JaxrsInterceptorRegistry<ContainerRequestFilter>
16 {
17 protected LegacyPrecedence precedence;
18
19 public ContainerRequestFilterRegistry(ResteasyProviderFactory providerFactory, LegacyPrecedence precedence)
20 {
21 super(providerFactory, ContainerRequestFilter.class);
22 this.precedence = precedence;
23 }
24
25 public ContainerRequestFilterRegistry clone(ResteasyProviderFactory factory)
26 {
27 ContainerRequestFilterRegistry clone = new ContainerRequestFilterRegistry(factory, precedence);
28 clone.interceptors.addAll(interceptors);
29 return clone;
30 }
31
32 private static class ContainerRequestFilterFacade implements ContainerRequestFilter
33 {
34 protected final PreProcessInterceptor interceptor;
35
36 private ContainerRequestFilterFacade(PreProcessInterceptor interceptor)
37 {
38 this.interceptor = interceptor;
39 }
40
41 @Override
42 public void filter(ContainerRequestContext requestContext) throws IOException
43 {
44 PostMatchContainerRequestContext ctx = (PostMatchContainerRequestContext)requestContext;
45 ServerResponse response = interceptor.preProcess(ctx.getHttpRequest(), ctx.getResourceMethod());
46 if (response != null)
47 {
48 requestContext.abortWith(response);
49 }
50 }
51 }
52
53 @Override
54 public ContainerRequestFilter[] postMatch(Class declaring, AccessibleObject target)
55 {
56 return super.postMatch(declaring, target);
57 }
58
59 public void registerLegacy(Class<? extends PreProcessInterceptor> decl)
60 {
61 register(new LegacyPerMethodInterceptorFactory(decl, precedence)
62 {
63 @Override
64 public Match postMatch(Class declaring, AccessibleObject target)
65 {
66 Object obj = super.getLegacyMatch(declaring, target);
67 if (obj == null) return null;
68 PreProcessInterceptor interceptor = (PreProcessInterceptor)obj;
69 return new Match(new ContainerRequestFilterFacade(interceptor), order);
70 }
71
72 });
73 }
74
75 public void registerLegacy(PreProcessInterceptor interceptor)
76 {
77 register(new LegacySingletonInterceptorFactory(interceptor.getClass(), interceptor, precedence)
78 {
79 @Override
80 public Match postMatch(Class declaring, AccessibleObject target)
81 {
82 Object obj = super.getLegacyMatch(declaring, target);
83 if (obj == null) return null;
84 PreProcessInterceptor interceptor = (PreProcessInterceptor)obj;
85 return new Match(new ContainerRequestFilterFacade(interceptor), order);
86 }
87 });
88
89 }
90 }
0 package org.jboss.resteasy.core.interception;
1
2 import java.io.IOException;
3 import java.io.OutputStream;
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.Type;
6 import java.net.URI;
7 import java.util.Date;
8 import java.util.Locale;
9 import java.util.Map;
10 import java.util.Set;
11 import java.util.function.Consumer;
12
13 import javax.servlet.http.HttpServletRequest;
14 import javax.ws.rs.container.ContainerResponseFilter;
15 import javax.ws.rs.core.EntityTag;
16 import javax.ws.rs.core.HttpHeaders;
17 import javax.ws.rs.core.Link;
18 import javax.ws.rs.core.MediaType;
19 import javax.ws.rs.core.MultivaluedMap;
20 import javax.ws.rs.core.NewCookie;
21 import javax.ws.rs.core.Response;
22
23 import org.jboss.resteasy.core.Dispatcher;
24 import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerResponseContext;
25 import org.jboss.resteasy.core.ServerResponseWriter.RunnableWithIOException;
26 import org.jboss.resteasy.core.SynchronousDispatcher;
27 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
28 import org.jboss.resteasy.specimpl.BuiltResponse;
29 import org.jboss.resteasy.spi.ApplicationException;
30 import org.jboss.resteasy.spi.HttpRequest;
31 import org.jboss.resteasy.spi.HttpResponse;
32 import org.jboss.resteasy.spi.ResteasyProviderFactory;
33
34 /**
35 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
36 * @version $Revision: 1 $
37 */
38 public class ContainerResponseContextImpl implements SuspendableContainerResponseContext
39 {
40 protected final HttpRequest request;
41 protected final HttpResponse httpResponse;
42 protected final BuiltResponse jaxrsResponse;
43 private ResponseContainerRequestContext requestContext;
44 private ContainerResponseFilter[] responseFilters;
45 private RunnableWithIOException continuation;
46 private int currentFilter;
47 private boolean suspended;
48 private boolean filterReturnIsMeaningful = true;
49 private Map<Class<?>, Object> contextDataMap;
50 private boolean inFilter;
51 private Throwable throwable;
52 private Consumer<Throwable> onComplete;
53 private boolean weSuspended;
54
55 @Deprecated
56 public ContainerResponseContextImpl(HttpRequest request, HttpResponse httpResponse, BuiltResponse serverResponse)
57 {
58 this(request, httpResponse, serverResponse, null, new ContainerResponseFilter[]{}, t -> {}, null);
59 }
60
61 public ContainerResponseContextImpl(HttpRequest request, HttpResponse httpResponse, BuiltResponse serverResponse,
62 ResponseContainerRequestContext requestContext, ContainerResponseFilter[] responseFilters,
63 Consumer<Throwable> onComplete, RunnableWithIOException continuation)
64 {
65 this.request = request;
66 this.httpResponse = httpResponse;
67 this.jaxrsResponse = serverResponse;
68 this.requestContext = requestContext;
69 this.responseFilters = responseFilters;
70 this.continuation = continuation;
71 this.onComplete = onComplete;
72 contextDataMap = ResteasyProviderFactory.getContextDataMap();
73 }
74
75 public BuiltResponse getJaxrsResponse()
76 {
77 return jaxrsResponse;
78 }
79
80 public HttpResponse getHttpResponse()
81 {
82 return httpResponse;
83 }
84
85 @Override
86 public int getStatus()
87 {
88 return jaxrsResponse.getStatus();
89 }
90
91 @Override
92 public void setStatus(int code)
93 {
94 httpResponse.setStatus(code);
95 jaxrsResponse.setStatus(code);
96 }
97
98 @Override
99 public Response.StatusType getStatusInfo()
100 {
101 return jaxrsResponse.getStatusInfo();
102 }
103
104 @Override
105 public void setStatusInfo(Response.StatusType statusInfo)
106 {
107 httpResponse.setStatus(statusInfo.getStatusCode());
108 jaxrsResponse.setStatus(statusInfo.getStatusCode());
109 }
110
111 @Override
112 public Class<?> getEntityClass()
113 {
114 return jaxrsResponse.getEntityClass();
115 }
116
117 @Override
118 public Type getEntityType()
119 {
120 return jaxrsResponse.getGenericType();
121 }
122
123 @Override
124 public void setEntity(Object entity)
125 {
126 //if (entity != null) logger.info("*** setEntity(Object) " + entity.toString());
127 jaxrsResponse.setEntity(entity);
128 // todo TCK does weird things in its testing of get length
129 // it resets the entity in a response filter which results
130 // in a bad content-length being sent back to the client
131 // so, we'll remove any content-length setting
132 getHeaders().remove(HttpHeaders.CONTENT_LENGTH);
133 }
134
135 @Override
136 public void setEntity(Object entity, Annotation[] annotations, MediaType mediaType)
137 {
138 //if (entity != null) logger.info("*** setEntity(Object, Annotation[], MediaType) " + entity.toString() + ", " + mediaType);
139 jaxrsResponse.setEntity(entity);
140 jaxrsResponse.setAnnotations(annotations);
141 jaxrsResponse.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType);
142 // todo TCK does weird things in its testing of get length
143 // it resets the entity in a response filter which results
144 // in a bad content-length being sent back to the client
145 // so, we'll remove any content-length setting
146 getHeaders().remove(HttpHeaders.CONTENT_LENGTH);
147 }
148
149 @Override
150 public MultivaluedMap<String, Object> getHeaders()
151 {
152 return jaxrsResponse.getMetadata();
153 }
154
155 @Override
156 public Set<String> getAllowedMethods()
157 {
158 return jaxrsResponse.getAllowedMethods();
159 }
160
161 @Override
162 public Date getDate()
163 {
164 return jaxrsResponse.getDate();
165 }
166
167 @Override
168 public Locale getLanguage()
169 {
170 return jaxrsResponse.getLanguage();
171 }
172
173 @Override
174 public int getLength()
175 {
176 return jaxrsResponse.getLength();
177 }
178
179 @Override
180 public MediaType getMediaType()
181 {
182 return jaxrsResponse.getMediaType();
183 }
184
185 @Override
186 public Map<String, NewCookie> getCookies()
187 {
188 return jaxrsResponse.getCookies();
189 }
190
191 @Override
192 public EntityTag getEntityTag()
193 {
194 return jaxrsResponse.getEntityTag();
195 }
196
197 @Override
198 public Date getLastModified()
199 {
200 return jaxrsResponse.getLastModified();
201 }
202
203 @Override
204 public URI getLocation()
205 {
206 return jaxrsResponse.getLocation();
207 }
208
209 @Override
210 public Set<Link> getLinks()
211 {
212 return jaxrsResponse.getLinks();
213 }
214
215 @Override
216 public boolean hasLink(String relation)
217 {
218 return jaxrsResponse.hasLink(relation);
219 }
220
221 @Override
222 public Link getLink(String relation)
223 {
224 return jaxrsResponse.getLink(relation);
225 }
226
227 @Override
228 public Link.Builder getLinkBuilder(String relation)
229 {
230 return jaxrsResponse.getLinkBuilder(relation);
231 }
232
233 @Override
234 public boolean hasEntity()
235 {
236 return jaxrsResponse.hasEntity();
237 }
238
239 @Override
240 public Object getEntity()
241 {
242 return jaxrsResponse.getEntity();
243 }
244
245 @Override
246 public OutputStream getEntityStream()
247 {
248 try
249 {
250 return httpResponse.getOutputStream();
251 }
252 catch (IOException e)
253 {
254 throw new RuntimeException(e);
255 }
256 }
257
258 @Override
259 public void setEntityStream(OutputStream entityStream)
260 {
261 httpResponse.setOutputStream(entityStream);
262 }
263
264 @Override
265 public Annotation[] getEntityAnnotations()
266 {
267 return jaxrsResponse.getAnnotations();
268 }
269
270 @Override
271 public MultivaluedMap<String, String> getStringHeaders()
272 {
273 return jaxrsResponse.getStringHeaders();
274 }
275
276 @Override
277 public String getHeaderString(String name)
278 {
279 return jaxrsResponse.getHeaderString(name);
280 }
281
282
283 @Override
284 public synchronized void suspend() {
285 if(continuation == null)
286 throw new RuntimeException("Suspend not supported yet");
287 suspended = true;
288 }
289
290 @Override
291 public synchronized void resume() {
292 if(!suspended)
293 throw new RuntimeException("Cannot resume: not suspended");
294 if(inFilter)
295 {
296 // suspend/resume within filter, same thread: just ignore and move on
297 suspended = false;
298 return;
299 }
300
301 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
302 // go on, but with proper exception handling
303 try {
304 filter();
305 }catch(Throwable t) {
306 // don't throw to client
307 writeException(t);
308 }
309 }
310
311 @Override
312 public synchronized void resume(Throwable t) {
313 if(!suspended)
314 throw new RuntimeException("Cannot resume: not suspended");
315 if(inFilter)
316 {
317 // not suspended, or suspend/abortWith within filter, same thread: collect and move on
318 throwable = t;
319 suspended = false;
320 }
321 else
322 {
323 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
324 writeException(t);
325 }
326 }
327
328 private void writeException(Throwable t)
329 {
330 HttpRequest httpRequest = (HttpRequest) contextDataMap.get(HttpRequest.class);
331 HttpResponse httpResponse = (HttpResponse) contextDataMap.get(HttpResponse.class);
332 SynchronousDispatcher dispatcher = (SynchronousDispatcher) contextDataMap.get(Dispatcher.class);
333 try {
334 dispatcher.writeException(httpRequest, httpResponse, t, onComplete);
335 }catch(Throwable x) {
336 dispatcher.unhandledAsynchronousException(httpResponse, x);
337 LogMessages.LOGGER.unhandledAsynchronousException(x);
338 onComplete.accept(null);
339 }
340 }
341
342 public synchronized void filter() throws IOException
343 {
344 while(currentFilter < responseFilters.length)
345 {
346 ContainerResponseFilter filter = responseFilters[currentFilter++];
347 try
348 {
349 suspended = false;
350 throwable = null;
351 inFilter = true;
352 filter.filter(requestContext, this);
353 }
354 catch (IOException e)
355 {
356 throw new ApplicationException(e);
357 }
358 finally
359 {
360 inFilter = false;
361 }
362 if(suspended) {
363 if(!request.getAsyncContext().isSuspended())
364 {
365 request.getAsyncContext().suspend();
366 weSuspended = true;
367 }
368 // ignore any abort request until we are resumed
369 filterReturnIsMeaningful = false;
370 return;
371 }
372 if (throwable != null)
373 {
374 // handle the case where we've been suspended by a previous filter
375 if(filterReturnIsMeaningful)
376 SynchronousDispatcher.rethrow(throwable);
377 else
378 {
379 writeException(throwable);
380 return;
381 }
382 }
383 }
384 // here it means we reached the last filter
385
386 // some frameworks don't support async request filters, in which case suspend() is forbidden
387 // so if we get here we're still synchronous and don't have a continuation, which must be in
388 // the caller
389 if(continuation == null)
390 return;
391
392 // if we've never been suspended, the caller is valid so let it handle any exception
393 if(filterReturnIsMeaningful) {
394 continuation.run();
395 onComplete.accept(null);
396 return;
397 }
398 // if we've been suspended then the caller is a filter and have to invoke our continuation
399 // FIXME: we don't really know if we're already trying to send an exception, so we can't just blindly
400 // try to write it out
401 try
402 {
403 continuation.run();
404 onComplete.accept(null);
405 if(weSuspended)
406 {
407 // if we're the ones who turned the request async, nobody will call complete() for us, so we have to
408 HttpServletRequest httpServletRequest = (HttpServletRequest) contextDataMap.get(HttpServletRequest.class);
409 httpServletRequest.getAsyncContext().complete();
410 }
411 } catch (IOException e)
412 {
413 LogMessages.LOGGER.unknownException(request.getHttpMethod(), request.getUri().getPath(), e);
414 }
415 }
416 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.core.ServerResponse;
3 import org.jboss.resteasy.specimpl.BuiltResponse;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
6
7 import javax.ws.rs.container.ContainerRequestContext;
8 import javax.ws.rs.container.ContainerResponseContext;
9 import javax.ws.rs.container.ContainerResponseFilter;
10 import java.io.IOException;
11 import java.lang.reflect.AccessibleObject;
12 import java.util.Collections;
13 import java.util.List;
14
15 /**
16 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
17 * @version $Revision: 1 $
18 */
19 public class ContainerResponseFilterRegistry extends JaxrsInterceptorRegistry<ContainerResponseFilter>
20 {
21 protected LegacyPrecedence precedence;
22
23 public ContainerResponseFilterRegistry(ResteasyProviderFactory providerFactory, LegacyPrecedence precedence)
24 {
25 super(providerFactory, ContainerResponseFilter.class);
26 this.precedence = precedence;
27 }
28
29 private static class ContainerResponseFilterFacade implements ContainerResponseFilter
30 {
31 protected final PostProcessInterceptor interceptor;
32
33 private ContainerResponseFilterFacade(PostProcessInterceptor interceptor)
34 {
35 this.interceptor = interceptor;
36 }
37
38 @Override
39 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException
40 {
41 ContainerResponseContextImpl ctx = (ContainerResponseContextImpl)responseContext;
42 BuiltResponse jaxrsResposne = ctx.getJaxrsResponse();
43 ServerResponse serverResponse = new ServerResponse(jaxrsResposne);
44 try
45 {
46 interceptor.postProcess(serverResponse);
47 }
48 finally
49 {
50 jaxrsResposne.setStatus(serverResponse.getStatus());
51 jaxrsResposne.setAnnotations(serverResponse.getAnnotations());
52 jaxrsResposne.setEntity(serverResponse.getEntity());
53 jaxrsResposne.setMetadata(serverResponse.getMetadata());
54 jaxrsResposne.setEntityClass(serverResponse.getEntityClass());
55 jaxrsResposne.setGenericType(serverResponse.getGenericType());
56 }
57
58 }
59 }
60
61 @Override
62 protected void sort(List<Match> matches)
63 {
64 Collections.sort(matches, new DescendingPrecedenceComparator());
65
66 }
67
68 public ContainerResponseFilterRegistry clone(ResteasyProviderFactory factory)
69 {
70 ContainerResponseFilterRegistry clone = new ContainerResponseFilterRegistry(factory, precedence);
71 clone.interceptors.addAll(interceptors);
72 return clone;
73 }
74
75 @Override
76 public synchronized void registerClass(Class<? extends ContainerResponseFilter> declaring)
77 {
78 OnDemandInterceptorFactory factory = new OnDemandInterceptorFactory(declaring);
79 factory.setIgnorePrematch(true);
80 register(factory);
81 }
82
83 @Override
84 public synchronized void registerClass(Class<? extends ContainerResponseFilter> declaring, int priority)
85 {
86 OnDemandInterceptorFactory factory = new OnDemandInterceptorFactory(declaring);
87 factory.setIgnorePrematch(true);
88 factory.setOrder(priority);
89 register(factory);
90 }
91
92 @Override
93 public synchronized void registerSingleton(ContainerResponseFilter interceptor)
94 {
95 SingletonInterceptorFactory factory = new SingletonInterceptorFactory(interceptor.getClass(), interceptor);
96 factory.setIgnorePrematch(true);
97 register(factory);
98 }
99
100 @Override
101 public synchronized void registerSingleton(ContainerResponseFilter interceptor, int priority)
102 {
103 SingletonInterceptorFactory factory = new SingletonInterceptorFactory(interceptor.getClass(), interceptor);
104 factory.setIgnorePrematch(true);
105 factory.setOrder(priority);
106 register(factory);
107 }
108
109 public void registerLegacy(Class<? extends PostProcessInterceptor> decl)
110 {
111 register(new LegacyPerMethodInterceptorFactory(decl, precedence)
112 {
113 @Override
114 public Match postMatch(Class declaring, AccessibleObject target)
115 {
116 Object obj = getLegacyMatch(declaring, target);
117 if (obj == null) return null;
118 PostProcessInterceptor interceptor = (PostProcessInterceptor)obj;
119 return new Match(new ContainerResponseFilterFacade(interceptor), order);
120 }
121
122 });
123 }
124
125 public void registerLegacy(PostProcessInterceptor interceptor)
126 {
127 register(new LegacySingletonInterceptorFactory(interceptor.getClass(), interceptor, precedence)
128 {
129 @Override
130 public Match postMatch(Class declaring, AccessibleObject target)
131 {
132 Object obj = getLegacyMatch(declaring, target);
133 if (obj == null) return null;
134 PostProcessInterceptor interceptor = (PostProcessInterceptor)obj;
135 return new Match(new ContainerResponseFilterFacade(interceptor), order);
136 }
137 });
138
139 }
140 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.annotations.DecorateTypes;
3 import org.jboss.resteasy.annotations.Decorator;
4 import org.jboss.resteasy.core.MediaTypeMap;
5 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
6
7 import javax.ws.rs.core.MediaType;
8 import java.lang.annotation.Annotation;
9 import java.util.HashMap;
10 import java.util.List;
11
12 /**
13 * Finds DecoratorProcessors and calls decorates on them by introspecting annotations.
14 *
15 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
16 * @version $Revision: 1 $
17 * @see org.jboss.resteasy.spi.interception.DecoratorProcessor
18 * @see org.jboss.resteasy.annotations.DecorateTypes
19 * @see org.jboss.resteasy.annotations.Decorator
20 */
21 public class DecoratorMatcher
22 {
23 /**
24 * @param targetClass i.e. Marshaller
25 * @param target
26 * @param type i.e. a JAXB annotated class
27 * @param annotations i.e. method or parameter annotations
28 * @param mediaType
29 * @param <T>
30 * @return
31 */
32 @SuppressWarnings(value = "unchecked")
33 public <T> T decorate(Class<T> targetClass, T target, Class type, Annotation[] annotations, MediaType mediaType)
34 {
35 HashMap<Class<?>, Annotation> meta = new HashMap<Class<?>, Annotation>();
36 if (type != null)
37 {
38 registerDecorators(targetClass, meta, type.getAnnotations());
39 }
40 // override any class level ones
41 if (annotations != null)
42 {
43 registerDecorators(targetClass, meta, annotations);
44 }
45 if (meta.size() == 0) return target;
46
47 MediaTypeMap<Class<?>> typeMap = new MediaTypeMap<Class<?>>();
48 for (Class<?> decoratorAnnotation : meta.keySet())
49 {
50 Decorator decorator = decoratorAnnotation.getAnnotation(Decorator.class);
51 String[] mediaTypes = {"*/*"};
52 DecorateTypes produces = decorator.processor().getAnnotation(DecorateTypes.class);
53 if (produces != null)
54 {
55 mediaTypes = produces.value();
56 }
57 for (String pType : mediaTypes)
58 {
59 typeMap.add(MediaType.valueOf(pType), decoratorAnnotation);
60 }
61 }
62
63 List<Class<?>> list = typeMap.getPossible(mediaType);
64 for (Class<?> decoratorAnnotation : list)
65 {
66 Annotation annotation = meta.get(decoratorAnnotation);
67 Decorator decorator = decoratorAnnotation.getAnnotation(Decorator.class);
68 DecoratorProcessor processor = null;
69 try
70 {
71 processor = decorator.processor().newInstance();
72 }
73 catch (InstantiationException e)
74 {
75 throw new RuntimeException(e.getCause());
76 }
77 catch (IllegalAccessException e)
78 {
79 throw new RuntimeException(e);
80 }
81 target = (T) processor.decorate(target, annotation, type, annotations, mediaType);
82 }
83
84 return target;
85 }
86
87 private <T> void registerDecorators(Class<T> targetClass, HashMap<Class<?>, Annotation> meta, Annotation[] annotations) {
88 for (Annotation annotation : annotations)
89 {
90 Decorator decorator = annotation.annotationType().getAnnotation(Decorator.class);
91 if (decorator != null && targetClass.isAssignableFrom(decorator.target()))
92 {
93 meta.put(annotation.annotationType(), annotation);
94 }
95 }
96 }
97 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
4 import org.jboss.resteasy.spi.ConstructorInjector;
5 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
7
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.AccessibleObject;
10 import java.lang.reflect.Array;
11 import java.lang.reflect.Method;
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.Comparator;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18
19 /**
20 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
21 * @version $Revision: 1 $
22 *
23 * @deprecated The Resteasy interceptor facility introduced in release 2.x
24 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
25 *
26 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
27 */
28 @Deprecated
29 @SuppressWarnings("unchecked")
30 public class InterceptorRegistry<T>
31 {
32 protected static interface InterceptorFactory
33 {
34 Object preMatch();
35 Object postMatch(Class declaring, AccessibleObject target);
36 int getOrder();
37 }
38
39 protected abstract class AbstractInterceptorFactory implements InterceptorFactory
40 {
41
42 protected String precedence = "DEFAULT";
43 protected int order = 100000;
44
45 protected void setPrecedence(Class<?> clazz)
46 {
47 Precedence precedence = clazz.getAnnotation(Precedence.class);
48 if (precedence != null)
49 {
50 this.precedence = precedence.value();
51 Integer o = precedenceOrder.get(this.precedence);
52 if (o == null) throw new RuntimeException(Messages.MESSAGES.unknownInterceptorPrecedence(this.precedence));
53 this.order = o;
54 }
55 else
56 {
57 for (Annotation annotation : clazz.getAnnotations())
58 {
59 precedence = annotation.annotationType().getAnnotation(Precedence.class);
60 if (precedence != null)
61 {
62 this.precedence = precedence.value();
63 Integer o = precedenceOrder.get(this.precedence);
64 if (o == null) throw new RuntimeException(Messages.MESSAGES.unknownInterceptorPrecedence(this.precedence));
65 this.order = o;
66 break;
67 }
68 }
69 }
70 }
71
72 public String getPrecedence()
73 {
74 return precedence;
75 }
76
77 public int getOrder()
78 {
79 return order;
80 }
81
82 protected Object binding(Class declaring, AccessibleObject target, Object inter)
83 {
84 if (inter instanceof AcceptedByMethod)
85 {
86 if (target == null || !(target instanceof Method)) return null;
87 Method method = (Method)target;
88 if (((AcceptedByMethod)inter).accept(declaring, method))
89 {
90 return inter;
91 }
92 else
93 {
94 return null;
95 }
96 }
97 return inter;
98 }
99 }
100
101
102 protected class SingletonInterceptorFactory extends AbstractInterceptorFactory
103 {
104 private Object interceptor;
105
106 public SingletonInterceptorFactory(Object interceptor)
107 {
108 this.interceptor = interceptor;
109 setPrecedence(interceptor.getClass());
110 }
111
112 @Override
113 public Object preMatch()
114 {
115 return null;
116 }
117
118 @Override
119 public Object postMatch(Class declaring, AccessibleObject target)
120 {
121 final Object inter = interceptor;
122 return binding(declaring, target, inter);
123 }
124
125 }
126
127 protected class PerMethodInterceptorFactory extends AbstractInterceptorFactory
128 {
129 private ConstructorInjector constructorInjector;
130
131 public PerMethodInterceptorFactory(Class clazz)
132 {
133 constructorInjector = providerFactory.createConstructorInjector(clazz);
134 setPrecedence(clazz);
135 }
136
137 @Override
138 public Object preMatch()
139 {
140 return null;
141 }
142
143 @Override
144 public Object postMatch(Class declaring, AccessibleObject target)
145 {
146 final Object inter = constructorInjector.construct();
147 return binding(declaring, target, inter);
148 }
149 }
150
151 protected ResteasyProviderFactory providerFactory;
152 protected Class<T> intf;
153 protected List<InterceptorFactory> interceptors = new ArrayList<InterceptorFactory>();
154 protected Map<String, Integer> precedenceOrder = new HashMap<String, Integer>();
155 protected List<String> precedenceList = new ArrayList<String>();
156 protected List<InterceptorRegistryListener> listeners = new ArrayList<InterceptorRegistryListener>();
157
158 public InterceptorRegistry<T> cloneTo(ResteasyProviderFactory factory)
159 {
160 InterceptorRegistry<T> clone = new InterceptorRegistry<T>(intf, factory);
161 clone.interceptors.addAll(interceptors);
162 clone.precedenceOrder.putAll(precedenceOrder);
163 precedenceList.addAll(precedenceList);
164 return clone;
165 }
166
167 public class PrecedenceComparator implements Comparator<InterceptorFactory>
168 {
169 public int compare(InterceptorFactory factory, InterceptorFactory factory2)
170 {
171 return factory.getOrder() - factory2.getOrder();
172 }
173 }
174
175 public List<InterceptorRegistryListener> getListeners()
176 {
177 return listeners;
178 }
179
180 public Class<T> getIntf()
181 {
182 return intf;
183 }
184
185 public InterceptorRegistry(Class<T> intf, ResteasyProviderFactory providerFactory)
186 {
187 this.providerFactory = providerFactory;
188 this.intf = intf;
189 precedenceOrder.put("DEFAULT", 100000);
190 }
191
192 protected void recalculateOrder()
193 {
194 precedenceOrder.clear();
195 for (int i = 0; i < precedenceList.size(); i++)
196 {
197 precedenceOrder.put(precedenceList.get(i), i);
198 }
199 precedenceOrder.put("DEFAULT", 100000);
200 }
201
202 public void appendPrecedence(String precedence)
203 {
204 precedenceList.add(precedence);
205 recalculateOrder();
206 }
207
208 public void insertPrecedenceAfter(String after, String newPrecedence)
209 {
210 for (int i = 0; i < precedenceList.size(); i++)
211 {
212 if (precedenceList.get(i).equals(after))
213 {
214 precedenceList.add(i + 1, newPrecedence);
215 break;
216 }
217 }
218 recalculateOrder();
219 }
220
221 public void insertPrecedenceBefore(String after, String newPrecedence)
222 {
223 for (int i = 0; i < precedenceList.size(); i++)
224 {
225 if (precedenceList.get(i).equals(after))
226 {
227 precedenceList.add(i, newPrecedence);
228 break;
229 }
230 }
231 recalculateOrder();
232 }
233
234 public T[] bind(Class declaring, AccessibleObject target)
235 {
236 List<T> list = bindForList(declaring, target);
237 return list.toArray((T[]) Array.newInstance(intf, list.size()));
238 }
239
240 public List<T> bindForList(Class declaring, AccessibleObject target)
241 {
242 List<T> list = new ArrayList<T>();
243 for (InterceptorFactory factory : interceptors)
244 {
245 Object interceptor = factory.postMatch(declaring, target);
246 if (interceptor != null) addNewInterceptor(list, interceptor);
247 }
248 return list;
249 }
250
251 protected void addNewInterceptor(List<T> list, Object interceptor)
252 {
253 providerFactory.injectProperties(interceptor);
254 list.add((T) interceptor);
255 }
256
257 public void register(Class<? extends T> clazz)
258 {
259 interceptors.add(new PerMethodInterceptorFactory(clazz));
260 Collections.sort(interceptors, new PrecedenceComparator());
261 for (InterceptorRegistryListener listener : listeners)
262 {
263 listener.registryUpdated(this);
264 }
265 }
266
267 public void register(T interceptor)
268 {
269 interceptors.add(new SingletonInterceptorFactory(interceptor));
270 Collections.sort(interceptors, new PrecedenceComparator());
271 for (InterceptorRegistryListener listener : listeners)
272 {
273 listener.registryUpdated(this);
274 }
275 }
276
277 }
0 package org.jboss.resteasy.core.interception;
1
2 /**
3 * Callback interface for when an interceptor registry changes
4 *
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 *
8 * @deprecated The Resteasy interceptor facility introduced in release 2.x
9 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
10 *
11 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
12 */
13 @Deprecated
14 public interface InterceptorRegistryListener
15 {
16 void registryUpdated(InterceptorRegistry registry);
17
18 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
5
6 import javax.annotation.Priority;
7 import javax.ws.rs.NameBinding;
8 import javax.ws.rs.Priorities;
9 import javax.ws.rs.container.PreMatching;
10 import javax.ws.rs.core.Application;
11
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.AccessibleObject;
14 import java.lang.reflect.Array;
15 import java.lang.reflect.Method;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.Comparator;
19 import java.util.List;
20 import java.util.concurrent.CopyOnWriteArrayList;
21
22 /**
23 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
24 * @version $Revision: 1 $
25 */
26 @SuppressWarnings("unchecked")
27 public class JaxrsInterceptorRegistry<T>
28 {
29 public static class Match
30 {
31 public Match(Object interceptor, int order)
32 {
33 this.interceptor = interceptor;
34 this.order = order;
35 }
36
37 final public Object interceptor;
38 final public int order;
39 }
40
41 public static interface InterceptorFactory
42 {
43 Match preMatch();
44
45 Match postMatch(Class declaring, AccessibleObject target);
46 }
47
48 protected static List<Class<? extends Annotation>> getNameBound(Class<?> declaring)
49 {
50 List<Class<? extends Annotation>> nameBound = new ArrayList<Class<? extends Annotation>>();
51 for (Annotation annotation : declaring.getAnnotations())
52 {
53 if (annotation.annotationType().isAnnotationPresent(NameBinding.class))
54 {
55 nameBound.add(annotation.annotationType());
56 }
57 }
58 return nameBound;
59 }
60
61 public static int getPriority(Class<?> declaring)
62 {
63 Priority priority = (Priority) declaring.getAnnotation(Priority.class);
64 if (priority != null) return priority.value();
65 return Priorities.USER;
66 }
67
68 public abstract class AbstractInterceptorFactory implements InterceptorFactory
69 {
70 protected final Class declaring;
71 protected int order = Priorities.USER;
72 protected List<Class<? extends Annotation>> nameBound;
73 protected volatile boolean initialized;
74 protected boolean ignorePrematch;
75
76 public AbstractInterceptorFactory(Class declaring)
77 {
78 this.declaring = declaring;
79 }
80
81 protected void setPrecedence(Class<?> declaring)
82 {
83 nameBound = getNameBound(declaring);
84 order = getPriority(declaring);
85 }
86
87 protected abstract void initialize();
88
89 protected abstract Object getInterceptor();
90
91 protected void checkInitialize()
92 {
93 boolean isInitialized = initialized;
94 if (!isInitialized)
95 {
96 synchronized (this)
97 {
98 isInitialized = initialized;
99 if (isInitialized) return;
100 isInitialized = initialized = true;
101 initialize();
102 }
103 }
104 }
105
106 public void setOrder(int order)
107 {
108 this.order = order;
109 }
110
111 public void setIgnorePrematch(boolean ignorePrematch)
112 {
113 this.ignorePrematch = ignorePrematch;
114 }
115
116 @Override
117 public Match preMatch()
118 {
119 if (declaring.isAnnotationPresent(PreMatching.class)) return new Match(getInterceptor(), order);
120 return null;
121 }
122
123 @Override
124 public Match postMatch(Class targetClass, AccessibleObject target)
125 {
126 if (!ignorePrematch && declaring.isAnnotationPresent(PreMatching.class)) return null;
127 if (targetClass != null && target != null)
128 {
129 if (nameBound.size() > 0)
130 {
131 Application application = ResteasyProviderFactory.getContextData(Application.class);
132 // must match all namebound annotations
133 for (Class<? extends Annotation> annotation : nameBound)
134 {
135 if (!targetClass.isAnnotationPresent(annotation) &&
136 !target.isAnnotationPresent(annotation)
137 && (application == null || !application.getClass().isAnnotationPresent(annotation)))
138 {
139 return null;
140 }
141 }
142 // we matched all of them
143 Object intercept = getInterceptor();
144 if (intercept == null)
145 throw new NullPointerException(Messages.MESSAGES.interceptorNullFromClass(this.getClass().getName()));
146 return new Match(intercept, order);
147 }
148 else
149 {
150 Object intercept = getInterceptor();
151 if (intercept == null)
152 throw new NullPointerException(Messages.MESSAGES.interceptorNullFromClass(this.getClass().getName()));
153 return new Match(intercept, order);
154 }
155 } else if (nameBound.size() == 0)
156 {
157 Object intercept = getInterceptor();
158 if (intercept == null)
159 throw new NullPointerException(Messages.MESSAGES.interceptorNullFromClass(this.getClass().getName()));
160 return new Match(intercept, order);
161 } else
162 {
163 return null;
164 }
165 }
166
167 protected Object createInterceptor()
168 {
169 return providerFactory.injectedInstance(declaring);
170 }
171 }
172
173
174 protected class OnDemandInterceptorFactory extends AbstractInterceptorFactory
175 {
176 protected volatile Object interceptor;
177
178 public OnDemandInterceptorFactory(Class declaring)
179 {
180 super(declaring);
181 setPrecedence(declaring);
182 }
183
184 @Override
185 protected void initialize()
186 {
187 interceptor = createInterceptor();
188 providerFactory.injectProperties(interceptor);
189 initialized = true;
190 }
191
192 protected void checkInitialize()
193 {
194 Object tmp = interceptor;
195 if (tmp == null)
196 {
197 synchronized (this)
198 {
199 tmp = interceptor;
200 if (tmp == null)
201 {
202 initialize();
203 tmp = interceptor;
204 }
205 }
206 }
207 }
208
209
210 @Override
211 protected Object getInterceptor()
212 {
213 checkInitialize();
214 return interceptor;
215 }
216 }
217
218 protected class SingletonInterceptorFactory extends AbstractInterceptorFactory
219 {
220 protected Object interceptor;
221
222 public SingletonInterceptorFactory(Class declaring, Object interceptor)
223 {
224 super(declaring);
225 this.interceptor = interceptor;
226 setPrecedence(declaring);
227 }
228
229 @Override
230 protected void initialize()
231 {
232 providerFactory.injectProperties(interceptor);
233 }
234
235 @Override
236 protected Object getInterceptor()
237 {
238 checkInitialize();
239 return interceptor;
240 }
241 }
242
243
244 public abstract class AbstractLegacyInterceptorFactory extends AbstractInterceptorFactory
245 {
246 protected LegacyPrecedence precedence;
247
248 protected AbstractLegacyInterceptorFactory(Class declaring, LegacyPrecedence precedence)
249 {
250 super(declaring);
251 this.precedence = precedence;
252 }
253
254 @Override
255 protected void setPrecedence(Class<?> declaring)
256 {
257 order = precedence.calculateOrder(declaring);
258 }
259
260 @Override
261 public Match preMatch()
262 {
263 return null;
264 }
265
266 public Object getLegacyMatch(Class declaring, AccessibleObject target)
267 {
268 Object interceptor = getInterceptor();
269 if (interceptor instanceof AcceptedByMethod)
270 {
271 if (target == null || !(target instanceof Method)) return null;
272 Method method = (Method) target;
273 if (((AcceptedByMethod) interceptor).accept(declaring, method))
274 {
275 return interceptor;
276 } else
277 {
278 return null;
279 }
280 }
281 return interceptor;
282 }
283
284 }
285
286 protected class LegacySingletonInterceptorFactory extends AbstractLegacyInterceptorFactory
287 {
288 protected Object interceptor;
289
290 public LegacySingletonInterceptorFactory(Class declaring, Object interceptor, LegacyPrecedence precedence)
291 {
292 super(declaring, precedence);
293 this.interceptor = interceptor;
294 setPrecedence(declaring);
295 }
296
297 @Override
298 protected void initialize()
299 {
300 providerFactory.injectProperties(interceptor);
301 }
302
303 @Override
304 protected Object getInterceptor()
305 {
306 checkInitialize();
307 return interceptor;
308 }
309 }
310
311 protected class LegacyPerMethodInterceptorFactory extends AbstractLegacyInterceptorFactory
312 {
313
314 public LegacyPerMethodInterceptorFactory(Class declaring, LegacyPrecedence precedence)
315 {
316 super(declaring, precedence);
317 setPrecedence(declaring);
318 }
319
320 @Override
321 protected void initialize()
322 {
323 }
324
325 @Override
326 protected Object getInterceptor()
327 {
328 Object interceptor = createInterceptor();
329 providerFactory.injectProperties(interceptor);
330 return interceptor;
331 }
332 }
333
334 protected List<InterceptorFactory> interceptors = new CopyOnWriteArrayList<InterceptorFactory>();
335 protected List<JaxrsInterceptorRegistryListener> listeners = new CopyOnWriteArrayList<JaxrsInterceptorRegistryListener>();
336 protected ResteasyProviderFactory providerFactory;
337 protected Class<T> intf;
338 protected volatile T[] cachedPreMatch;
339
340 public JaxrsInterceptorRegistry(ResteasyProviderFactory providerFactory, Class<T> intf)
341 {
342 this.providerFactory = providerFactory;
343 this.intf = intf;
344 }
345
346 public JaxrsInterceptorRegistry<T> clone(ResteasyProviderFactory factory)
347 {
348 JaxrsInterceptorRegistry<T> clone = new JaxrsInterceptorRegistry(factory, intf);
349 clone.interceptors.addAll(interceptors);
350 return clone;
351 }
352
353 public Class<T> getIntf()
354 {
355 return intf;
356 }
357
358 public static class AscendingPrecedenceComparator implements Comparator<Match>
359 {
360 public int compare(Match match, Match match2)
361 {
362 if (match.order < match2.order)
363 {
364 return -1;
365 }
366 if (match.order == match2.order)
367 {
368 return 0;
369 }
370 return 1;
371 }
372 }
373
374 public static class DescendingPrecedenceComparator implements Comparator<Match>
375 {
376 public int compare(Match match, Match match2)
377 {
378 if (match2.order < match.order)
379 {
380 return -1;
381 }
382 if (match2.order == match.order)
383 {
384 return 0;
385 }
386 return 1;
387 }
388 }
389
390
391 public List<JaxrsInterceptorRegistryListener> getListeners()
392 {
393 return listeners;
394 }
395
396 public T[] preMatch()
397 {
398 if (cachedPreMatch == null)
399 {
400 List<Match> matches = new ArrayList<Match>();
401 for (InterceptorFactory factory : interceptors)
402 {
403 Match match = factory.preMatch();
404 if (match != null)
405 {
406 matches.add(match);
407 }
408 }
409 cachedPreMatch = createArray(matches);
410 }
411 return cachedPreMatch;
412 }
413
414
415 public T[] postMatch(Class declaring, AccessibleObject target)
416 {
417 List<Match> matches = new ArrayList<Match>();
418 for (InterceptorFactory factory : interceptors)
419 {
420 Match match = factory.postMatch(declaring, target);
421 if (match != null)
422 {
423 matches.add(match);
424 }
425 }
426 return createArray(matches);
427 }
428
429 private T[] createArray(List<Match> matches)
430 {
431 sort(matches);
432 T[] array = (T[]) Array.newInstance(intf, matches.size());
433 for (int i = 0; i < array.length; i++)
434 {
435 array[i] = (T) matches.get(i).interceptor;
436 }
437 return array;
438 }
439
440 protected void sort(List<Match> matches)
441 {
442 Collections.sort(matches, new AscendingPrecedenceComparator());
443 }
444
445 public synchronized void register(InterceptorFactory factory)
446 {
447 interceptors.add(factory);
448 cachedPreMatch = null;
449 for (JaxrsInterceptorRegistryListener listener : listeners)
450 {
451 listener.registryUpdated(this);
452 }
453 }
454
455 public synchronized void registerClass(Class<? extends T> declaring)
456 {
457 register(new OnDemandInterceptorFactory(declaring));
458 }
459
460 public synchronized void registerClass(Class<? extends T> declaring, int priority)
461 {
462 OnDemandInterceptorFactory factory = new OnDemandInterceptorFactory(declaring);
463 factory.setOrder(priority);
464 register(factory);
465 }
466
467 public synchronized void registerSingleton(T interceptor)
468 {
469 register(new SingletonInterceptorFactory(interceptor.getClass(), interceptor));
470 }
471
472 public synchronized void registerSingleton(T interceptor, int priority)
473 {
474 SingletonInterceptorFactory factory = new SingletonInterceptorFactory(interceptor.getClass(), interceptor);
475 factory.setOrder(priority);
476 register(factory);
477 }
478 }
0 package org.jboss.resteasy.core.interception;
1
2 /**
3 * Callback interface for when an interceptor registry changes
4 *
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 */
8 public interface JaxrsInterceptorRegistryListener
9 {
10 void registryUpdated(JaxrsInterceptorRegistry registry);
11
12 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
4
5 import javax.annotation.Priority;
6 import javax.ws.rs.Priorities;
7
8 import java.lang.annotation.Annotation;
9 import java.util.ArrayList;
10 import java.util.HashMap;
11 import java.util.List;
12 import java.util.Map;
13
14 /**
15 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
16 * @version $Revision: 1 $
17 */
18 @Deprecated
19 public class LegacyPrecedence
20 {
21 private static final int DEFAULTS_ORDER = 100000;
22 protected Map<String, Integer> precedenceOrder = new HashMap<String, Integer>();
23 protected List<String> precedenceList = new ArrayList<String>();
24
25 public LegacyPrecedence clone()
26 {
27 LegacyPrecedence precedence = new LegacyPrecedence();
28 precedence.precedenceList.addAll(precedenceList);
29 precedence.precedenceOrder.putAll(precedenceOrder);
30 return precedence;
31 }
32
33 public int calculateOrder(Class<?> clazz)
34 {
35 Precedence precedence = (Precedence)clazz.getAnnotation(Precedence.class);
36 if (precedence != null)
37 {
38 String value = precedence.value();
39 Integer o = precedenceOrder.get(value);
40 if (o == null) throw new RuntimeException(Messages.MESSAGES.unknownInterceptorPrecedence(value));
41 return o;
42 }
43 else
44 {
45 for (Annotation annotation : clazz.getAnnotations())
46 {
47 precedence = annotation.annotationType().getAnnotation(Precedence.class);
48 if (precedence != null)
49 {
50 String value = precedence.value();
51 Integer o = precedenceOrder.get(value);
52 if (o == null) throw new RuntimeException(Messages.MESSAGES.unknownInterceptorPrecedence(value));
53 return o;
54 }
55 }
56 }
57 return Priorities.USER;
58 }
59
60 public void addPrecedence(String precedent, int order)
61 {
62 precedenceList.add(precedent);
63 precedenceOrder.put(precedent, order);
64 }
65
66 public void appendPrecedence(String precedence)
67 {
68 precedenceList.add(precedence);
69
70 int greatest = 0;
71 for (Integer i : precedenceOrder.values())
72 {
73 if (i > greatest && ((int)i) != DEFAULTS_ORDER) greatest = i;
74 }
75
76 addPrecedence(precedence, greatest + 100);
77 }
78
79 public void insertPrecedenceAfter(String after, String newPrecedence)
80 {
81 int order = precedenceOrder.get(after);
82 order++;
83 addPrecedence(newPrecedence, order);
84 }
85
86 public void insertPrecedenceBefore(String after, String newPrecedence)
87 {
88 int order = precedenceOrder.get(after);
89 order--;
90 addPrecedence(newPrecedence, order);
91 }
92
93 public LegacyPrecedence()
94 {
95 precedenceOrder.put("DEFAULT", DEFAULTS_ORDER);
96 }
97
98 }
0 package org.jboss.resteasy.core.interception;
1
2 import java.net.URI;
3 import java.util.function.Supplier;
4
5 import javax.ws.rs.container.ContainerRequestFilter;
6
7 import org.jboss.resteasy.core.ResourceMethodInvoker;
8 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
9 import org.jboss.resteasy.specimpl.BuiltResponse;
10 import org.jboss.resteasy.spi.HttpRequest;
11
12 /**
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 */
16 public class PostMatchContainerRequestContext extends PreMatchContainerRequestContext
17 {
18 protected final ResourceMethodInvoker resourceMethod;
19
20 @Deprecated
21 public PostMatchContainerRequestContext(HttpRequest request,ResourceMethodInvoker resourceMethod)
22 {
23 this(request, resourceMethod, new ContainerRequestFilter[]{}, null);
24 }
25
26 public PostMatchContainerRequestContext(HttpRequest request,ResourceMethodInvoker resourceMethod,
27 ContainerRequestFilter[] requestFilters, Supplier<BuiltResponse> continuation)
28 {
29 super(request, requestFilters, continuation);
30 this.resourceMethod = resourceMethod;
31 }
32
33 public ResourceMethodInvoker getResourceMethod()
34 {
35 return resourceMethod;
36 }
37
38 @Override
39 public void setMethod(String method)
40 {
41 throw new IllegalStateException(Messages.MESSAGES.cantSetMethod());
42 }
43
44 @Override
45 public void setRequestUri(URI requestUri) throws IllegalStateException
46 {
47 throw new IllegalStateException(Messages.MESSAGES.cantSetURI());
48 }
49
50 @Override
51 public void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException
52 {
53 throw new IllegalStateException(Messages.MESSAGES.cantSetURI());
54 }
55 }
0 package org.jboss.resteasy.core.interception;
1
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.net.URI;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.Date;
8 import java.util.Enumeration;
9 import java.util.List;
10 import java.util.Locale;
11 import java.util.Map;
12 import java.util.function.Supplier;
13
14 import javax.ws.rs.container.ContainerRequestFilter;
15 import javax.ws.rs.core.Cookie;
16 import javax.ws.rs.core.MediaType;
17 import javax.ws.rs.core.MultivaluedMap;
18 import javax.ws.rs.core.Request;
19 import javax.ws.rs.core.Response;
20 import javax.ws.rs.core.SecurityContext;
21 import javax.ws.rs.core.UriInfo;
22
23 import org.jboss.resteasy.core.Dispatcher;
24 import org.jboss.resteasy.core.SynchronousDispatcher;
25 import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerRequestContext;
26 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
27 import org.jboss.resteasy.specimpl.BuiltResponse;
28 import org.jboss.resteasy.spi.ApplicationException;
29 import org.jboss.resteasy.spi.HttpRequest;
30 import org.jboss.resteasy.spi.HttpResponse;
31 import org.jboss.resteasy.spi.ResteasyProviderFactory;
32
33 /**
34 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
35 * @version $Revision: 1 $
36 */
37 public class PreMatchContainerRequestContext implements SuspendableContainerRequestContext
38 {
39 protected final HttpRequest httpRequest;
40 protected Response response;
41 private ContainerRequestFilter[] requestFilters;
42 private int currentFilter;
43 private boolean suspended;
44 private boolean filterReturnIsMeaningful = true;
45 private Supplier<BuiltResponse> continuation;
46 private Map<Class<?>, Object> contextDataMap;
47 private boolean inFilter;
48 private Throwable throwable;
49 private boolean startedContinuation;
50
51 @Deprecated
52 public PreMatchContainerRequestContext(HttpRequest request)
53 {
54 this(request, new ContainerRequestFilter[]{}, null);
55 }
56
57 public PreMatchContainerRequestContext(HttpRequest request,
58 ContainerRequestFilter[] requestFilters, Supplier<BuiltResponse> continuation)
59 {
60 this.httpRequest = request;
61 this.requestFilters = requestFilters;
62 this.continuation = continuation;
63 contextDataMap = ResteasyProviderFactory.getContextDataMap();
64 }
65
66 public HttpRequest getHttpRequest()
67 {
68 return httpRequest;
69 }
70
71 public Response getResponseAbortedWith()
72 {
73 return response;
74 }
75
76 @Override
77 public Object getProperty(String name)
78 {
79 return httpRequest.getAttribute(name);
80 }
81
82 @Override
83 public Collection<String> getPropertyNames()
84 {
85 ArrayList<String> names = new ArrayList<String>();
86 Enumeration<String> enames = httpRequest.getAttributeNames();
87 while (enames.hasMoreElements())
88 {
89 names.add(enames.nextElement());
90 }
91 return names;
92 }
93
94 @Override
95 public void setProperty(String name, Object object)
96 {
97 httpRequest.setAttribute(name, object);
98 }
99
100 @Override
101 public void removeProperty(String name)
102 {
103 httpRequest.removeAttribute(name);
104 }
105
106 @Override
107 public UriInfo getUriInfo()
108 {
109 return httpRequest.getUri();
110 }
111
112 @Override
113 public void setRequestUri(URI requestUri) throws IllegalStateException
114 {
115 httpRequest.setRequestUri(requestUri);
116 }
117
118 @Override
119 public void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException
120 {
121 httpRequest.setRequestUri(baseUri, requestUri);
122 }
123
124 @Override
125 public String getMethod()
126 {
127 return httpRequest.getHttpMethod();
128 }
129
130 @Override
131 public void setMethod(String method)
132 {
133 httpRequest.setHttpMethod(method);
134 }
135
136 @Override
137 public MultivaluedMap<String, String> getHeaders()
138 {
139 return httpRequest.getHttpHeaders().getRequestHeaders();
140 }
141
142 @Override
143 public Date getDate()
144 {
145 return httpRequest.getHttpHeaders().getDate();
146 }
147
148 @Override
149 public Locale getLanguage()
150 {
151 return httpRequest.getHttpHeaders().getLanguage();
152 }
153
154 @Override
155 public int getLength()
156 {
157 return httpRequest.getHttpHeaders().getLength();
158 }
159
160 @Override
161 public MediaType getMediaType()
162 {
163 return httpRequest.getHttpHeaders().getMediaType();
164 }
165
166 @Override
167 public List<MediaType> getAcceptableMediaTypes()
168 {
169 return httpRequest.getHttpHeaders().getAcceptableMediaTypes();
170 }
171
172 @Override
173 public List<Locale> getAcceptableLanguages()
174 {
175 return httpRequest.getHttpHeaders().getAcceptableLanguages();
176 }
177
178 @Override
179 public Map<String, Cookie> getCookies()
180 {
181 return httpRequest.getHttpHeaders().getCookies();
182 }
183
184 @Override
185 public boolean hasEntity()
186 {
187 return getMediaType() != null;
188 }
189
190 @Override
191 public InputStream getEntityStream()
192 {
193 return httpRequest.getInputStream();
194 }
195
196 @Override
197 public void setEntityStream(InputStream entityStream)
198 {
199 httpRequest.setInputStream(entityStream);
200 }
201
202 @Override
203 public SecurityContext getSecurityContext()
204 {
205 return ResteasyProviderFactory.getContextData(SecurityContext.class);
206 }
207
208 @Override
209 public void setSecurityContext(SecurityContext context)
210 {
211 ResteasyProviderFactory.pushContext(SecurityContext.class, context);
212 }
213
214 @Override
215 public Request getRequest()
216 {
217 return ResteasyProviderFactory.getContextData(Request.class);
218 }
219
220 @Override
221 public String getHeaderString(String name)
222 {
223 return httpRequest.getHttpHeaders().getHeaderString(name);
224 }
225
226 @Override
227 public synchronized void suspend() {
228 if(continuation == null)
229 throw new RuntimeException("Suspend not supported yet");
230 suspended = true;
231 }
232
233 @Override
234 public synchronized void abortWith(Response response)
235 {
236 if(suspended && !inFilter)
237 {
238 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
239 httpRequest.getAsyncContext().getAsyncResponse().resume(response);
240 }
241 else
242 {
243 // not suspended, or suspend/abortWith within filter, same thread: collect and move on
244 this.response = response;
245 suspended = false;
246 }
247 }
248
249 @Override
250 public synchronized void resume() {
251 if(!suspended)
252 throw new RuntimeException("Cannot resume: not suspended");
253 if(inFilter)
254 {
255 // suspend/resume within filter, same thread: just ignore and move on
256 suspended = false;
257 return;
258 }
259
260 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
261 // go on, but with proper exception handling
262 try {
263 filter();
264 }catch(Throwable t) {
265 // don't throw to client
266 writeException(t);
267 }
268 }
269
270 @Override
271 public synchronized void resume(Throwable t) {
272 if(!suspended)
273 throw new RuntimeException("Cannot resume: not suspended");
274 if(inFilter)
275 {
276 // not suspended, or suspend/abortWith within filter, same thread: collect and move on
277 throwable = t;
278 suspended = false;
279 }
280 else
281 {
282 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
283 writeException(t);
284 }
285 }
286
287 private void writeException(Throwable t)
288 {
289 HttpRequest httpRequest = (HttpRequest) contextDataMap.get(HttpRequest.class);
290 HttpResponse httpResponse = (HttpResponse) contextDataMap.get(HttpResponse.class);
291 SynchronousDispatcher dispatcher = (SynchronousDispatcher) contextDataMap.get(Dispatcher.class);
292 try {
293 dispatcher.writeException(httpRequest, httpResponse, t, t2 -> {});
294 }catch(Throwable x) {
295 dispatcher.unhandledAsynchronousException(httpResponse, x);
296 }
297 }
298
299 public synchronized BuiltResponse filter()
300 {
301 while(currentFilter < requestFilters.length)
302 {
303 ContainerRequestFilter filter = requestFilters[currentFilter++];
304 try
305 {
306 suspended = false;
307 response = null;
308 throwable = null;
309 inFilter = true;
310 filter.filter(this);
311 }
312 catch (IOException e)
313 {
314 throw new ApplicationException(e);
315 }
316 finally
317 {
318 inFilter = false;
319 }
320 if(suspended) {
321 if(!httpRequest.getAsyncContext().isSuspended())
322 httpRequest.getAsyncContext().suspend();
323 // ignore any abort request until we are resumed
324 filterReturnIsMeaningful = false;
325 response = null;
326 return null;
327 }
328 BuiltResponse serverResponse = (BuiltResponse)getResponseAbortedWith();
329 if (serverResponse != null)
330 {
331 // handle the case where we've been suspended by a previous filter
332 if(filterReturnIsMeaningful)
333 return serverResponse;
334 else
335 {
336 httpRequest.getAsyncContext().getAsyncResponse().resume(serverResponse);
337 return null;
338 }
339 }
340 if (throwable != null)
341 {
342 // handle the case where we've been suspended by a previous filter
343 if(filterReturnIsMeaningful)
344 SynchronousDispatcher.rethrow(throwable);
345 else
346 {
347 writeException(throwable);
348 return null;
349 }
350 }
351 }
352 // here it means we reached the last filter
353 // some frameworks don't support async request filters, in which case suspend() is forbidden
354 // so if we get here we're still synchronous and don't have a continuation, which must be in
355 // the caller
356 startedContinuation = true;
357 if(continuation == null)
358 return null;
359 // in any case, return the continuation: sync will use it, and async will ignore it
360 return continuation.get();
361 }
362
363 public boolean startedContinuation()
364 {
365 return startedContinuation;
366 }
367 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3 import org.jboss.resteasy.spi.interception.MessageBodyReaderContext;
4 import org.jboss.resteasy.spi.interception.MessageBodyReaderInterceptor;
5
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.ReaderInterceptor;
10 import javax.ws.rs.ext.ReaderInterceptorContext;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.AccessibleObject;
15 import java.lang.reflect.Type;
16
17 /**
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 */
21 public class ReaderInterceptorRegistry extends JaxrsInterceptorRegistry<ReaderInterceptor>
22 {
23 protected LegacyPrecedence precedence;
24
25 public ReaderInterceptorRegistry(ResteasyProviderFactory providerFactory, LegacyPrecedence precedence)
26 {
27 super(providerFactory, ReaderInterceptor.class);
28 this.precedence = precedence;
29 }
30
31 public ReaderInterceptorRegistry clone(ResteasyProviderFactory factory)
32 {
33 ReaderInterceptorRegistry clone = new ReaderInterceptorRegistry(factory, precedence);
34 clone.interceptors.addAll(interceptors);
35 return clone;
36 }
37
38 private static class MessageBodyReaderContextFacade implements MessageBodyReaderContext
39 {
40 protected final ReaderInterceptorContext readerInterceptorContext;
41
42 private MessageBodyReaderContextFacade(ReaderInterceptorContext readerInterceptorContext)
43 {
44 this.readerInterceptorContext = readerInterceptorContext;
45 }
46
47 @Override
48 public Class getType()
49 {
50 return readerInterceptorContext.getType();
51 }
52
53 @Override
54 public void setType(Class type)
55 {
56 readerInterceptorContext.setType(type);
57 }
58
59 @Override
60 public Type getGenericType()
61 {
62 return readerInterceptorContext.getGenericType();
63 }
64
65 @Override
66 public void setGenericType(Type genericType)
67 {
68 readerInterceptorContext.setGenericType(genericType);
69 }
70
71 @Override
72 public Annotation[] getAnnotations()
73 {
74 return readerInterceptorContext.getAnnotations();
75 }
76
77 @Override
78 public void setAnnotations(Annotation[] annotations)
79 {
80 readerInterceptorContext.setAnnotations(annotations);
81 }
82
83 @Override
84 public MediaType getMediaType()
85 {
86 return readerInterceptorContext.getMediaType();
87 }
88
89 @Override
90 public void setMediaType(MediaType mediaType)
91 {
92 readerInterceptorContext.setMediaType(mediaType);
93 }
94
95 @Override
96 public MultivaluedMap<String, String> getHeaders()
97 {
98 return readerInterceptorContext.getHeaders();
99 }
100
101 @Override
102 public InputStream getInputStream()
103 {
104 return readerInterceptorContext.getInputStream();
105 }
106
107 @Override
108 public void setInputStream(InputStream is)
109 {
110 readerInterceptorContext.setInputStream(is);
111 }
112
113 @Override
114 public Object getAttribute(String attribute)
115 {
116 return readerInterceptorContext.getProperty(attribute);
117 }
118
119 @Override
120 public void setAttribute(String name, Object value)
121 {
122 readerInterceptorContext.setProperty(name, value);
123 }
124
125 @Override
126 public void removeAttribute(String name)
127 {
128 readerInterceptorContext.removeProperty(name);
129 }
130
131 @Override
132 public Object proceed() throws IOException, WebApplicationException
133 {
134 return readerInterceptorContext.proceed();
135 }
136 }
137
138 public static class ReaderInterceptorFacade implements ReaderInterceptor
139 {
140 protected final MessageBodyReaderInterceptor interceptor;
141
142 public ReaderInterceptorFacade(MessageBodyReaderInterceptor interceptor)
143 {
144 this.interceptor = interceptor;
145 }
146
147 public MessageBodyReaderInterceptor getInterceptor()
148 {
149 return interceptor;
150 }
151
152 @Override
153 public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException
154 {
155 MessageBodyReaderContextFacade facade = new MessageBodyReaderContextFacade(readerInterceptorContext);
156 return interceptor.read(facade);
157 }
158 }
159
160
161 public void registerLegacy(Class<? extends MessageBodyReaderInterceptor> decl)
162 {
163 register(new LegacyPerMethodInterceptorFactory(decl, precedence)
164 {
165 @Override
166 public Match postMatch(Class declaring, AccessibleObject target)
167 {
168 Object obj = getLegacyMatch(declaring, target);
169 if (obj == null) return null;
170 MessageBodyReaderInterceptor interceptor = (MessageBodyReaderInterceptor)obj;
171 return new Match(new ReaderInterceptorFacade(interceptor), order);
172 }
173
174 });
175 }
176
177 public void registerLegacy(MessageBodyReaderInterceptor interceptor)
178 {
179 register(new LegacySingletonInterceptorFactory(interceptor.getClass(), interceptor, precedence)
180 {
181 @Override
182 public Match postMatch(Class declaring, AccessibleObject target)
183 {
184 Object obj = getLegacyMatch(declaring, target);
185 if (obj == null) return null;
186 MessageBodyReaderInterceptor interceptor = (MessageBodyReaderInterceptor)obj;
187 return new Match(new ReaderInterceptorFacade(interceptor), order);
188 }
189 });
190
191 }
192 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.spi.HttpRequest;
4
5 import javax.ws.rs.core.Response;
6 import javax.ws.rs.core.SecurityContext;
7
8 import java.io.InputStream;
9 import java.net.URI;
10
11 /**
12 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
13 * @version $Revision: 1 $
14 */
15 public class ResponseContainerRequestContext extends PreMatchContainerRequestContext
16 {
17 public ResponseContainerRequestContext(HttpRequest request)
18 {
19 super(request, null, null);
20 }
21
22
23
24 @Override
25 public void abortWith(Response response)
26 {
27 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
28 }
29
30 @Override
31 public void setSecurityContext(SecurityContext context)
32 {
33 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
34 }
35
36 @Override
37 public void setEntityStream(InputStream entityStream)
38 {
39 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
40 }
41
42 @Override
43 public void setMethod(String method)
44 {
45 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
46 }
47
48 @Override
49 public void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException
50 {
51 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
52 }
53
54 @Override
55 public void setRequestUri(URI requestUri) throws IllegalStateException
56 {
57 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
58 }
59 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.spi.HttpRequest;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import javax.ws.rs.BadRequestException;
7 import javax.ws.rs.NotSupportedException;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.MultivaluedMap;
10 import javax.ws.rs.core.NoContentException;
11 import javax.ws.rs.ext.MessageBodyReader;
12 import javax.ws.rs.ext.ReaderInterceptor;
13
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.lang.annotation.Annotation;
17 import java.lang.reflect.Type;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Enumeration;
21
22 /**
23 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
24 * @version $Revision: 1 $
25 */
26 public class ServerReaderInterceptorContext extends AbstractReaderInterceptorContext
27 {
28 private HttpRequest request;
29
30 public ServerReaderInterceptorContext(ReaderInterceptor[] interceptors, ResteasyProviderFactory providerFactory, Class type,
31 Type genericType, Annotation[] annotations, MediaType mediaType,
32 MultivaluedMap<String, String> headers, InputStream inputStream,
33 HttpRequest request)
34 {
35 super(mediaType, providerFactory, annotations, interceptors, headers, genericType, type, inputStream);
36 this.request = request;
37 }
38
39 @Override
40 protected MessageBodyReader resolveReader(MediaType mediaType)
41 {
42 @SuppressWarnings(value = "unchecked")
43 MessageBodyReader reader = providerFactory.getServerMessageBodyReader(type,
44 genericType, annotations, mediaType);
45 //logger.info("**** picked reader: " + reader.getClass().getName());
46 return reader;
47 }
48
49 @Override
50 protected void throwReaderNotFound()
51 {
52 throw new NotSupportedException(Messages.MESSAGES.couldNotFindMessageBodyReader(genericType, mediaType));
53 }
54
55 @Override
56 protected Object readFrom(MessageBodyReader reader) throws IOException
57 {
58 try
59 {
60 return super.readFrom(reader);
61 }
62 catch (NoContentException e)
63 {
64 throw new BadRequestException(e);
65 }
66 }
67
68 @Override
69 public Object getProperty(String name)
70 {
71 return request.getAttribute(name);
72 }
73
74 @Override
75 public Collection<String> getPropertyNames()
76 {
77 ArrayList<String> names = new ArrayList<String>();
78 Enumeration<String> enames = request.getAttributeNames();
79 while (enames.hasMoreElements())
80 {
81 names.add(enames.nextElement());
82 }
83 return names;
84 }
85
86 @Override
87 public void setProperty(String name, Object object)
88 {
89 if (object == null)
90 {
91 request.removeAttribute(name);
92 }
93 else
94 {
95 request.setAttribute(name, object);
96 }
97 }
98
99 @Override
100 public void removeProperty(String name)
101 {
102 request.removeAttribute(name);
103 }
104 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure;
3 import org.jboss.resteasy.spi.HttpRequest;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.WriterInterceptor;
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Enumeration;
17
18 /**
19 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
20 * @version $Revision: 1 $
21 */
22 public class ServerWriterInterceptorContext extends AbstractWriterInterceptorContext
23 {
24 private HttpRequest request;
25
26 public ServerWriterInterceptorContext(WriterInterceptor[] interceptors, ResteasyProviderFactory providerFactory,
27 Object entity, Class type, Type genericType, Annotation[] annotations,
28 MediaType mediaType, MultivaluedMap<String, Object> headers,
29 OutputStream outputStream,
30 HttpRequest request)
31 {
32 super(interceptors, annotations, entity, genericType, mediaType, type, outputStream, providerFactory, headers);
33 this.request = request;
34 }
35
36 @SuppressWarnings(value = "unchecked")
37 @Override
38 protected MessageBodyWriter resolveWriter()
39 {
40 return providerFactory.getServerMessageBodyWriter(
41 type, genericType, annotations, mediaType);
42
43 }
44 @Override
45 void throwWriterNotFoundException()
46 {
47 throw new NoMessageBodyWriterFoundFailure(type, mediaType);
48 }
49
50 @Override
51 public Object getProperty(String name)
52 {
53 return request.getAttribute(name);
54 }
55
56 @Override
57 protected void writeTo(MessageBodyWriter writer) throws IOException
58 {
59 //logger.info("*** " + request.getUri().getPath() + " writeTo(" + entity.toString() + ", " + mediaType);
60 super.writeTo(writer);
61 }
62
63 @Override
64 public Collection<String> getPropertyNames()
65 {
66 ArrayList<String> names = new ArrayList<String>();
67 Enumeration<String> enames = request.getAttributeNames();
68 while (enames.hasMoreElements())
69 {
70 names.add(enames.nextElement());
71 }
72 return names;
73 }
74
75 @Override
76 public void setProperty(String name, Object object)
77 {
78 if (object == null)
79 {
80 request.removeAttribute(name);
81 }
82 else
83 {
84 request.setAttribute(name, object);
85 }
86 }
87
88 @Override
89 public void removeProperty(String name)
90 {
91 request.removeAttribute(name);
92 }
93 }
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
5
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.WriterInterceptor;
10 import javax.ws.rs.ext.WriterInterceptorContext;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.AccessibleObject;
15 import java.lang.reflect.Type;
16
17 /**
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 */
21 public class WriterInterceptorRegistry extends JaxrsInterceptorRegistry<WriterInterceptor>
22 {
23 protected LegacyPrecedence precedence;
24
25 public WriterInterceptorRegistry(ResteasyProviderFactory providerFactory, LegacyPrecedence precedence)
26 {
27 super(providerFactory, WriterInterceptor.class);
28 this.precedence = precedence;
29 }
30
31 public WriterInterceptorRegistry clone(ResteasyProviderFactory factory)
32 {
33 WriterInterceptorRegistry clone = new WriterInterceptorRegistry(factory, precedence);
34 clone.interceptors.addAll(interceptors);
35 return clone;
36 }
37
38 private static class MessageBodyWriterContextFacade implements MessageBodyWriterContext
39 {
40 protected final WriterInterceptorContext writerInterceptorContext;
41
42 private MessageBodyWriterContextFacade(WriterInterceptorContext writerInterceptorContext)
43 {
44 this.writerInterceptorContext = writerInterceptorContext;
45 }
46
47 @Override
48 public Class getType()
49 {
50 return writerInterceptorContext.getType();
51 }
52
53 @Override
54 public void setType(Class type)
55 {
56 writerInterceptorContext.setType(type);
57 }
58
59 @Override
60 public Type getGenericType()
61 {
62 return writerInterceptorContext.getGenericType();
63 }
64
65 @Override
66 public void setGenericType(Type genericType)
67 {
68 writerInterceptorContext.setGenericType(genericType);
69 }
70
71 @Override
72 public Annotation[] getAnnotations()
73 {
74 return writerInterceptorContext.getAnnotations();
75 }
76
77 @Override
78 public void setAnnotations(Annotation[] annotations)
79 {
80 writerInterceptorContext.setAnnotations(annotations);
81 }
82
83 @Override
84 public MediaType getMediaType()
85 {
86 return writerInterceptorContext.getMediaType();
87 }
88
89 @Override
90 public void setMediaType(MediaType mediaType)
91 {
92 writerInterceptorContext.setMediaType(mediaType);
93 }
94
95 @Override
96 public MultivaluedMap<String, Object> getHeaders()
97 {
98 return writerInterceptorContext.getHeaders();
99 }
100
101 @Override
102 public Object getAttribute(String attribute)
103 {
104 return writerInterceptorContext.getProperty(attribute);
105 }
106
107 @Override
108 public void setAttribute(String name, Object value)
109 {
110 writerInterceptorContext.setProperty(name, value);
111 }
112
113 @Override
114 public void removeAttribute(String name)
115 {
116 writerInterceptorContext.removeProperty(name);
117 }
118
119 @Override
120 public Object getEntity()
121 {
122 return writerInterceptorContext.getEntity();
123 }
124
125 @Override
126 public void setEntity(Object entity)
127 {
128 writerInterceptorContext.setEntity(entity);
129 }
130
131 @Override
132 public OutputStream getOutputStream()
133 {
134 return writerInterceptorContext.getOutputStream();
135 }
136
137 @Override
138 public void setOutputStream(OutputStream os)
139 {
140 writerInterceptorContext.setOutputStream(os);
141 }
142
143 @Override
144 public void proceed() throws IOException, WebApplicationException
145 {
146 writerInterceptorContext.proceed();
147 }
148 }
149
150 public static class WriterInterceptorFacade implements WriterInterceptor
151 {
152 protected final MessageBodyWriterInterceptor interceptor;
153
154 public WriterInterceptorFacade(MessageBodyWriterInterceptor interceptor)
155 {
156 this.interceptor = interceptor;
157 }
158
159 public MessageBodyWriterInterceptor getInterceptor()
160 {
161 return interceptor;
162 }
163
164 @Override
165 public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException
166 {
167 MessageBodyWriterContextFacade facade = new MessageBodyWriterContextFacade(writerInterceptorContext);
168 interceptor.write(facade);
169 }
170 }
171
172
173 public void registerLegacy(Class<? extends MessageBodyWriterInterceptor> decl)
174 {
175 register(new LegacyPerMethodInterceptorFactory(decl, precedence)
176 {
177 @Override
178 public Match postMatch(Class declaring, AccessibleObject target)
179 {
180 Object obj = getLegacyMatch(declaring, target);
181 if (obj == null) return null;
182 MessageBodyWriterInterceptor interceptor = (MessageBodyWriterInterceptor)obj;
183 return new Match(new WriterInterceptorFacade(interceptor), order);
184 }
185
186 });
187 }
188
189 public void registerLegacy(MessageBodyWriterInterceptor interceptor)
190 {
191 register(new LegacySingletonInterceptorFactory(interceptor.getClass(), interceptor, precedence)
192 {
193 @Override
194 public Match postMatch(Class declaring, AccessibleObject target)
195 {
196 Object obj = getLegacyMatch(declaring, target);
197 if (obj == null) return null;
198 MessageBodyWriterInterceptor interceptor = (MessageBodyWriterInterceptor)obj;
199 return new Match(new WriterInterceptorFacade(interceptor), order);
200 }
201 });
202
203 }
204 }
+0
-155
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/AbstractReaderInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.NotSupportedException;
6 import javax.ws.rs.core.HttpHeaders;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyReader;
10 import javax.ws.rs.ext.ReaderInterceptor;
11 import javax.ws.rs.ext.ReaderInterceptorContext;
12
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17
18 /**
19 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
20 * @version $Revision: 1 $
21 */
22 public abstract class AbstractReaderInterceptorContext implements ReaderInterceptorContext
23 {
24 protected ReaderInterceptor[] interceptors;
25 protected ResteasyProviderFactory providerFactory;
26 protected Class type;
27 protected Type genericType;
28 protected Annotation[] annotations;
29 protected MediaType mediaType;
30 protected MultivaluedMap<String, String> headers;
31 protected InputStream inputStream;
32 protected int index = 0;
33
34 public AbstractReaderInterceptorContext(MediaType mediaType, ResteasyProviderFactory providerFactory, Annotation[] annotations, ReaderInterceptor[] interceptors, MultivaluedMap<String, String> headers, Type genericType, Class type, InputStream inputStream)
35 {
36 this.mediaType = mediaType;
37 this.annotations = annotations;
38 this.interceptors = interceptors;
39 this.headers = headers;
40 this.genericType = genericType;
41 this.type = type;
42 this.inputStream = inputStream;
43 this.providerFactory = providerFactory;
44 }
45
46 @Override
47 public Object proceed() throws IOException
48 {
49 LogMessages.LOGGER.debugf("Interceptor Context: %s, Method : proceed", getClass().getName());
50 if (interceptors == null || index >= interceptors.length)
51 {
52 MessageBodyReader reader = getReader();
53 if (reader!=null)
54 LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName());
55 return readFrom(reader);
56 }
57 LogMessages.LOGGER.debugf("ReaderInterceptor: %s", interceptors[index].getClass().getName());
58 return interceptors[index++].aroundReadFrom(this);
59 // index--; we used to pop the index, but the TCK does not like this
60 }
61
62 @SuppressWarnings(value = "unchecked")
63 protected Object readFrom(MessageBodyReader reader) throws IOException
64 {
65 return reader.readFrom(type, genericType, annotations, mediaType, headers, inputStream);
66 }
67
68 protected MessageBodyReader getReader()
69 {
70 MediaType mediaType = this.mediaType;
71 // spec says set to octet stream
72 if (getHeaders() != null && getHeaders().getFirst(HttpHeaders.CONTENT_TYPE) == null && mediaType.isWildcardType())
73 {
74 mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
75 }
76 MessageBodyReader reader = resolveReader(mediaType);
77 if (reader == null)
78 {
79 throwReaderNotFound();
80 }
81 return reader;
82 }
83
84 protected abstract MessageBodyReader resolveReader(MediaType mediaType);
85
86 abstract protected void throwReaderNotFound();
87
88 @Override
89 public InputStream getInputStream()
90 {
91 return inputStream;
92 }
93
94 @Override
95 public void setInputStream(InputStream is)
96 {
97 this.inputStream = is;
98 }
99
100 @Override
101 public MultivaluedMap<String, String> getHeaders()
102 {
103 return headers;
104 }
105
106 @Override
107 public Annotation[] getAnnotations()
108 {
109 return annotations;
110 }
111
112 @Override
113 public void setAnnotations(Annotation[] annotations)
114 {
115 if (annotations == null) throw new NullPointerException(Messages.MESSAGES.annotationsParamNull());
116 this.annotations = annotations;
117 }
118
119 @Override
120 public Class getType()
121 {
122 return type;
123 }
124
125 @Override
126 public void setType(Class type)
127 {
128 this.type = type;
129 }
130
131 @Override
132 public Type getGenericType()
133 {
134 return genericType;
135 }
136
137 @Override
138 public void setGenericType(Type genericType)
139 {
140 this.genericType = genericType;
141 }
142
143 @Override
144 public MediaType getMediaType()
145 {
146 return mediaType;
147 }
148
149 @Override
150 public void setMediaType(MediaType mediaType)
151 {
152 this.mediaType = mediaType;
153 }
154 }
+0
-155
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/AbstractWriterInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyWriter;
10 import javax.ws.rs.ext.WriterInterceptor;
11 import javax.ws.rs.ext.WriterInterceptorContext;
12
13 import java.io.IOException;
14 import java.io.OutputStream;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17
18 /**
19 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
20 * @version $Revision: 1 $
21 */
22 public abstract class AbstractWriterInterceptorContext implements WriterInterceptorContext
23 {
24 protected WriterInterceptor[] interceptors;
25 protected Object entity;
26 protected Class type;
27 protected Type genericType;
28 protected Annotation[] annotations;
29 protected MediaType mediaType;
30 protected MultivaluedMap<String, Object> headers;
31 protected OutputStream outputStream;
32 protected int index = 0;
33 protected ResteasyProviderFactory providerFactory;
34
35 public AbstractWriterInterceptorContext(WriterInterceptor[] interceptors, Annotation[] annotations, Object entity, Type genericType, MediaType mediaType, Class type, OutputStream outputStream, ResteasyProviderFactory providerFactory, MultivaluedMap<String, Object> headers)
36 {
37 this.providerFactory = providerFactory;
38 this.interceptors = interceptors;
39 this.annotations = annotations;
40 this.entity = entity;
41 this.genericType = genericType;
42 this.mediaType = mediaType;
43 this.type = type;
44 this.outputStream = outputStream;
45 this.headers = headers;
46 }
47
48 public Object getEntity()
49 {
50 return entity;
51 }
52
53 public void setEntity(Object entity)
54 {
55 this.entity = entity;
56 }
57
58 public Class getType()
59 {
60 return type;
61 }
62
63 public void setType(Class type)
64 {
65 this.type = type;
66 }
67
68 public Type getGenericType()
69 {
70 return genericType;
71 }
72
73 public void setGenericType(Type genericType)
74 {
75 this.genericType = genericType;
76 }
77
78 public Annotation[] getAnnotations()
79 {
80 return annotations;
81 }
82
83 public void setAnnotations(Annotation[] annotations)
84 {
85 if (annotations == null) throw new NullPointerException(Messages.MESSAGES.annotationsParamNull());
86 this.annotations = annotations;
87 }
88
89 public MediaType getMediaType()
90 {
91 return mediaType;
92 }
93
94 public void setMediaType(MediaType mediaType)
95 {
96 this.mediaType = mediaType;
97 }
98
99 public MultivaluedMap<String, Object> getHeaders()
100 {
101 return headers;
102 }
103
104 public OutputStream getOutputStream()
105 {
106 return outputStream;
107 }
108
109 public void setOutputStream(OutputStream outputStream)
110 {
111 this.outputStream = outputStream;
112 }
113
114 public void proceed() throws IOException, WebApplicationException
115 {
116 LogMessages.LOGGER.debugf("Interceptor Context: %s, Method : proceed", getClass().getName());
117
118 if (interceptors == null || index >= interceptors.length)
119 {
120 MessageBodyWriter writer = getWriter();
121 if (writer!=null)
122 LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName());
123 writeTo(writer);
124 }
125 else
126 {
127 LogMessages.LOGGER.debugf("WriterInterceptor: %s", interceptors[index].getClass().getName());
128 interceptors[index++].aroundWriteTo(this);
129 // we used to pop the index, but the TCK doesn't like this
130 }
131 }
132
133 @SuppressWarnings(value = "unchecked")
134 protected void writeTo(MessageBodyWriter writer) throws IOException
135 {
136 writer.writeTo(entity, type, genericType, annotations, mediaType, headers, outputStream);
137 }
138
139 protected MessageBodyWriter getWriter()
140 {
141 MessageBodyWriter writer = resolveWriter();
142
143 if (writer == null)
144 {
145 throwWriterNotFoundException();
146 }
147 return writer;
148
149 }
150
151 abstract protected MessageBodyWriter resolveWriter();
152
153 abstract void throwWriterNotFoundException();
154 }
+0
-83
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ClientReaderInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.NotSupportedException;
6 import javax.ws.rs.ProcessingException;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyReader;
10 import javax.ws.rs.ext.ReaderInterceptor;
11
12 import java.io.InputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.Type;
15 import java.util.Collection;
16 import java.util.Enumeration;
17 import java.util.Iterator;
18 import java.util.Map;
19
20 import static java.lang.String.format;
21
22 /**
23 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
24 * @version $Revision: 1 $
25 */
26 public class ClientReaderInterceptorContext extends AbstractReaderInterceptorContext
27 {
28 protected Map<String, Object> properties;
29
30 public ClientReaderInterceptorContext(ReaderInterceptor[] interceptors, ResteasyProviderFactory providerFactory, Class type,
31 Type genericType, Annotation[] annotations, MediaType mediaType,
32 MultivaluedMap<String, String> headers, InputStream inputStream,
33 Map<String, Object> properties)
34 {
35 super(mediaType, providerFactory, annotations, interceptors, headers, genericType, type, inputStream);
36 this.properties = properties;
37 }
38
39 protected void throwReaderNotFound()
40 {
41 throw new ProcessingException(Messages.MESSAGES.clientResponseFailureMediaType(mediaType, type));
42 }
43
44 @SuppressWarnings(value = "unchecked")
45 @Override
46 protected MessageBodyReader resolveReader(MediaType mediaType)
47 {
48 return providerFactory.getClientMessageBodyReader(type,
49 genericType, annotations, mediaType);
50 }
51
52 @Override
53 public Object getProperty(String name)
54 {
55 return properties.get(name);
56 }
57
58 @Override
59 public Collection<String> getPropertyNames()
60 {
61 return properties.keySet();
62 }
63
64 @Override
65 public void setProperty(String name, Object object)
66 {
67 if (object == null)
68 {
69 properties.remove(name);
70 }
71 else
72 {
73 properties.put(name, object);
74 }
75 }
76
77 @Override
78 public void removeProperty(String name)
79 {
80 properties.remove(name);
81 }
82 }
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import javax.ws.rs.client.ClientRequestFilter;
6 import javax.ws.rs.container.PreMatching;
7 import java.util.logging.Logger;
8
9 /**
10 * Created by rsearls on 8/4/17.
11 */
12 public class ClientRequestFilterRegistry extends JaxrsInterceptorRegistry<ClientRequestFilter> {
13
14 //private static final Logger LOGGER = Logger.getLogger(ClientRequestFilterRegistry.class.getName());
15
16 public ClientRequestFilterRegistry(ResteasyProviderFactory providerFactory)
17 {
18 super(providerFactory, ClientRequestFilter.class);
19 }
20
21 @Override
22 public synchronized void registerClass(Class<? extends ClientRequestFilter> declaring)
23 {
24 checkPreMaching(declaring);
25 OnDemandInterceptorFactory factory = new OnDemandInterceptorFactory(declaring)
26 {
27 @Override
28 public Match preMatch()
29 {
30 return null;
31 }
32 };
33 factory.setIgnorePrematch(true);
34 register(factory);
35 }
36
37 @Override
38 public synchronized void registerClass(Class<? extends ClientRequestFilter> declaring, int priority)
39 {
40 checkPreMaching(declaring);
41 OnDemandInterceptorFactory factory = new OnDemandInterceptorFactory(declaring)
42 {
43 @Override
44 public Match preMatch()
45 {
46 return null;
47 }
48 };
49 factory.setIgnorePrematch(true);
50 factory.setOrder(priority);
51 register(factory);
52 }
53
54 private void checkPreMaching(Class declaring) {
55 if (declaring.isAnnotationPresent(PreMatching.class)) {
56 LogMessages.LOGGER.warningPreMatchingSupport(declaring.getName());
57 }
58 }
59
60 @Override
61 public ClientRequestFilterRegistry clone(ResteasyProviderFactory factory)
62 {
63 ClientRequestFilterRegistry clone = new ClientRequestFilterRegistry(factory);
64 clone.interceptors.addAll(interceptors);
65 return clone;
66 }
67 }
+0
-34
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ClientResponseFilterRegistry.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3
4 import javax.ws.rs.client.ClientResponseFilter;
5 import java.util.Collections;
6 import java.util.List;
7
8 /**
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @version $Revision: 1 $
11 */
12 public class ClientResponseFilterRegistry extends JaxrsInterceptorRegistry<ClientResponseFilter>
13 {
14 public ClientResponseFilterRegistry(ResteasyProviderFactory providerFactory)
15 {
16 super(providerFactory, ClientResponseFilter.class);
17 }
18
19 @Override
20 protected void sort(List<Match> matches)
21 {
22 Collections.sort(matches, new DescendingPrecedenceComparator());
23
24 }
25
26 @Override
27 public ClientResponseFilterRegistry clone(ResteasyProviderFactory factory)
28 {
29 ClientResponseFilterRegistry clone = new ClientResponseFilterRegistry(factory);
30 clone.interceptors.addAll(interceptors);
31 return clone;
32 }
33 }
+0
-83
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ClientWriterInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.ProcessingException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.WriterInterceptor;
10
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14 import java.util.Collection;
15 import java.util.Enumeration;
16 import java.util.Iterator;
17 import java.util.Map;
18
19 /**
20 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
21 * @version $Revision: 1 $
22 */
23 public class ClientWriterInterceptorContext extends AbstractWriterInterceptorContext
24 {
25 protected Map<String, Object> properties;
26
27 public ClientWriterInterceptorContext(WriterInterceptor[] interceptors, ResteasyProviderFactory providerFactory,
28 Object entity, Class type, Type genericType, Annotation[] annotations,
29 MediaType mediaType, MultivaluedMap<String, Object> headers,
30 OutputStream outputStream, Map<String, Object> properties)
31 {
32 super(interceptors, annotations, entity, genericType, mediaType, type, outputStream, providerFactory, headers);
33 this.properties = properties;
34 }
35
36 @Override
37 void throwWriterNotFoundException()
38 {
39 throw new ProcessingException(Messages.MESSAGES.couldNotFindWriterForContentType(mediaType, type.getName()));
40 }
41
42 @Override
43 protected MessageBodyWriter resolveWriter()
44 {
45 @SuppressWarnings(value = "unchecked")
46 MessageBodyWriter writer = providerFactory.getClientMessageBodyWriter(
47 type, genericType, annotations, mediaType);
48 //logger.info("********* WRITER: " + writer.getClass().getName());
49 return writer;
50 }
51
52 @Override
53 public Object getProperty(String name)
54 {
55 return properties.get(name);
56 }
57
58 @Override
59 public Collection<String> getPropertyNames()
60 {
61 return properties.keySet();
62 }
63
64 @Override
65 public void setProperty(String name, Object object)
66 {
67 if (object == null)
68 {
69 properties.remove(name);
70 }
71 else
72 {
73 properties.put(name, object);
74 }
75 }
76
77 @Override
78 public void removeProperty(String name)
79 {
80 properties.remove(name);
81 }
82 }
+0
-32
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ContainerRequestFilterRegistry.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import java.lang.reflect.AccessibleObject;
3
4 import javax.ws.rs.container.ContainerRequestFilter;
5
6 import org.jboss.resteasy.spi.ResteasyProviderFactory;
7
8 /**
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @version $Revision: 1 $
11 */
12 public class ContainerRequestFilterRegistry extends JaxrsInterceptorRegistry<ContainerRequestFilter>
13 {
14 public ContainerRequestFilterRegistry(ResteasyProviderFactory providerFactory)
15 {
16 super(providerFactory, ContainerRequestFilter.class);
17 }
18
19 public ContainerRequestFilterRegistry clone(ResteasyProviderFactory factory)
20 {
21 ContainerRequestFilterRegistry clone = new ContainerRequestFilterRegistry(factory);
22 clone.interceptors.addAll(interceptors);
23 return clone;
24 }
25
26 @Override
27 public ContainerRequestFilter[] postMatch(Class declaring, AccessibleObject target)
28 {
29 return super.postMatch(declaring, target);
30 }
31 }
+0
-248
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ContainerResponseContextImpl.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.specimpl.BuiltResponse;
3 import org.jboss.resteasy.spi.HttpRequest;
4 import org.jboss.resteasy.spi.HttpResponse;
5
6 import javax.ws.rs.container.ContainerResponseContext;
7 import javax.ws.rs.core.EntityTag;
8 import javax.ws.rs.core.HttpHeaders;
9 import javax.ws.rs.core.Link;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.MultivaluedMap;
12 import javax.ws.rs.core.NewCookie;
13 import javax.ws.rs.core.Response;
14 import java.io.IOException;
15 import java.io.OutputStream;
16 import java.lang.annotation.Annotation;
17 import java.lang.reflect.Type;
18 import java.net.URI;
19 import java.util.Date;
20 import java.util.Locale;
21 import java.util.Map;
22 import java.util.Set;
23
24 /**
25 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
26 * @version $Revision: 1 $
27 */
28 public class ContainerResponseContextImpl implements ContainerResponseContext
29 {
30 protected final HttpRequest request;
31 protected final HttpResponse httpResponse;
32 protected final BuiltResponse jaxrsResponse;
33
34 public ContainerResponseContextImpl(HttpRequest request, HttpResponse httpResponse, BuiltResponse serverResponse)
35 {
36 this.request = request;
37 this.httpResponse = httpResponse;
38 this.jaxrsResponse = serverResponse;
39 }
40
41 public BuiltResponse getJaxrsResponse()
42 {
43 return jaxrsResponse;
44 }
45
46 public HttpResponse getHttpResponse()
47 {
48 return httpResponse;
49 }
50
51 @Override
52 public int getStatus()
53 {
54 return jaxrsResponse.getStatus();
55 }
56
57 @Override
58 public void setStatus(int code)
59 {
60 httpResponse.setStatus(code);
61 jaxrsResponse.setStatus(code);
62 }
63
64 @Override
65 public Response.StatusType getStatusInfo()
66 {
67 return jaxrsResponse.getStatusInfo();
68 }
69
70 @Override
71 public void setStatusInfo(Response.StatusType statusInfo)
72 {
73 httpResponse.setStatus(statusInfo.getStatusCode());
74 jaxrsResponse.setStatus(statusInfo.getStatusCode());
75 }
76
77 @Override
78 public Class<?> getEntityClass()
79 {
80 return jaxrsResponse.getEntityClass();
81 }
82
83 @Override
84 public Type getEntityType()
85 {
86 return jaxrsResponse.getGenericType();
87 }
88
89 @Override
90 public void setEntity(Object entity)
91 {
92 //if (entity != null) logger.info("*** setEntity(Object) " + entity.toString());
93 jaxrsResponse.setEntity(entity);
94 // todo TCK does weird things in its testing of get length
95 // it resets the entity in a response filter which results
96 // in a bad content-length being sent back to the client
97 // so, we'll remove any content-length setting
98 getHeaders().remove(HttpHeaders.CONTENT_LENGTH);
99 }
100
101 @Override
102 public void setEntity(Object entity, Annotation[] annotations, MediaType mediaType)
103 {
104 //if (entity != null) logger.info("*** setEntity(Object, Annotation[], MediaType) " + entity.toString() + ", " + mediaType);
105 jaxrsResponse.setEntity(entity);
106 jaxrsResponse.setAnnotations(annotations);
107 jaxrsResponse.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType);
108 // todo TCK does weird things in its testing of get length
109 // it resets the entity in a response filter which results
110 // in a bad content-length being sent back to the client
111 // so, we'll remove any content-length setting
112 getHeaders().remove(HttpHeaders.CONTENT_LENGTH);
113 }
114
115 @Override
116 public MultivaluedMap<String, Object> getHeaders()
117 {
118 return jaxrsResponse.getMetadata();
119 }
120
121 @Override
122 public Set<String> getAllowedMethods()
123 {
124 return jaxrsResponse.getAllowedMethods();
125 }
126
127 @Override
128 public Date getDate()
129 {
130 return jaxrsResponse.getDate();
131 }
132
133 @Override
134 public Locale getLanguage()
135 {
136 return jaxrsResponse.getLanguage();
137 }
138
139 @Override
140 public int getLength()
141 {
142 return jaxrsResponse.getLength();
143 }
144
145 @Override
146 public MediaType getMediaType()
147 {
148 return jaxrsResponse.getMediaType();
149 }
150
151 @Override
152 public Map<String, NewCookie> getCookies()
153 {
154 return jaxrsResponse.getCookies();
155 }
156
157 @Override
158 public EntityTag getEntityTag()
159 {
160 return jaxrsResponse.getEntityTag();
161 }
162
163 @Override
164 public Date getLastModified()
165 {
166 return jaxrsResponse.getLastModified();
167 }
168
169 @Override
170 public URI getLocation()
171 {
172 return jaxrsResponse.getLocation();
173 }
174
175 @Override
176 public Set<Link> getLinks()
177 {
178 return jaxrsResponse.getLinks();
179 }
180
181 @Override
182 public boolean hasLink(String relation)
183 {
184 return jaxrsResponse.hasLink(relation);
185 }
186
187 @Override
188 public Link getLink(String relation)
189 {
190 return jaxrsResponse.getLink(relation);
191 }
192
193 @Override
194 public Link.Builder getLinkBuilder(String relation)
195 {
196 return jaxrsResponse.getLinkBuilder(relation);
197 }
198
199 @Override
200 public boolean hasEntity()
201 {
202 return jaxrsResponse.hasEntity();
203 }
204
205 @Override
206 public Object getEntity()
207 {
208 return jaxrsResponse.getEntity();
209 }
210
211 @Override
212 public OutputStream getEntityStream()
213 {
214 try
215 {
216 return httpResponse.getOutputStream();
217 }
218 catch (IOException e)
219 {
220 throw new RuntimeException(e);
221 }
222 }
223
224 @Override
225 public void setEntityStream(OutputStream entityStream)
226 {
227 httpResponse.setOutputStream(entityStream);
228 }
229
230 @Override
231 public Annotation[] getEntityAnnotations()
232 {
233 return jaxrsResponse.getAnnotations();
234 }
235
236 @Override
237 public MultivaluedMap<String, String> getStringHeaders()
238 {
239 return jaxrsResponse.getStringHeaders();
240 }
241
242 @Override
243 public String getHeaderString(String name)
244 {
245 return jaxrsResponse.getHeaderString(name);
246 }
247 }
+0
-68
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ContainerResponseFilterRegistry.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import java.util.Collections;
3 import java.util.List;
4
5 import javax.ws.rs.container.ContainerResponseFilter;
6
7 import org.jboss.resteasy.spi.ResteasyProviderFactory;
8
9 /**
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 public class ContainerResponseFilterRegistry extends JaxrsInterceptorRegistry<ContainerResponseFilter>
14 {
15 public ContainerResponseFilterRegistry(ResteasyProviderFactory providerFactory)
16 {
17 super(providerFactory, ContainerResponseFilter.class);
18 }
19
20 @Override
21 protected void sort(List<Match> matches)
22 {
23 Collections.sort(matches, new DescendingPrecedenceComparator());
24
25 }
26
27 public ContainerResponseFilterRegistry clone(ResteasyProviderFactory factory)
28 {
29 ContainerResponseFilterRegistry clone = new ContainerResponseFilterRegistry(factory);
30 clone.interceptors.addAll(interceptors);
31 return clone;
32 }
33
34 @Override
35 public synchronized void registerClass(Class<? extends ContainerResponseFilter> declaring)
36 {
37 OnDemandInterceptorFactory factory = new OnDemandInterceptorFactory(declaring);
38 factory.setIgnorePrematch(true);
39 register(factory);
40 }
41
42 @Override
43 public synchronized void registerClass(Class<? extends ContainerResponseFilter> declaring, int priority)
44 {
45 OnDemandInterceptorFactory factory = new OnDemandInterceptorFactory(declaring);
46 factory.setIgnorePrematch(true);
47 factory.setOrder(priority);
48 register(factory);
49 }
50
51 @Override
52 public synchronized void registerSingleton(ContainerResponseFilter interceptor)
53 {
54 SingletonInterceptorFactory factory = new SingletonInterceptorFactory(interceptor.getClass(), interceptor);
55 factory.setIgnorePrematch(true);
56 register(factory);
57 }
58
59 @Override
60 public synchronized void registerSingleton(ContainerResponseFilter interceptor, int priority)
61 {
62 SingletonInterceptorFactory factory = new SingletonInterceptorFactory(interceptor.getClass(), interceptor);
63 factory.setIgnorePrematch(true);
64 factory.setOrder(priority);
65 register(factory);
66 }
67 }
+0
-98
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/DecoratorMatcher.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.annotations.DecorateTypes;
3 import org.jboss.resteasy.annotations.Decorator;
4 import org.jboss.resteasy.core.MediaTypeMap;
5 import org.jboss.resteasy.spi.DecoratorProcessor;
6
7 import javax.ws.rs.core.MediaType;
8 import java.lang.annotation.Annotation;
9 import java.util.HashMap;
10 import java.util.List;
11
12 /**
13 * Finds DecoratorProcessors and calls decorates on them by introspecting annotations.
14 *
15 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
16 * @version $Revision: 1 $
17 * @see org.jboss.resteasy.spi.DecoratorProcessor
18 * @see org.jboss.resteasy.annotations.DecorateTypes
19 * @see org.jboss.resteasy.annotations.Decorator
20 */
21 public class DecoratorMatcher
22 {
23 /**
24 * @param targetClass i.e. Marshaller
25 * @param target
26 * @param type i.e. a JAXB annotated class
27 * @param annotations i.e. method or parameter annotations
28 * @param mediaType
29 * @param <T>
30 * @return
31 */
32 @SuppressWarnings(value = "unchecked")
33 public <T> T decorate(Class<T> targetClass, T target, Class type, Annotation[] annotations, MediaType mediaType)
34 {
35 HashMap<Class<?>, Annotation> meta = new HashMap<Class<?>, Annotation>();
36 if (type != null)
37 {
38 registerDecorators(targetClass, meta, type.getAnnotations());
39 }
40 // override any class level ones
41 if (annotations != null)
42 {
43 registerDecorators(targetClass, meta, annotations);
44 }
45 if (meta.size() == 0) return target;
46
47 MediaTypeMap<Class<?>> typeMap = new MediaTypeMap<Class<?>>();
48 for (Class<?> decoratorAnnotation : meta.keySet())
49 {
50 Decorator decorator = decoratorAnnotation.getAnnotation(Decorator.class);
51 String[] mediaTypes = {"*/*"};
52 DecorateTypes produces = decorator.processor().getAnnotation(DecorateTypes.class);
53 if (produces != null)
54 {
55 mediaTypes = produces.value();
56 }
57 for (String pType : mediaTypes)
58 {
59 typeMap.add(MediaType.valueOf(pType), decoratorAnnotation);
60 }
61 }
62
63 List<Class<?>> list = typeMap.getPossible(mediaType);
64 for (Class<?> decoratorAnnotation : list)
65 {
66 Annotation annotation = meta.get(decoratorAnnotation);
67 Decorator decorator = decoratorAnnotation.getAnnotation(Decorator.class);
68 DecoratorProcessor processor = null;
69 try
70 {
71 processor = decorator.processor().newInstance();
72 }
73 catch (InstantiationException e)
74 {
75 throw new RuntimeException(e.getCause());
76 }
77 catch (IllegalAccessException e)
78 {
79 throw new RuntimeException(e);
80 }
81 target = (T) processor.decorate(target, annotation, type, annotations, mediaType);
82 }
83
84 return target;
85 }
86
87 private <T> void registerDecorators(Class<T> targetClass, HashMap<Class<?>, Annotation> meta, Annotation[] annotations) {
88 for (Annotation annotation : annotations)
89 {
90 Decorator decorator = annotation.annotationType().getAnnotation(Decorator.class);
91 if (decorator != null && targetClass.isAssignableFrom(decorator.target()))
92 {
93 meta.put(annotation.annotationType(), annotation);
94 }
95 }
96 }
97 }
+0
-386
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/JaxrsInterceptorRegistry.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.annotation.Priority;
6 import javax.ws.rs.NameBinding;
7 import javax.ws.rs.Priorities;
8 import javax.ws.rs.container.PreMatching;
9 import javax.ws.rs.core.Application;
10
11 import java.lang.annotation.Annotation;
12 import java.lang.reflect.AccessibleObject;
13 import java.lang.reflect.Array;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.Comparator;
17 import java.util.List;
18 import java.util.concurrent.CopyOnWriteArrayList;
19
20 /**
21 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
22 * @version $Revision: 1 $
23 */
24 @SuppressWarnings("unchecked")
25 public class JaxrsInterceptorRegistry<T>
26 {
27 public static class Match
28 {
29 public Match(Object interceptor, int order)
30 {
31 this.interceptor = interceptor;
32 this.order = order;
33 }
34
35 final public Object interceptor;
36 final public int order;
37 }
38
39 public static interface InterceptorFactory
40 {
41 Match preMatch();
42
43 Match postMatch(Class declaring, AccessibleObject target);
44 }
45
46 protected static List<Class<? extends Annotation>> getNameBound(Class<?> declaring)
47 {
48 List<Class<? extends Annotation>> nameBound = new ArrayList<Class<? extends Annotation>>();
49 for (Annotation annotation : declaring.getAnnotations())
50 {
51 if (annotation.annotationType().isAnnotationPresent(NameBinding.class))
52 {
53 nameBound.add(annotation.annotationType());
54 }
55 }
56 return nameBound;
57 }
58
59 public static int getPriority(Class<?> declaring)
60 {
61 Priority priority = (Priority) declaring.getAnnotation(Priority.class);
62 if (priority != null) return priority.value();
63 return Priorities.USER;
64 }
65
66 public abstract class AbstractInterceptorFactory implements InterceptorFactory
67 {
68 protected final Class declaring;
69 protected int order = Priorities.USER;
70 protected List<Class<? extends Annotation>> nameBound;
71 protected volatile boolean initialized;
72 protected boolean ignorePrematch;
73
74 public AbstractInterceptorFactory(Class declaring)
75 {
76 this.declaring = declaring;
77 }
78
79 protected void setPrecedence(Class<?> declaring)
80 {
81 nameBound = getNameBound(declaring);
82 order = getPriority(declaring);
83 }
84
85 protected abstract void initialize();
86
87 protected abstract Object getInterceptor();
88
89 protected void checkInitialize()
90 {
91 boolean isInitialized = initialized;
92 if (!isInitialized)
93 {
94 synchronized (this)
95 {
96 isInitialized = initialized;
97 if (isInitialized) return;
98 isInitialized = initialized = true;
99 initialize();
100 }
101 }
102 }
103
104 public void setOrder(int order)
105 {
106 this.order = order;
107 }
108
109 public void setIgnorePrematch(boolean ignorePrematch)
110 {
111 this.ignorePrematch = ignorePrematch;
112 }
113
114 @Override
115 public Match preMatch()
116 {
117 if (declaring.isAnnotationPresent(PreMatching.class)) return new Match(getInterceptor(), order);
118 return null;
119 }
120
121 @Override
122 public Match postMatch(Class targetClass, AccessibleObject target)
123 {
124 if (!ignorePrematch && declaring.isAnnotationPresent(PreMatching.class)) return null;
125 if (targetClass != null && target != null)
126 {
127 if (nameBound.size() > 0)
128 {
129 Application application = ResteasyProviderFactory.getContextData(Application.class);
130 // must match all namebound annotations
131 for (Class<? extends Annotation> annotation : nameBound)
132 {
133 if (!targetClass.isAnnotationPresent(annotation) &&
134 !target.isAnnotationPresent(annotation)
135 && (application == null || !application.getClass().isAnnotationPresent(annotation)))
136 {
137 return null;
138 }
139 }
140 // we matched all of them
141 Object intercept = getInterceptor();
142 if (intercept == null)
143 throw new NullPointerException(Messages.MESSAGES.interceptorNullFromClass(this.getClass().getName()));
144 return new Match(intercept, order);
145 }
146 else
147 {
148 Object intercept = getInterceptor();
149 if (intercept == null)
150 throw new NullPointerException(Messages.MESSAGES.interceptorNullFromClass(this.getClass().getName()));
151 return new Match(intercept, order);
152 }
153 } else if (nameBound.size() == 0)
154 {
155 Object intercept = getInterceptor();
156 if (intercept == null)
157 throw new NullPointerException(Messages.MESSAGES.interceptorNullFromClass(this.getClass().getName()));
158 return new Match(intercept, order);
159 } else
160 {
161 return null;
162 }
163 }
164
165 protected Object createInterceptor()
166 {
167 return providerFactory.injectedInstance(declaring);
168 }
169 }
170
171
172 protected class OnDemandInterceptorFactory extends AbstractInterceptorFactory
173 {
174 protected volatile Object interceptor;
175
176 public OnDemandInterceptorFactory(Class declaring)
177 {
178 super(declaring);
179 setPrecedence(declaring);
180 }
181
182 @Override
183 protected void initialize()
184 {
185 interceptor = createInterceptor();
186 providerFactory.injectProperties(interceptor);
187 initialized = true;
188 }
189
190 protected void checkInitialize()
191 {
192 Object tmp = interceptor;
193 if (tmp == null)
194 {
195 synchronized (this)
196 {
197 tmp = interceptor;
198 if (tmp == null)
199 {
200 initialize();
201 tmp = interceptor;
202 }
203 }
204 }
205 }
206
207
208 @Override
209 protected Object getInterceptor()
210 {
211 checkInitialize();
212 return interceptor;
213 }
214 }
215
216 protected class SingletonInterceptorFactory extends AbstractInterceptorFactory
217 {
218 protected Object interceptor;
219
220 public SingletonInterceptorFactory(Class declaring, Object interceptor)
221 {
222 super(declaring);
223 this.interceptor = interceptor;
224 setPrecedence(declaring);
225 }
226
227 @Override
228 protected void initialize()
229 {
230 providerFactory.injectProperties(interceptor);
231 }
232
233 @Override
234 protected Object getInterceptor()
235 {
236 checkInitialize();
237 return interceptor;
238 }
239 }
240
241 protected List<InterceptorFactory> interceptors = new CopyOnWriteArrayList<InterceptorFactory>();
242 protected List<JaxrsInterceptorRegistryListener> listeners = new CopyOnWriteArrayList<JaxrsInterceptorRegistryListener>();
243 protected ResteasyProviderFactory providerFactory;
244 protected Class<T> intf;
245 protected volatile T[] cachedPreMatch;
246
247 public JaxrsInterceptorRegistry(ResteasyProviderFactory providerFactory, Class<T> intf)
248 {
249 this.providerFactory = providerFactory;
250 this.intf = intf;
251 }
252
253 public JaxrsInterceptorRegistry<T> clone(ResteasyProviderFactory factory)
254 {
255 JaxrsInterceptorRegistry<T> clone = new JaxrsInterceptorRegistry(factory, intf);
256 clone.interceptors.addAll(interceptors);
257 return clone;
258 }
259
260 public Class<T> getIntf()
261 {
262 return intf;
263 }
264
265 public static class AscendingPrecedenceComparator implements Comparator<Match>
266 {
267 public int compare(Match match, Match match2)
268 {
269 if (match.order < match2.order)
270 {
271 return -1;
272 }
273 if (match.order == match2.order)
274 {
275 return 0;
276 }
277 return 1;
278 }
279 }
280
281 public static class DescendingPrecedenceComparator implements Comparator<Match>
282 {
283 public int compare(Match match, Match match2)
284 {
285 if (match2.order < match.order)
286 {
287 return -1;
288 }
289 if (match2.order == match.order)
290 {
291 return 0;
292 }
293 return 1;
294 }
295 }
296
297
298 public List<JaxrsInterceptorRegistryListener> getListeners()
299 {
300 return listeners;
301 }
302
303 public T[] preMatch()
304 {
305 if (cachedPreMatch == null)
306 {
307 List<Match> matches = new ArrayList<Match>();
308 for (InterceptorFactory factory : interceptors)
309 {
310 Match match = factory.preMatch();
311 if (match != null)
312 {
313 matches.add(match);
314 }
315 }
316 cachedPreMatch = createArray(matches);
317 }
318 return cachedPreMatch;
319 }
320
321
322 public T[] postMatch(Class declaring, AccessibleObject target)
323 {
324 List<Match> matches = new ArrayList<Match>();
325 for (InterceptorFactory factory : interceptors)
326 {
327 Match match = factory.postMatch(declaring, target);
328 if (match != null)
329 {
330 matches.add(match);
331 }
332 }
333 return createArray(matches);
334 }
335
336 private T[] createArray(List<Match> matches)
337 {
338 sort(matches);
339 T[] array = (T[]) Array.newInstance(intf, matches.size());
340 for (int i = 0; i < array.length; i++)
341 {
342 array[i] = (T) matches.get(i).interceptor;
343 }
344 return array;
345 }
346
347 protected void sort(List<Match> matches)
348 {
349 Collections.sort(matches, new AscendingPrecedenceComparator());
350 }
351
352 public synchronized void register(InterceptorFactory factory)
353 {
354 interceptors.add(factory);
355 cachedPreMatch = null;
356 for (JaxrsInterceptorRegistryListener listener : listeners)
357 {
358 listener.registryUpdated(this);
359 }
360 }
361
362 public synchronized void registerClass(Class<? extends T> declaring)
363 {
364 register(new OnDemandInterceptorFactory(declaring));
365 }
366
367 public synchronized void registerClass(Class<? extends T> declaring, int priority)
368 {
369 OnDemandInterceptorFactory factory = new OnDemandInterceptorFactory(declaring);
370 factory.setOrder(priority);
371 register(factory);
372 }
373
374 public synchronized void registerSingleton(T interceptor)
375 {
376 register(new SingletonInterceptorFactory(interceptor.getClass(), interceptor));
377 }
378
379 public synchronized void registerSingleton(T interceptor, int priority)
380 {
381 SingletonInterceptorFactory factory = new SingletonInterceptorFactory(interceptor.getClass(), interceptor);
382 factory.setOrder(priority);
383 register(factory);
384 }
385 }
+0
-13
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/JaxrsInterceptorRegistryListener.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 /**
3 * Callback interface for when an interceptor registry changes
4 *
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 */
8 public interface JaxrsInterceptorRegistryListener
9 {
10 void registryUpdated(JaxrsInterceptorRegistry registry);
11
12 }
+0
-45
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/PostMatchContainerRequestContext.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.core.ResourceMethodInvoker;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
4 import org.jboss.resteasy.spi.HttpRequest;
5
6 import java.net.URI;
7
8 /**
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @version $Revision: 1 $
11 */
12 public class PostMatchContainerRequestContext extends PreMatchContainerRequestContext
13 {
14 protected final ResourceMethodInvoker resourceMethod;
15
16 public PostMatchContainerRequestContext(HttpRequest request,ResourceMethodInvoker resourceMethod)
17 {
18 super(request);
19 this.resourceMethod = resourceMethod;
20 }
21
22 public ResourceMethodInvoker getResourceMethod()
23 {
24 return resourceMethod;
25 }
26
27 @Override
28 public void setMethod(String method)
29 {
30 throw new IllegalStateException(Messages.MESSAGES.cantSetMethod());
31 }
32
33 @Override
34 public void setRequestUri(URI requestUri) throws IllegalStateException
35 {
36 throw new IllegalStateException(Messages.MESSAGES.cantSetURI());
37 }
38
39 @Override
40 public void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException
41 {
42 throw new IllegalStateException(Messages.MESSAGES.cantSetURI());
43 }
44 }
+0
-203
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/PreMatchContainerRequestContext.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.spi.HttpRequest;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.container.ContainerRequestContext;
6 import javax.ws.rs.core.Cookie;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.core.Request;
10 import javax.ws.rs.core.Response;
11 import javax.ws.rs.core.SecurityContext;
12 import javax.ws.rs.core.UriInfo;
13 import java.io.InputStream;
14 import java.net.URI;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Date;
18 import java.util.Enumeration;
19 import java.util.List;
20 import java.util.Locale;
21 import java.util.Map;
22
23 /**
24 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
25 * @version $Revision: 1 $
26 */
27 public class PreMatchContainerRequestContext implements ContainerRequestContext
28 {
29 protected final HttpRequest httpRequest;
30 protected Response response;
31
32 public PreMatchContainerRequestContext(HttpRequest request)
33 {
34 this.httpRequest = request;
35 }
36
37 public HttpRequest getHttpRequest()
38 {
39 return httpRequest;
40 }
41
42 public Response getResponseAbortedWith()
43 {
44 return response;
45 }
46
47 @Override
48 public Object getProperty(String name)
49 {
50 return httpRequest.getAttribute(name);
51 }
52
53 @Override
54 public Collection<String> getPropertyNames()
55 {
56 ArrayList<String> names = new ArrayList<String>();
57 Enumeration<String> enames = httpRequest.getAttributeNames();
58 while (enames.hasMoreElements())
59 {
60 names.add(enames.nextElement());
61 }
62 return names;
63 }
64
65 @Override
66 public void setProperty(String name, Object object)
67 {
68 httpRequest.setAttribute(name, object);
69 }
70
71 @Override
72 public void removeProperty(String name)
73 {
74 httpRequest.removeAttribute(name);
75 }
76
77 @Override
78 public UriInfo getUriInfo()
79 {
80 return httpRequest.getUri();
81 }
82
83 @Override
84 public void setRequestUri(URI requestUri) throws IllegalStateException
85 {
86 httpRequest.setRequestUri(requestUri);
87 }
88
89 @Override
90 public void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException
91 {
92 httpRequest.setRequestUri(baseUri, requestUri);
93 }
94
95 @Override
96 public String getMethod()
97 {
98 return httpRequest.getHttpMethod();
99 }
100
101 @Override
102 public void setMethod(String method)
103 {
104 httpRequest.setHttpMethod(method);
105 }
106
107 @Override
108 public MultivaluedMap<String, String> getHeaders()
109 {
110 return httpRequest.getHttpHeaders().getRequestHeaders();
111 }
112
113 @Override
114 public Date getDate()
115 {
116 return httpRequest.getHttpHeaders().getDate();
117 }
118
119 @Override
120 public Locale getLanguage()
121 {
122 return httpRequest.getHttpHeaders().getLanguage();
123 }
124
125 @Override
126 public int getLength()
127 {
128 return httpRequest.getHttpHeaders().getLength();
129 }
130
131 @Override
132 public MediaType getMediaType()
133 {
134 return httpRequest.getHttpHeaders().getMediaType();
135 }
136
137 @Override
138 public List<MediaType> getAcceptableMediaTypes()
139 {
140 return httpRequest.getHttpHeaders().getAcceptableMediaTypes();
141 }
142
143 @Override
144 public List<Locale> getAcceptableLanguages()
145 {
146 return httpRequest.getHttpHeaders().getAcceptableLanguages();
147 }
148
149 @Override
150 public Map<String, Cookie> getCookies()
151 {
152 return httpRequest.getHttpHeaders().getCookies();
153 }
154
155 @Override
156 public boolean hasEntity()
157 {
158 return getMediaType() != null;
159 }
160
161 @Override
162 public InputStream getEntityStream()
163 {
164 return httpRequest.getInputStream();
165 }
166
167 @Override
168 public void setEntityStream(InputStream entityStream)
169 {
170 httpRequest.setInputStream(entityStream);
171 }
172
173 @Override
174 public SecurityContext getSecurityContext()
175 {
176 return ResteasyProviderFactory.getContextData(SecurityContext.class);
177 }
178
179 @Override
180 public void setSecurityContext(SecurityContext context)
181 {
182 ResteasyProviderFactory.pushContext(SecurityContext.class, context);
183 }
184
185 @Override
186 public Request getRequest()
187 {
188 return ResteasyProviderFactory.getContextData(Request.class);
189 }
190
191 @Override
192 public void abortWith(Response response)
193 {
194 this.response = response;
195 }
196
197 @Override
198 public String getHeaderString(String name)
199 {
200 return httpRequest.getHttpHeaders().getHeaderString(name);
201 }
202 }
+0
-24
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ReaderInterceptorRegistry.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import javax.ws.rs.ext.ReaderInterceptor;
3
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class ReaderInterceptorRegistry extends JaxrsInterceptorRegistry<ReaderInterceptor>
11 {
12 public ReaderInterceptorRegistry(ResteasyProviderFactory providerFactory)
13 {
14 super(providerFactory, ReaderInterceptor.class);
15 }
16
17 public ReaderInterceptorRegistry clone(ResteasyProviderFactory factory)
18 {
19 ReaderInterceptorRegistry clone = new ReaderInterceptorRegistry(factory);
20 clone.interceptors.addAll(interceptors);
21 return clone;
22 }
23 }
+0
-60
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ResponseContainerRequestContext.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.spi.HttpRequest;
4
5 import javax.ws.rs.core.Response;
6 import javax.ws.rs.core.SecurityContext;
7
8 import java.io.InputStream;
9 import java.net.URI;
10
11 /**
12 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
13 * @version $Revision: 1 $
14 */
15 public class ResponseContainerRequestContext extends PreMatchContainerRequestContext
16 {
17 public ResponseContainerRequestContext(HttpRequest request)
18 {
19 super(request);
20 }
21
22
23
24 @Override
25 public void abortWith(Response response)
26 {
27 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
28 }
29
30 @Override
31 public void setSecurityContext(SecurityContext context)
32 {
33 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
34 }
35
36 @Override
37 public void setEntityStream(InputStream entityStream)
38 {
39 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
40 }
41
42 @Override
43 public void setMethod(String method)
44 {
45 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
46 }
47
48 @Override
49 public void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException
50 {
51 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
52 }
53
54 @Override
55 public void setRequestUri(URI requestUri) throws IllegalStateException
56 {
57 throw new IllegalStateException(Messages.MESSAGES.requestWasAlreadyExecuted());
58 }
59 }
+0
-105
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ServerReaderInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.spi.HttpRequest;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import javax.ws.rs.BadRequestException;
7 import javax.ws.rs.NotSupportedException;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.MultivaluedMap;
10 import javax.ws.rs.core.NoContentException;
11 import javax.ws.rs.ext.MessageBodyReader;
12 import javax.ws.rs.ext.ReaderInterceptor;
13
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.lang.annotation.Annotation;
17 import java.lang.reflect.Type;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Enumeration;
21
22 /**
23 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
24 * @version $Revision: 1 $
25 */
26 public class ServerReaderInterceptorContext extends AbstractReaderInterceptorContext
27 {
28 private HttpRequest request;
29
30 public ServerReaderInterceptorContext(ReaderInterceptor[] interceptors, ResteasyProviderFactory providerFactory, Class type,
31 Type genericType, Annotation[] annotations, MediaType mediaType,
32 MultivaluedMap<String, String> headers, InputStream inputStream,
33 HttpRequest request)
34 {
35 super(mediaType, providerFactory, annotations, interceptors, headers, genericType, type, inputStream);
36 this.request = request;
37 }
38
39 @Override
40 protected MessageBodyReader resolveReader(MediaType mediaType)
41 {
42 @SuppressWarnings(value = "unchecked")
43 MessageBodyReader reader = providerFactory.getServerMessageBodyReader(type,
44 genericType, annotations, mediaType);
45 //logger.info("**** picked reader: " + reader.getClass().getName());
46 return reader;
47 }
48
49 @Override
50 protected void throwReaderNotFound()
51 {
52 throw new NotSupportedException(Messages.MESSAGES.couldNotFindMessageBodyReader(genericType, mediaType));
53 }
54
55 @Override
56 protected Object readFrom(MessageBodyReader reader) throws IOException
57 {
58 try
59 {
60 return super.readFrom(reader);
61 }
62 catch (NoContentException e)
63 {
64 throw new BadRequestException(e);
65 }
66 }
67
68 @Override
69 public Object getProperty(String name)
70 {
71 return request.getAttribute(name);
72 }
73
74 @Override
75 public Collection<String> getPropertyNames()
76 {
77 ArrayList<String> names = new ArrayList<String>();
78 Enumeration<String> enames = request.getAttributeNames();
79 while (enames.hasMoreElements())
80 {
81 names.add(enames.nextElement());
82 }
83 return names;
84 }
85
86 @Override
87 public void setProperty(String name, Object object)
88 {
89 if (object == null)
90 {
91 request.removeAttribute(name);
92 }
93 else
94 {
95 request.setAttribute(name, object);
96 }
97 }
98
99 @Override
100 public void removeProperty(String name)
101 {
102 request.removeAttribute(name);
103 }
104 }
+0
-94
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/ServerWriterInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure;
3 import org.jboss.resteasy.spi.HttpRequest;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.WriterInterceptor;
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Enumeration;
17
18 /**
19 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
20 * @version $Revision: 1 $
21 */
22 public class ServerWriterInterceptorContext extends AbstractWriterInterceptorContext
23 {
24 private HttpRequest request;
25
26 public ServerWriterInterceptorContext(WriterInterceptor[] interceptors, ResteasyProviderFactory providerFactory,
27 Object entity, Class type, Type genericType, Annotation[] annotations,
28 MediaType mediaType, MultivaluedMap<String, Object> headers,
29 OutputStream outputStream,
30 HttpRequest request)
31 {
32 super(interceptors, annotations, entity, genericType, mediaType, type, outputStream, providerFactory, headers);
33 this.request = request;
34 }
35
36 @SuppressWarnings(value = "unchecked")
37 @Override
38 protected MessageBodyWriter resolveWriter()
39 {
40 return providerFactory.getServerMessageBodyWriter(
41 type, genericType, annotations, mediaType);
42
43 }
44 @Override
45 void throwWriterNotFoundException()
46 {
47 throw new NoMessageBodyWriterFoundFailure(type, mediaType);
48 }
49
50 @Override
51 public Object getProperty(String name)
52 {
53 return request.getAttribute(name);
54 }
55
56 @Override
57 protected void writeTo(MessageBodyWriter writer) throws IOException
58 {
59 //logger.info("*** " + request.getUri().getPath() + " writeTo(" + entity.toString() + ", " + mediaType);
60 super.writeTo(writer);
61 }
62
63 @Override
64 public Collection<String> getPropertyNames()
65 {
66 ArrayList<String> names = new ArrayList<String>();
67 Enumeration<String> enames = request.getAttributeNames();
68 while (enames.hasMoreElements())
69 {
70 names.add(enames.nextElement());
71 }
72 return names;
73 }
74
75 @Override
76 public void setProperty(String name, Object object)
77 {
78 if (object == null)
79 {
80 request.removeAttribute(name);
81 }
82 else
83 {
84 request.setAttribute(name, object);
85 }
86 }
87
88 @Override
89 public void removeProperty(String name)
90 {
91 request.removeAttribute(name);
92 }
93 }
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import javax.ws.rs.container.ContainerRequestContext;
3
4 /**
5 * Suspendable request context, which allows the users to suspend execution of the filter
6 * chain until it is resumed normally, or abnormally with a @{link Response} or
7 * @{link Throwable}.
8 *
9 * @author Stéphane Épardaud <stef@epardaud.fr>
10 */
11 public interface SuspendableContainerRequestContext extends ContainerRequestContext
12 {
13 /**
14 * Suspends the current request. This makes the current request asynchronous. No
15 * further request filter is executed until this request is resumed.
16 *
17 * No reply is going to be sent to the client until this request is resumed either
18 * with {@link #resume()} or aborted with {@link #resume(Throwable)} or
19 * {@link #abortWith(javax.ws.rs.core.Response)}.
20 */
21 public void suspend();
22
23 /**
24 * Resumes the current request, and proceeds to the next request filter, if any,
25 * or to the resource method.
26 */
27 public void resume();
28
29 /**
30 * Aborts the current request with the given exception. This behaves as if the request
31 * filter threw this exception synchronously.
32 *
33 * @param t the exception to send back to the client, as mapped by the application.
34 */
35 public void resume(Throwable t);
36 }
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import javax.ws.rs.container.ContainerResponseContext;
3
4 /**
5 * Suspendable response context, which allows the users to suspend execution of the filter
6 * chain until it is resumed normally, or abnormally with a @{link Response} or
7 * @{link Throwable}.
8 *
9 * @author Stéphane Épardaud <stef@epardaud.fr>
10 */
11 public interface SuspendableContainerResponseContext extends ContainerResponseContext
12 {
13 /**
14 * Suspends the current response. This makes the current request asynchronous. No
15 * further response filter is executed until this response is resumed.
16 *
17 * No reply is going to be sent to the client until this response is resumed either
18 * with {@link #resume()} or aborted with {@link #resume(Throwable)} or
19 * {@link #abortWith(javax.ws.rs.core.Response)}.
20 */
21 public void suspend();
22
23 /**
24 * Resumes the current response, and proceeds to the next response filter, if any,
25 * or to send the response.
26 */
27 public void resume();
28
29 /**
30 * Aborts the current response with the given exception. This behaves as if the request
31 * filter threw this exception synchronously.
32 *
33 * @param t the exception to send back to the client, as mapped by the application.
34 */
35 public void resume(Throwable t);
36
37 }
+0
-24
resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/WriterInterceptorRegistry.java less more
0 package org.jboss.resteasy.core.interception.jaxrs;
1
2 import javax.ws.rs.ext.WriterInterceptor;
3
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class WriterInterceptorRegistry extends JaxrsInterceptorRegistry<WriterInterceptor>
11 {
12 public WriterInterceptorRegistry(ResteasyProviderFactory providerFactory)
13 {
14 super(providerFactory, WriterInterceptor.class);
15 }
16
17 public WriterInterceptorRegistry clone(ResteasyProviderFactory factory)
18 {
19 WriterInterceptorRegistry clone = new WriterInterceptorRegistry(factory);
20 clone.interceptors.addAll(interceptors);
21 return clone;
22 }
23 }
00 package org.jboss.resteasy.core.messagebody;
11
2 import org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext;
3 import org.jboss.resteasy.core.interception.jaxrs.ClientReaderInterceptorContext;
2 import org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext;
3 import org.jboss.resteasy.core.interception.ClientReaderInterceptorContext;
44 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
55 import org.jboss.resteasy.spi.HttpRequest;
66 import org.jboss.resteasy.spi.ReaderException;
88
99 import javax.ws.rs.core.MediaType;
1010 import javax.ws.rs.core.MultivaluedMap;
11 import javax.ws.rs.ext.MessageBodyReader;
1112 import javax.ws.rs.ext.ReaderInterceptor;
1213
1314 import java.io.ByteArrayInputStream;
00 package org.jboss.resteasy.core.messagebody;
11
2 import org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext;
3 import org.jboss.resteasy.core.interception.jaxrs.ClientWriterInterceptorContext;
2 import org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext;
3 import org.jboss.resteasy.core.interception.ClientWriterInterceptorContext;
44 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
55 import org.jboss.resteasy.spi.HttpResponse;
66 import org.jboss.resteasy.spi.ResteasyProviderFactory;
77
88 import javax.ws.rs.core.MediaType;
99 import javax.ws.rs.core.MultivaluedMap;
10 import javax.ws.rs.ext.MessageBodyWriter;
1011 import javax.ws.rs.ext.WriterInterceptor;
1112
1213 import java.io.ByteArrayOutputStream;
2525 public Expression(String segment, String additionalRegex)
2626 {
2727 this.pathExpression = segment;
28 String replacedCurlySegment = PathHelper.replaceEnclosedCurlyBraces(segment);
28 CharSequence replacedCurlySegment = PathHelper.replaceEnclosedCurlyBracesCS(segment);
2929 literalCharacters = PathHelper.URI_PARAM_PATTERN.matcher(replacedCurlySegment).replaceAll("").length();
3030
3131 String[] split = PathHelper.URI_PARAM_PATTERN.split(replacedCurlySegment);
0 package org.jboss.resteasy.logging;
1
2 import java.lang.reflect.Constructor;
3 import java.lang.reflect.InvocationTargetException;
4
5 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
6
7 /**
8 * Logging abstraction. Call setLoggerType() to the logging framework you want to use.
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 public abstract class Logger
14 {
15 public static enum LoggerType
16 {
17 JUL,
18 LOG4J,
19 SLF4J
20 }
21
22 /**
23 * Set this variable to set what logger you want. The default is java.util.logging
24 */
25 private static Constructor loggerConstructor = null;
26
27 public static void setLoggerType(LoggerType loggerType)
28 {
29 try
30 {
31 Class loggerClass = null;
32 if (loggerType == LoggerType.JUL)
33 {
34 loggerClass = Logger.class.getClassLoader().loadClass("org.jboss.resteasy.logging.impl.JULLogger");
35 }
36 else if (loggerType == LoggerType.LOG4J)
37 {
38 loggerClass = Logger.class.getClassLoader().loadClass("org.jboss.resteasy.logging.impl.Log4jLogger");
39 }
40 else if (loggerType == LoggerType.SLF4J)
41 {
42 loggerClass = Logger.class.getClassLoader().loadClass("org.jboss.resteasy.logging.impl.Slf4jLogger");
43 }
44 if (loggerClass == null)
45 throw new RuntimeException(Messages.MESSAGES.couldNotMatchUpLoggerTypeImplementation(loggerType));
46 loggerConstructor = loggerClass.getDeclaredConstructor(String.class);
47 }
48 catch (ClassNotFoundException e)
49 {
50 throw new RuntimeException(e);
51 }
52 catch (NoSuchMethodException e)
53 {
54 throw new RuntimeException(e);
55 }
56
57 }
58
59 private static boolean classInClasspath(String className)
60 {
61 try
62 {
63 return Thread.currentThread().getContextClassLoader().loadClass(className) != null;
64 }
65 catch (ClassNotFoundException e)
66 {
67 return false;
68 }
69
70 }
71
72 static
73 {
74 LoggerType type = LoggerType.JUL;
75
76 if (classInClasspath("org.apache.log4j.Logger"))
77 {
78 type = LoggerType.LOG4J;
79 }
80 else if (classInClasspath("org.slf4j.Logger"))
81 {
82 type = LoggerType.SLF4J;
83 }
84
85 setLoggerType(type);
86 }
87
88
89 public static Logger getLogger(Class<?> clazz)
90 {
91 try
92 {
93 return (Logger) loggerConstructor.newInstance(clazz.getName());
94 }
95 catch (InstantiationException e)
96 {
97 throw new RuntimeException(e);
98 }
99 catch (IllegalAccessException e)
100 {
101 throw new RuntimeException(e);
102 }
103 catch (InvocationTargetException e)
104 {
105 throw new RuntimeException(e);
106 }
107 }
108
109
110 public abstract boolean isTraceEnabled();
111
112 public abstract void trace(String message);
113
114 public abstract void trace(String message, Object... params);
115
116 public abstract void trace(String message, Throwable error);
117
118 public abstract boolean isDebugEnabled();
119
120 public abstract void debug(String message);
121
122 public abstract void debug(String message, Object... params);
123
124 public abstract void debug(String message, Throwable error);
125
126 public abstract void info(String message);
127
128 public abstract void info(String message, Object... params);
129
130 public abstract void info(String message, Throwable error);
131
132 public abstract boolean isWarnEnabled();
133
134 public abstract void warn(String message);
135
136 public abstract void warn(String message, Object... params);
137
138 public abstract void warn(String message, Throwable error);
139
140 public abstract void error(String message);
141
142 public abstract void error(String message, Object... params);
143
144 public abstract void error(String message, Throwable error);
145 }
0 package org.jboss.resteasy.logging.impl;
1
2 import org.jboss.resteasy.logging.Logger;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 */
8 public class JULLogger extends Logger
9 {
10 private transient java.util.logging.Logger delegate;
11 private String classname;
12
13 public JULLogger(String classname)
14 {
15 delegate = java.util.logging.Logger.getLogger(classname);
16 this.classname = classname;
17 }
18
19 @Override
20 public boolean isTraceEnabled()
21 {
22 return delegate.isLoggable(java.util.logging.Level.FINEST);
23 }
24
25 @Override
26 public void trace(String message)
27 {
28 if (!delegate.isLoggable(java.util.logging.Level.FINEST)) return;
29 delegate.logp(java.util.logging.Level.FINEST, classname, "", message);
30 }
31
32 @Override
33 public void trace(String message, Object... params)
34 {
35 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
36 delegate.logp(java.util.logging.Level.FINEST, classname, "", message, params);
37 }
38
39 @Override
40 public void trace(String message, Throwable error)
41 {
42 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
43 delegate.logp(java.util.logging.Level.FINEST, classname, "", message, error);
44 }
45
46 @Override
47 public boolean isDebugEnabled()
48 {
49 return delegate.isLoggable(java.util.logging.Level.FINE);
50 }
51
52 @Override
53 public void debug(String message)
54 {
55 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
56 delegate.logp(java.util.logging.Level.FINE, classname, "", message);
57 }
58
59 @Override
60 public void debug(String message, Object... params)
61 {
62 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
63 delegate.logp(java.util.logging.Level.FINE, classname, "", message, params);
64 }
65
66 @Override
67 public void debug(String message, Throwable error)
68 {
69 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
70 delegate.logp(java.util.logging.Level.FINE, classname, "", message, error);
71 }
72
73 @Override
74 public void info(String message)
75 {
76 if (!delegate.isLoggable(java.util.logging.Level.INFO)) return;
77 delegate.logp(java.util.logging.Level.INFO, classname, "", message);
78 }
79
80 @Override
81 public void info(String message, Object... params)
82 {
83 if (!delegate.isLoggable(java.util.logging.Level.INFO)) return;
84 delegate.logp(java.util.logging.Level.INFO, classname, "", message, params);
85 }
86
87 @Override
88 public void info(String message, Throwable error)
89 {
90 if (!delegate.isLoggable(java.util.logging.Level.INFO)) return;
91 delegate.logp(java.util.logging.Level.INFO, classname, "", message, error);
92 }
93
94 @Override
95 public void warn(String message)
96 {
97 if (!delegate.isLoggable(java.util.logging.Level.WARNING)) return;
98 delegate.logp(java.util.logging.Level.WARNING, classname, "", message);
99 }
100
101 @Override
102 public void warn(String message, Object... params)
103 {
104 if (!delegate.isLoggable(java.util.logging.Level.WARNING)) return;
105 delegate.logp(java.util.logging.Level.WARNING, classname, "", message, params);
106 }
107
108 @Override
109 public void warn(String message, Throwable error)
110 {
111 if (!delegate.isLoggable(java.util.logging.Level.WARNING)) return;
112 delegate.logp(java.util.logging.Level.WARNING, classname, "", message, error);
113 }
114
115 @Override
116 public void error(String message)
117 {
118 if (!delegate.isLoggable(java.util.logging.Level.SEVERE)) return;
119 delegate.logp(java.util.logging.Level.SEVERE, classname, "", message);
120 }
121
122 @Override
123 public void error(String message, Object... params)
124 {
125 if (!delegate.isLoggable(java.util.logging.Level.SEVERE)) return;
126 delegate.logp(java.util.logging.Level.SEVERE, classname, "", message, params);
127 }
128
129 @Override
130 public void error(String message, Throwable error)
131 {
132 if (!delegate.isLoggable(java.util.logging.Level.SEVERE)) return;
133 delegate.logp(java.util.logging.Level.SEVERE, classname, "", message, error);
134 }
135
136 @Override
137 public boolean isWarnEnabled()
138 {
139 return delegate.isLoggable(java.util.logging.Level.WARNING);
140 }
141 }
0 package org.jboss.resteasy.logging.impl;
1
2 import org.apache.log4j.Logger;
3
4 import java.text.MessageFormat;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class Log4jLogger extends org.jboss.resteasy.logging.Logger
11 {
12 private transient Logger delegate;
13 private String classname;
14
15 public Log4jLogger(String classname)
16 {
17 this.classname = classname;
18 delegate = Logger.getLogger(classname);
19 }
20
21 @Override
22 public boolean isTraceEnabled()
23 {
24 return delegate.isTraceEnabled();
25 }
26
27 @Override
28 public void trace(String message)
29 {
30 if (!delegate.isTraceEnabled()) return;
31 delegate.trace(message);
32 }
33
34 @Override
35 public void trace(String message, Object... params)
36 {
37 if (!delegate.isTraceEnabled()) return;
38 String msg = MessageFormat.format(message, params);
39 delegate.trace(msg);
40 }
41
42 @Override
43 public void trace(String message, Throwable error)
44 {
45 if (!delegate.isTraceEnabled()) return;
46 delegate.trace(message, error);
47 }
48
49 @Override
50 public boolean isDebugEnabled()
51 {
52 return delegate.isDebugEnabled();
53 }
54
55 @Override
56 public void debug(String message)
57 {
58 if (!delegate.isDebugEnabled()) return;
59 delegate.debug(message);
60 }
61
62 @Override
63 public void debug(String message, Object... params)
64 {
65 if (!delegate.isDebugEnabled()) return;
66 String msg = MessageFormat.format(message, params);
67 delegate.debug(msg);
68 }
69
70 @Override
71 public void debug(String message, Throwable error)
72 {
73 if (!isDebugEnabled()) return;
74 delegate.debug(message, error);
75 }
76
77 @Override
78 public void info(String message)
79 {
80 if (!(delegate.isInfoEnabled())) return;
81 delegate.info(message);
82 }
83
84 @Override
85 public void info(String message, Object... params)
86 {
87 if (!delegate.isInfoEnabled()) return;
88 String msg = MessageFormat.format(message, params);
89 delegate.info(msg);
90 }
91
92 @Override
93 public void info(String message, Throwable error)
94 {
95 if (!delegate.isInfoEnabled()) return;
96 delegate.info(message, error);
97 }
98
99 @Override
100 public void warn(String message)
101 {
102 delegate.warn(message);
103 }
104
105 @Override
106 public void warn(String message, Object... params)
107 {
108 String msg = MessageFormat.format(message, params);
109 delegate.warn(msg);
110 }
111
112 @Override
113 public void warn(String message, Throwable error)
114 {
115 delegate.warn(message, error);
116 }
117
118 @Override
119 public void error(String message)
120 {
121 delegate.warn(message);
122 }
123
124 @Override
125 public void error(String message, Object... params)
126 {
127 String msg = MessageFormat.format(message, params);
128 delegate.error(msg);
129 }
130
131 @Override
132 public void error(String message, Throwable error)
133 {
134 delegate.warn(message, error);
135 }
136
137 @Override
138 public boolean isWarnEnabled()
139 {
140 return true;
141 }
142
143 }
0 package org.jboss.resteasy.logging.impl;
1
2 import org.slf4j.Logger;
3 import org.slf4j.LoggerFactory;
4
5 import java.text.MessageFormat;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 */
11 public class Slf4jLogger extends org.jboss.resteasy.logging.Logger
12 {
13 private transient Logger delegate;
14 private String classname;
15
16 public Slf4jLogger(String classname)
17 {
18 delegate = LoggerFactory.getLogger(classname);
19 this.classname = classname;
20 }
21
22 @Override
23 public boolean isTraceEnabled()
24 {
25 return delegate.isTraceEnabled();
26 }
27
28 @Override
29 public void trace(String message)
30 {
31 if (!delegate.isTraceEnabled()) return;
32 delegate.trace(message);
33 }
34
35 @Override
36 public void trace(String message, Object... params)
37 {
38 if (!delegate.isTraceEnabled()) return;
39 String msg = MessageFormat.format(message, params);
40 delegate.trace(msg);
41 }
42
43 @Override
44 public void trace(String message, Throwable error)
45 {
46 if (!delegate.isTraceEnabled()) return;
47 delegate.trace(message, error);
48
49 }
50
51 @Override
52 public boolean isDebugEnabled()
53 {
54 return delegate.isDebugEnabled();
55 }
56
57 @Override
58 public void debug(String message)
59 {
60 if (!delegate.isDebugEnabled()) return;
61 delegate.debug(message);
62 }
63
64 @Override
65 public void debug(String message, Object... params)
66 {
67 if (!delegate.isDebugEnabled()) return;
68 String msg = MessageFormat.format(message, params);
69 delegate.debug(msg);
70 }
71
72 @Override
73 public void debug(String message, Throwable error)
74 {
75 if (!delegate.isDebugEnabled()) return;
76 delegate.debug(message, error);
77 }
78
79 @Override
80 public void info(String message)
81 {
82 if (!delegate.isInfoEnabled()) return;
83 delegate.info(message);
84 }
85
86 @Override
87 public void info(String message, Object... params)
88 {
89 if (!delegate.isInfoEnabled()) return;
90 String msg = MessageFormat.format(message, params);
91 delegate.info(msg);
92 }
93
94 @Override
95 public void info(String message, Throwable error)
96 {
97 if (!delegate.isInfoEnabled()) return;
98 delegate.info(message, error);
99 }
100
101 @Override
102 public void warn(String message)
103 {
104 if (!delegate.isWarnEnabled()) return;
105 delegate.warn(message);
106 }
107
108 @Override
109 public void warn(String message, Object... params)
110 {
111 if (!delegate.isWarnEnabled()) return;
112 String msg = MessageFormat.format(message, params);
113 delegate.warn(msg);
114 }
115
116 @Override
117 public void warn(String message, Throwable error)
118 {
119 if (!delegate.isWarnEnabled()) return;
120 delegate.warn(message, error);
121 }
122
123 @Override
124 public void error(String message)
125 {
126 if (!delegate.isErrorEnabled()) return;
127 delegate.error(message);
128 }
129
130 @Override
131 public void error(String message, Object... params)
132 {
133 if (!delegate.isErrorEnabled()) return;
134 String msg = MessageFormat.format(message, params);
135 delegate.error(msg);
136 }
137
138 @Override
139 public void error(String message, Throwable error)
140 {
141 if (!delegate.isErrorEnabled()) return;
142 delegate.error(message, error);
143 }
144
145 @Override
146 public boolean isWarnEnabled()
147 {
148 return delegate.isWarnEnabled();
149 }
150
151 }
11
22 import org.jboss.resteasy.spi.HttpResponse;
33 import org.jboss.resteasy.util.CaseInsensitiveMap;
4 import org.jboss.resteasy.util.HttpHeaderNames;
45
6 import javax.ws.rs.core.MediaType;
57 import javax.ws.rs.core.MultivaluedMap;
68 import javax.ws.rs.core.NewCookie;
79 import java.io.ByteArrayOutputStream;
810 import java.io.IOException;
911 import java.io.OutputStream;
12 import java.io.UnsupportedEncodingException;
1013 import java.util.ArrayList;
1114 import java.util.List;
1215
1821 */
1922 public class MockHttpResponse implements HttpResponse
2023 {
24 private static final String CHARSET_PREFIX = "charset=";
2125 protected int status;
2226 protected ByteArrayOutputStream baos = new ByteArrayOutputStream();
2327 protected OutputStream os = baos;
6367 return baos.toByteArray();
6468 }
6569
66 public String getContentAsString()
70 public String getContentAsString() throws UnsupportedEncodingException
6771 {
68 return new String(baos.toByteArray());
72 String charset = getCharset();
73 return (charset == null ? baos.toString() : baos.toString(charset));
74 }
75
76 private String getCharset()
77 {
78 String characterEncoding = null;
79 MultivaluedMap<String, Object> headers = this.getOutputHeaders();
80 Object obj = headers.getFirst(HttpHeaderNames.CONTENT_TYPE);
81 String value = null;
82 if (obj instanceof MediaType)
83 {
84 value = ((MediaType)obj).toString();
85 }
86 else
87 {
88 value = (String)obj;
89 }
90
91 if (value != null && !value.isEmpty())
92 {
93 int charsetIndex = value.toLowerCase().indexOf(CHARSET_PREFIX);
94 if (charsetIndex != -1)
95 {
96 characterEncoding = value.substring(charsetIndex + CHARSET_PREFIX.length());
97 }
98 }
99 return characterEncoding;
69100 }
70101
71102 public void addNewCookie(NewCookie cookie)
116147 status = 0;
117148 errorMessage = null;
118149 }
150
151 @Override
152 public void flushBuffer() throws IOException
153 {
154 }
119155 }
22 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
33 import org.jboss.resteasy.specimpl.LinkBuilderImpl;
44 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
5 import org.jboss.resteasy.spi.LinkHeader;
6
57 import javax.ws.rs.core.Link;
68 import javax.ws.rs.core.MultivaluedMap;
79 import javax.ws.rs.ext.RuntimeDelegate;
810
11 import java.util.HashMap;
12 import java.util.HashSet;
913 import java.util.List;
1014 import java.util.Map;
15 import java.util.Set;
16 import java.util.StringTokenizer;
1117
1218 /**
1319 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
00 package org.jboss.resteasy.plugins.delegates;
11
22 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.specimpl.LinkBuilderImpl;
43 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
4 import org.jboss.resteasy.spi.Link;
55 import org.jboss.resteasy.spi.LinkHeader;
66
7 import javax.ws.rs.core.Link;
87 import javax.ws.rs.core.MultivaluedMap;
98 import javax.ws.rs.ext.RuntimeDelegate;
109
9897 while (tokenizer.hasMoreTokens())
9998 {
10099 String rel = tokenizer.nextToken();
101 Link.Builder builder = new LinkBuilderImpl().uri(href);
102 if (title != null)
103 {
104 builder.title(title);
105 }
106 if (rel != null)
107 {
108 builder.rel(rel);
109 }
110 if (type != null)
111 {
112 builder.type(type);
113 }
114 for (String key : attributes.keySet())
115 {
116 builder.param(key, attributes.getFirst(key));
117 }
118 Link link = builder.build();
100 Link link = new Link(title, rel, href, type, attributes);
119101 header.getLinksByRelationship().put(rel, link);
120102 header.getLinksByTitle().put(title, link);
121103 header.getLinks().add(link);
+0
-41
resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/AcceptEncodingGZIPFilter.java less more
0 package org.jboss.resteasy.plugins.interceptors;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.Priorities;
4 import javax.ws.rs.client.ClientRequestContext;
5 import javax.ws.rs.client.ClientRequestFilter;
6 import javax.ws.rs.core.HttpHeaders;
7 import javax.ws.rs.ext.Provider;
8 import java.io.IOException;
9
10 /**
11 * Must be used in conjunction with GZIPDecodingInterceptor
12 * <p/>
13 * Sets
14 *
15 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
16 * @version $Revision: 1 $
17 */
18 @Provider
19 @Priority(Priorities.HEADER_DECORATOR)
20 public class AcceptEncodingGZIPFilter implements ClientRequestFilter
21 {
22
23 @Override
24 public void filter(ClientRequestContext ctx) throws IOException
25 {
26 String encoding = ctx.getHeaderString(HttpHeaders.ACCEPT_ENCODING);
27 if (encoding == null)
28 {
29 ctx.getHeaders().add(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate");
30 }
31 else
32 {
33 if (!encoding.contains("gzip"))
34 {
35 encoding += ", gzip";
36 ctx.getHeaders().add(HttpHeaders.ACCEPT_ENCODING, encoding);
37 }
38 }
39 }
40 }
11
22 import org.jboss.resteasy.annotations.cache.Cache;
33 import org.jboss.resteasy.annotations.cache.NoCache;
4 import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
5
46 import javax.ws.rs.GET;
57 import javax.ws.rs.container.DynamicFeature;
68 import javax.ws.rs.container.ResourceInfo;
79 import javax.ws.rs.core.CacheControl;
10 import javax.ws.rs.core.Configurable;
811 import javax.ws.rs.core.FeatureContext;
912 import java.lang.reflect.Method;
1013
00 package org.jboss.resteasy.plugins.interceptors;
1
2 import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
13
24 import javax.annotation.Priority;
35 import javax.ws.rs.Priorities;
+0
-52
resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/ClientContentEncodingAnnotationFeature.java less more
0 package org.jboss.resteasy.plugins.interceptors;
1
2 import org.jboss.resteasy.annotations.ContentEncoding;
3
4 import javax.ws.rs.ConstrainedTo;
5 import javax.ws.rs.RuntimeType;
6 import javax.ws.rs.container.DynamicFeature;
7 import javax.ws.rs.container.ResourceInfo;
8 import javax.ws.rs.core.Configurable;
9 import javax.ws.rs.core.FeatureContext;
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.Method;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 */
17 @ConstrainedTo(RuntimeType.CLIENT)
18 public class ClientContentEncodingAnnotationFeature implements DynamicFeature
19 {
20 @Override
21 public void configure(ResourceInfo resourceInfo, FeatureContext configurable)
22 {
23 final Class declaring = resourceInfo.getResourceClass();
24 final Method method = resourceInfo.getResourceMethod();
25
26 if (declaring == null || method == null) return;
27
28 for (Annotation[] annotations : method.getParameterAnnotations())
29 {
30 String encoding = getEncoding(annotations);
31 if (encoding != null)
32 {
33 configurable.register(new ClientContentEncodingAnnotationFilter(encoding));
34 return;
35 }
36 }
37 }
38
39 protected String getEncoding(Annotation[] annotations)
40 {
41 for (Annotation annotation : annotations)
42 {
43 if (annotation.annotationType().isAnnotationPresent(ContentEncoding.class))
44 {
45 return annotation.annotationType().getAnnotation(ContentEncoding.class).value();
46 }
47 }
48 return null;
49 }
50
51 }
+0
-34
resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/ClientContentEncodingAnnotationFilter.java less more
0 package org.jboss.resteasy.plugins.interceptors;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.ConstrainedTo;
4 import javax.ws.rs.Priorities;
5 import javax.ws.rs.RuntimeType;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.HttpHeaders;
8 import javax.ws.rs.ext.WriterInterceptor;
9 import javax.ws.rs.ext.WriterInterceptorContext;
10 import java.io.IOException;
11
12 /**
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 */
16 @ConstrainedTo(RuntimeType.CLIENT)
17 @Priority(Priorities.HEADER_DECORATOR)
18 public class ClientContentEncodingAnnotationFilter implements WriterInterceptor
19 {
20 protected String encoding;
21
22 public ClientContentEncodingAnnotationFilter(String encoding)
23 {
24 this.encoding = encoding;
25 }
26
27 @Override
28 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
29 {
30 context.getHeaders().putSingle(HttpHeaders.CONTENT_ENCODING, encoding);
31 context.proceed();
32 }
33 }
00 package org.jboss.resteasy.plugins.interceptors;
11
2 import org.jboss.resteasy.core.Headers;
23 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
34 import org.jboss.resteasy.spi.CorsHeaders;
45
1213
1314 import java.io.IOException;
1415 import java.util.HashSet;
16 import java.util.Map;
1517 import java.util.Set;
1618
1719 /**
146148 return;
147149 }
148150 responseContext.getHeaders().putSingle(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
151 responseContext.getHeaders().putSingle(CorsHeaders.VARY, CorsHeaders.ORIGIN);
149152 if (allowCredentials) responseContext.getHeaders().putSingle(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
150153
151154 if (exposedHeaders != null) {
160163
161164 Response.ResponseBuilder builder = Response.ok();
162165 builder.header(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
166 builder.header(CorsHeaders.VARY, CorsHeaders.ORIGIN);
163167 if (allowCredentials) builder.header(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
164168 String requestMethods = requestContext.getHeaderString(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD);
165169 if (requestMethods != null)
+0
-158
resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/GZIPDecodingInterceptor.java less more
0 package org.jboss.resteasy.plugins.interceptors;
1
2 import javax.annotation.Priority;
3 import javax.servlet.ServletContext;
4 import javax.ws.rs.Priorities;
5 import javax.ws.rs.ProcessingException;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.HttpHeaders;
8 import javax.ws.rs.core.Response;
9 import javax.ws.rs.core.Response.Status;
10 import javax.ws.rs.ext.Provider;
11 import javax.ws.rs.ext.ReaderInterceptor;
12 import javax.ws.rs.ext.ReaderInterceptorContext;
13
14 import org.jboss.resteasy.core.interception.jaxrs.ServerReaderInterceptorContext;
15 import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
16 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
17 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
18 import org.jboss.resteasy.spi.ResteasyProviderFactory;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.zip.GZIPInputStream;
23
24 /**
25 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
26 * @version $Revision: 1 $
27 */
28 @Provider
29 @Priority(Priorities.ENTITY_CODER)
30 public class GZIPDecodingInterceptor implements ReaderInterceptor
31 {
32 private static final int DEFAULT_MAX_SIZE = 10000000;
33 private int maxSize;
34
35 public GZIPDecodingInterceptor(int maxSize)
36 {
37 this.maxSize = maxSize;
38 }
39
40 public GZIPDecodingInterceptor()
41 {
42 this.maxSize = -1;
43 }
44
45 public static class FinishableGZIPInputStream extends GZIPInputStream
46 {
47 private int maxSize;
48 private int count;
49 private boolean server;
50
51 public FinishableGZIPInputStream(final InputStream is) throws IOException
52 {
53 this(is, true, DEFAULT_MAX_SIZE);
54 }
55
56 public FinishableGZIPInputStream(final InputStream is, boolean server) throws IOException
57 {
58 this(is, server, DEFAULT_MAX_SIZE);
59 }
60
61 public FinishableGZIPInputStream(final InputStream is, boolean server, int maxSize) throws IOException
62 {
63 super(is);
64 this.server = server;
65 this.maxSize = maxSize;
66 }
67
68 public int read(byte[] buf, int off, int len) throws IOException
69 {
70 LogMessages.LOGGER.debugf("Interceptor : %s, Method : read", getClass().getName());
71 int n = super.read(buf, off, len);
72 if (n > -1)
73 {
74 count += n;
75 }
76 if (count > maxSize)
77 {
78 finish();
79 close();
80 if (server)
81 {
82 throw new WebApplicationException(Response.status(Status.REQUEST_ENTITY_TOO_LARGE).entity(Messages.MESSAGES.gzipExceedsMaxSize(maxSize)).build());
83 }
84 else
85 {
86 throw new ProcessingException(Messages.MESSAGES.gzipExceedsMaxSize(maxSize));
87 }
88 }
89 return n;
90 }
91
92 public void finish()
93 {
94 inf.end(); // make sure on finish the inflater's end() is called to release the native code pointer
95 }
96 }
97
98 @Override
99 public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException
100 {
101 LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundReadFrom", getClass().getName());
102 Object encoding = context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
103 if (encoding != null && encoding.toString().equalsIgnoreCase("gzip"))
104 {
105 InputStream old = context.getInputStream();
106 FinishableGZIPInputStream is = new FinishableGZIPInputStream(old, context instanceof ServerReaderInterceptorContext, getMaxSize());
107 context.setInputStream(is);
108 try
109 {
110 return context.proceed();
111 }
112 finally
113 {
114 // Don't finish() an InputStream - TODO this still will require a garbage collect to finish the stream
115 // see RESTEASY-554 for more details
116 if (!context.getType().equals(InputStream.class)) is.finish();
117 context.setInputStream(old);
118 }
119 }
120 else
121 {
122 return context.proceed();
123 }
124 }
125
126 private int getMaxSize()
127 {
128 if (maxSize != -1)
129 {
130 return maxSize;
131 }
132
133 int size = -1;
134 ServletContext context = ResteasyProviderFactory.getContextData(ServletContext.class);
135 if (context != null)
136 {
137 String s = context.getInitParameter(ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT);
138 if (s != null)
139 {
140 try
141 {
142 size = Integer.parseInt(s);
143 }
144 catch (NumberFormatException e)
145 {
146 LogMessages.LOGGER.invalidFormat(ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT, Integer.toString(DEFAULT_MAX_SIZE));
147 }
148 }
149 }
150 if (size == -1)
151 {
152 size = DEFAULT_MAX_SIZE;
153 }
154
155 return size;
156 }
157 }
+0
-106
resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/GZIPEncodingInterceptor.java less more
0 package org.jboss.resteasy.plugins.interceptors;
1
2 import org.jboss.resteasy.util.CommitHeaderOutputStream;
3
4 import javax.annotation.Priority;
5 import javax.ws.rs.Priorities;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.HttpHeaders;
8 import javax.ws.rs.ext.Provider;
9 import javax.ws.rs.ext.WriterInterceptor;
10 import javax.ws.rs.ext.WriterInterceptorContext;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.util.zip.GZIPOutputStream;
14 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
15
16 /**
17 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
18 * @version $Revision: 1 $
19 */
20 @Provider
21 @Priority(Priorities.ENTITY_CODER)
22 public class GZIPEncodingInterceptor implements WriterInterceptor
23 {
24 public static class EndableGZIPOutputStream extends GZIPOutputStream
25 {
26 public EndableGZIPOutputStream(OutputStream os) throws IOException
27 {
28 super(os);
29 }
30
31 @Override
32 public void finish() throws IOException
33 {
34 super.finish();
35 def.end(); // make sure on finish the deflater's end() is called to release the native code pointer
36 }
37 }
38
39 public static class CommittedGZIPOutputStream extends CommitHeaderOutputStream
40 {
41 protected CommittedGZIPOutputStream(OutputStream delegate, CommitCallback headers)
42 {
43 super(delegate, headers);
44 }
45
46 protected GZIPOutputStream gzip;
47
48 public GZIPOutputStream getGzip()
49 {
50 return gzip;
51 }
52
53 @Override
54 public synchronized void commit()
55 {
56 if (isHeadersCommitted) return;
57 isHeadersCommitted = true;
58 try
59 {
60 // GZIPOutputStream constructor writes to underlying OS causing headers to be written.
61 // so we swap gzip OS in when we are ready to write.
62 gzip = new EndableGZIPOutputStream(delegate);
63 delegate = gzip;
64 }
65 catch (IOException e)
66 {
67 throw new RuntimeException(e);
68 }
69 }
70 }
71
72 @Override
73 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
74 {
75 LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundWriteTo", getClass().getName());
76
77 Object encoding = context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
78
79 if (encoding != null && encoding.toString().equalsIgnoreCase("gzip"))
80 {
81 OutputStream old = context.getOutputStream();
82 // GZIPOutputStream constructor writes to underlying OS causing headers to be written.
83 CommittedGZIPOutputStream gzipOutputStream = new CommittedGZIPOutputStream(old, null);
84
85 // Any content length set will be obsolete
86 context.getHeaders().remove("Content-Length");
87
88 context.setOutputStream(gzipOutputStream);
89 try
90 {
91 context.proceed();
92 }
93 finally
94 {
95 if (gzipOutputStream.getGzip() != null) gzipOutputStream.getGzip().finish();
96 context.setOutputStream(old);
97 }
98 return;
99 }
100 else
101 {
102 context.proceed();
103 }
104 }
105 }
+0
-94
resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/MessageSanitizerContainerResponseFilter.java less more
0 package org.jboss.resteasy.plugins.interceptors;
1
2 import java.io.IOException;
3 import java.util.ArrayList;
4 import java.util.HashMap;
5
6 import javax.annotation.Priority;
7 import javax.ws.rs.Priorities;
8 import javax.ws.rs.container.ContainerRequestContext;
9 import javax.ws.rs.container.ContainerResponseContext;
10 import javax.ws.rs.container.ContainerResponseFilter;
11 import javax.ws.rs.ext.Provider;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13
14 /**
15 * (RESTEASY-1485) Thwart select XSS attack by escaping special chars in
16 * Exception message.
17 *
18 * User: rsearls
19 * Date: 9/16/16
20 */
21 @Provider
22 @Priority(Priorities.ENTITY_CODER)
23 public class MessageSanitizerContainerResponseFilter implements ContainerResponseFilter {
24 @Override
25 public void filter(ContainerRequestContext requestContext,
26 ContainerResponseContext responseContext) throws IOException {
27
28 if (HttpResponseCodes.SC_BAD_REQUEST == responseContext.getStatus()) {
29 Object entity = responseContext.getEntity();
30 if (entity != null && entity instanceof String) {
31 ArrayList<Object> contentTypes = (ArrayList<Object>)responseContext.getHeaders().get("Content-Type");
32 if (contentTypes != null && containsHtmlText(contentTypes)) {
33 String escapedMsg = escapeXml((String) entity);
34 responseContext.setEntity(escapedMsg);
35 }
36 }
37 }
38 }
39
40
41 // set of replacement chars to hex encoding
42 private static final HashMap<String, String> replacementMap;
43 static {
44 replacementMap = new HashMap<String, String>();
45 replacementMap.put("/", "&#x2F;");
46 replacementMap.put("<", "&lt;");
47 replacementMap.put(">", "&gt;");
48 replacementMap.put("&", "&amp;");
49 replacementMap.put("\"", "&quot;");
50 replacementMap.put("'", "&#x27;");
51 }
52
53 /**
54 * Replace char with the hex encoding
55 * @param str
56 * @return
57 */
58 private String escapeXml(String str) {
59 StringBuilder sb = new StringBuilder();
60 if (!str.isEmpty()) {
61 // the vertical bar, |, is a special regular expression char that
62 // causes splitting on individual characters.
63 for (String key : str.split("|")) {
64 String value = replacementMap.get(key);
65 if (value == null) {
66 sb.append(key);
67 } else {
68 sb.append(value);
69 }
70
71 }
72 }
73 return sb.toString();
74 }
75
76 private boolean containsHtmlText(ArrayList<Object> list) {
77 for (Object o :list) {
78 if (o instanceof String) {
79 String mediaType = (String) o;
80 String[] partsType = mediaType.split("/");
81 if (partsType.length >= 2) {
82 String[] partsSubtype = partsType[1].split(";");
83 if (partsType[0].trim().equalsIgnoreCase("text") &&
84 partsSubtype[0].trim().toLowerCase().equals("html")) {
85 return true;
86 }
87 }
88 }
89 }
90 return false;
91 }
92 }
93
+0
-56
resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/ServerContentEncodingAnnotationFeature.java less more
0 package org.jboss.resteasy.plugins.interceptors;
1
2 import org.jboss.resteasy.annotations.ContentEncoding;
3
4 import javax.ws.rs.ConstrainedTo;
5 import javax.ws.rs.RuntimeType;
6 import javax.ws.rs.container.DynamicFeature;
7 import javax.ws.rs.container.ResourceInfo;
8 import javax.ws.rs.core.Configurable;
9 import javax.ws.rs.core.FeatureContext;
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.Method;
12 import java.util.HashSet;
13 import java.util.Set;
14
15 /**
16 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
17 * @version $Revision: 1 $
18 */
19 @ConstrainedTo(RuntimeType.SERVER)
20 public class ServerContentEncodingAnnotationFeature implements DynamicFeature
21 {
22 @Override
23 public void configure(ResourceInfo resourceInfo, FeatureContext configurable)
24 {
25 final Class declaring = resourceInfo.getResourceClass();
26 final Method method = resourceInfo.getResourceMethod();
27
28 if (declaring == null || method == null) return;
29 Set<String> encodings = getEncodings(method.getAnnotations());
30 if (encodings.size() <= 0)
31 {
32 encodings = getEncodings(declaring.getAnnotations());
33 if (encodings.size() <= 0) return;
34 }
35 configurable.register(createFilter(encodings));
36 }
37
38 protected ServerContentEncodingAnnotationFilter createFilter(Set<String> encodings)
39 {
40 return new ServerContentEncodingAnnotationFilter(encodings);
41 }
42
43 protected Set<String> getEncodings(Annotation[] annotations)
44 {
45 Set<String> encodings = new HashSet<String>();
46 for (Annotation annotation : annotations)
47 {
48 if (annotation.annotationType().isAnnotationPresent(ContentEncoding.class))
49 {
50 encodings.add(annotation.annotationType().getAnnotation(ContentEncoding.class).value().toLowerCase());
51 }
52 }
53 return encodings;
54 }
55 }
+0
-62
resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/ServerContentEncodingAnnotationFilter.java less more
0 package org.jboss.resteasy.plugins.interceptors;
1
2 import org.jboss.resteasy.spi.HttpRequest;
3 import org.jboss.resteasy.util.AcceptParser;
4
5 import javax.annotation.Priority;
6 import javax.ws.rs.ConstrainedTo;
7 import javax.ws.rs.Priorities;
8 import javax.ws.rs.RuntimeType;
9 import javax.ws.rs.WebApplicationException;
10 import javax.ws.rs.core.Context;
11 import javax.ws.rs.core.HttpHeaders;
12 import javax.ws.rs.ext.WriterInterceptor;
13 import javax.ws.rs.ext.WriterInterceptorContext;
14 import java.io.IOException;
15 import java.util.List;
16 import java.util.Set;
17
18 /**
19 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
20 * @version $Revision: 1 $
21 */
22 @ConstrainedTo(RuntimeType.SERVER)
23 @Priority(Priorities.HEADER_DECORATOR)
24 public class ServerContentEncodingAnnotationFilter implements WriterInterceptor
25 {
26 protected
27 @Context
28 HttpRequest request;
29
30 Set<String> encodings;
31
32 public ServerContentEncodingAnnotationFilter(Set<String> encodings)
33 {
34 this.encodings = encodings;
35 }
36
37 @Override
38 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
39 {
40 List<String> acceptEncoding = request.getHttpHeaders().getRequestHeaders().get(HttpHeaders.ACCEPT_ENCODING);
41 if (acceptEncoding != null)
42 {
43 StringBuffer buf = new StringBuffer();
44 for (String accept : acceptEncoding)
45 {
46 if (buf.length() > 0) buf.append(",");
47 buf.append(accept);
48 }
49 List<String> accepts = AcceptParser.parseAcceptHeader(buf.toString());
50 for (String encoding : accepts)
51 {
52 if (encodings.contains(encoding.toLowerCase()))
53 {
54 context.getHeaders().putSingle(HttpHeaders.CONTENT_ENCODING, encoding);
55 break;
56 }
57 }
58 }
59 context.proceed();
60 }
61 }
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.Priorities;
4 import javax.ws.rs.client.ClientRequestContext;
5 import javax.ws.rs.client.ClientRequestFilter;
6 import javax.ws.rs.core.HttpHeaders;
7 import javax.ws.rs.ext.Provider;
8 import java.io.IOException;
9
10 /**
11 * Must be used in conjunction with GZIPDecodingInterceptor
12 * <p/>
13 * Sets
14 *
15 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
16 * @version $Revision: 1 $
17 */
18 @Provider
19 @Priority(Priorities.HEADER_DECORATOR)
20 public class AcceptEncodingGZIPFilter implements ClientRequestFilter
21 {
22
23 @Override
24 public void filter(ClientRequestContext ctx) throws IOException
25 {
26 String encoding = ctx.getHeaderString(HttpHeaders.ACCEPT_ENCODING);
27 if (encoding == null)
28 {
29 ctx.getHeaders().add(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate");
30 }
31 else
32 {
33 if (!encoding.contains("gzip"))
34 {
35 encoding += ", gzip";
36 ctx.getHeaders().add(HttpHeaders.ACCEPT_ENCODING, encoding);
37 }
38 }
39 }
40 }
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import org.jboss.resteasy.annotations.interception.ClientInterceptor;
3 import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.spi.interception.ClientExecutionContext;
6 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
7
8 import javax.ws.rs.core.HttpHeaders;
9 import javax.ws.rs.ext.Provider;
10
11 /**
12 * Must be used in conjunction with GZIPDecodingInterceptor
13 * <p/>
14 * Sets
15 *
16 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
17 * @version $Revision: 1 $
18 */
19 @Provider
20 @ClientInterceptor
21 @HeaderDecoratorPrecedence
22 @Deprecated
23 public class AcceptEncodingGZIPInterceptor implements ClientExecutionInterceptor
24 {
25 public ClientResponse execute(ClientExecutionContext ctx) throws Exception
26 {
27 String encoding = ctx.getRequest().getHeaders().getFirst(HttpHeaders.ACCEPT_ENCODING);
28 if (encoding == null)
29 {
30 ctx.getRequest().header(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate");
31 }
32 else
33 {
34 if (!encoding.contains("gzip"))
35 {
36 encoding += ", gzip";
37 ctx.getRequest().header(HttpHeaders.ACCEPT_ENCODING, encoding);
38 }
39 }
40 return ctx.proceed();
41 }
42 }
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import org.jboss.resteasy.annotations.ContentEncoding;
3
4 import javax.ws.rs.ConstrainedTo;
5 import javax.ws.rs.RuntimeType;
6 import javax.ws.rs.container.DynamicFeature;
7 import javax.ws.rs.container.ResourceInfo;
8 import javax.ws.rs.core.Configurable;
9 import javax.ws.rs.core.FeatureContext;
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.Method;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 */
17 @ConstrainedTo(RuntimeType.CLIENT)
18 public class ClientContentEncodingAnnotationFeature implements DynamicFeature
19 {
20 @Override
21 public void configure(ResourceInfo resourceInfo, FeatureContext configurable)
22 {
23 final Class declaring = resourceInfo.getResourceClass();
24 final Method method = resourceInfo.getResourceMethod();
25
26 if (declaring == null || method == null) return;
27
28 for (Annotation[] annotations : method.getParameterAnnotations())
29 {
30 String encoding = getEncoding(annotations);
31 if (encoding != null)
32 {
33 configurable.register(new ClientContentEncodingAnnotationFilter(encoding));
34 return;
35 }
36 }
37 }
38
39 protected String getEncoding(Annotation[] annotations)
40 {
41 for (Annotation annotation : annotations)
42 {
43 if (annotation.annotationType().isAnnotationPresent(ContentEncoding.class))
44 {
45 return annotation.annotationType().getAnnotation(ContentEncoding.class).value();
46 }
47 }
48 return null;
49 }
50
51 }
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.ConstrainedTo;
4 import javax.ws.rs.Priorities;
5 import javax.ws.rs.RuntimeType;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.HttpHeaders;
8 import javax.ws.rs.ext.WriterInterceptor;
9 import javax.ws.rs.ext.WriterInterceptorContext;
10 import java.io.IOException;
11
12 /**
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 */
16 @ConstrainedTo(RuntimeType.CLIENT)
17 @Priority(Priorities.HEADER_DECORATOR)
18 public class ClientContentEncodingAnnotationFilter implements WriterInterceptor
19 {
20 protected String encoding;
21
22 public ClientContentEncodingAnnotationFilter(String encoding)
23 {
24 this.encoding = encoding;
25 }
26
27 @Override
28 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
29 {
30 context.getHeaders().putSingle(HttpHeaders.CONTENT_ENCODING, encoding);
31 context.proceed();
32 }
33 }
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import javax.annotation.Priority;
3 import javax.servlet.ServletContext;
4 import javax.ws.rs.Priorities;
5 import javax.ws.rs.ProcessingException;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.HttpHeaders;
8 import javax.ws.rs.core.Response;
9 import javax.ws.rs.core.Response.Status;
10 import javax.ws.rs.ext.Provider;
11 import javax.ws.rs.ext.ReaderInterceptor;
12 import javax.ws.rs.ext.ReaderInterceptorContext;
13
14 import org.jboss.resteasy.core.interception.ServerReaderInterceptorContext;
15 import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
16 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
17 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
18 import org.jboss.resteasy.spi.ResteasyProviderFactory;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.zip.GZIPInputStream;
23
24 /**
25 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
26 * @version $Revision: 1 $
27 */
28 @Provider
29 @Priority(Priorities.ENTITY_CODER)
30 public class GZIPDecodingInterceptor implements ReaderInterceptor
31 {
32 private static final int DEFAULT_MAX_SIZE = 10000000;
33 private int maxSize;
34
35 public GZIPDecodingInterceptor(int maxSize)
36 {
37 this.maxSize = maxSize;
38 }
39
40 public GZIPDecodingInterceptor()
41 {
42 this.maxSize = -1;
43 }
44
45 public static class FinishableGZIPInputStream extends GZIPInputStream
46 {
47 private int maxSize;
48 private int count;
49 private boolean server;
50
51 public FinishableGZIPInputStream(final InputStream is) throws IOException
52 {
53 this(is, true, DEFAULT_MAX_SIZE);
54 }
55
56 public FinishableGZIPInputStream(final InputStream is, boolean server) throws IOException
57 {
58 this(is, server, DEFAULT_MAX_SIZE);
59 }
60
61 public FinishableGZIPInputStream(final InputStream is, boolean server, int maxSize) throws IOException
62 {
63 super(is);
64 this.server = server;
65 this.maxSize = maxSize;
66 }
67
68 public int read(byte[] buf, int off, int len) throws IOException
69 {
70 LogMessages.LOGGER.debugf("Interceptor : %s, Method : read", getClass().getName());
71 int n = super.read(buf, off, len);
72 if (n > -1)
73 {
74 count += n;
75 }
76 if (count > maxSize)
77 {
78 finish();
79 close();
80 if (server)
81 {
82 throw new WebApplicationException(Response.status(Status.REQUEST_ENTITY_TOO_LARGE).entity(Messages.MESSAGES.gzipExceedsMaxSize(maxSize)).build());
83 }
84 else
85 {
86 throw new ProcessingException(Messages.MESSAGES.gzipExceedsMaxSize(maxSize));
87 }
88 }
89 return n;
90 }
91
92 public void finish()
93 {
94 inf.end(); // make sure on finish the inflater's end() is called to release the native code pointer
95 }
96 }
97
98 @Override
99 public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException
100 {
101 LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundReadFrom", getClass().getName());
102 Object encoding = context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
103 if (encoding != null && encoding.toString().equalsIgnoreCase("gzip"))
104 {
105 InputStream old = context.getInputStream();
106 FinishableGZIPInputStream is = new FinishableGZIPInputStream(old, context instanceof ServerReaderInterceptorContext, getMaxSize());
107 context.setInputStream(is);
108 try
109 {
110 return context.proceed();
111 }
112 finally
113 {
114 // Don't finish() an InputStream - TODO this still will require a garbage collect to finish the stream
115 // see RESTEASY-554 for more details
116 if (!context.getType().equals(InputStream.class)) is.finish();
117 context.setInputStream(old);
118 }
119 }
120 else
121 {
122 return context.proceed();
123 }
124 }
125
126 private int getMaxSize()
127 {
128 if (maxSize != -1)
129 {
130 return maxSize;
131 }
132
133 int size = -1;
134 ServletContext context = ResteasyProviderFactory.getContextData(ServletContext.class);
135 if (context != null)
136 {
137 String s = context.getInitParameter(ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT);
138 if (s != null)
139 {
140 try
141 {
142 size = Integer.parseInt(s);
143 }
144 catch (NumberFormatException e)
145 {
146 LogMessages.LOGGER.invalidFormat(ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT, Integer.toString(DEFAULT_MAX_SIZE));
147 }
148 }
149 }
150 if (size == -1)
151 {
152 size = DEFAULT_MAX_SIZE;
153 }
154
155 return size;
156 }
157 }
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import org.jboss.resteasy.util.CommitHeaderOutputStream;
3
4 import javax.annotation.Priority;
5 import javax.ws.rs.Priorities;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.HttpHeaders;
8 import javax.ws.rs.ext.Provider;
9 import javax.ws.rs.ext.WriterInterceptor;
10 import javax.ws.rs.ext.WriterInterceptorContext;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.util.zip.GZIPOutputStream;
14 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
15
16 /**
17 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
18 * @version $Revision: 1 $
19 */
20 @Provider
21 @Priority(Priorities.ENTITY_CODER)
22 public class GZIPEncodingInterceptor implements WriterInterceptor
23 {
24 public static class EndableGZIPOutputStream extends GZIPOutputStream
25 {
26 public EndableGZIPOutputStream(OutputStream os) throws IOException
27 {
28 super(os);
29 }
30
31 @Override
32 public void finish() throws IOException
33 {
34 super.finish();
35 def.end(); // make sure on finish the deflater's end() is called to release the native code pointer
36 }
37 }
38
39 public static class CommittedGZIPOutputStream extends CommitHeaderOutputStream
40 {
41 protected CommittedGZIPOutputStream(OutputStream delegate, CommitCallback headers)
42 {
43 super(delegate, headers);
44 }
45
46 protected GZIPOutputStream gzip;
47
48 public GZIPOutputStream getGzip()
49 {
50 return gzip;
51 }
52
53 @Override
54 public synchronized void commit()
55 {
56 if (isHeadersCommitted) return;
57 isHeadersCommitted = true;
58 try
59 {
60 // GZIPOutputStream constructor writes to underlying OS causing headers to be written.
61 // so we swap gzip OS in when we are ready to write.
62 gzip = new EndableGZIPOutputStream(delegate);
63 delegate = gzip;
64 }
65 catch (IOException e)
66 {
67 throw new RuntimeException(e);
68 }
69 }
70 }
71
72 @Override
73 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
74 {
75 LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundWriteTo", getClass().getName());
76
77 Object encoding = context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
78
79 if (encoding != null && encoding.toString().equalsIgnoreCase("gzip"))
80 {
81 OutputStream old = context.getOutputStream();
82 // GZIPOutputStream constructor writes to underlying OS causing headers to be written.
83 CommittedGZIPOutputStream gzipOutputStream = new CommittedGZIPOutputStream(old, null);
84
85 // Any content length set will be obsolete
86 context.getHeaders().remove("Content-Length");
87
88 context.setOutputStream(gzipOutputStream);
89 try
90 {
91 context.proceed();
92 }
93 finally
94 {
95 if (gzipOutputStream.getGzip() != null) gzipOutputStream.getGzip().finish();
96 context.setOutputStream(old);
97 }
98 return;
99 }
100 else
101 {
102 context.proceed();
103 }
104 }
105 }
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import java.io.IOException;
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.Iterator;
6
7 import javax.annotation.Priority;
8 import javax.ws.rs.Priorities;
9 import javax.ws.rs.container.ContainerRequestContext;
10 import javax.ws.rs.container.ContainerResponseContext;
11 import javax.ws.rs.container.ContainerResponseFilter;
12 import javax.ws.rs.core.MediaType;
13 import javax.ws.rs.ext.Provider;
14 import org.jboss.resteasy.util.HttpResponseCodes;
15
16 /**
17 * (RESTEASY-1485) Thwart select XSS attack by escaping special chars in
18 * Exception message.
19 *
20 * User: rsearls
21 * Date: 9/16/16
22 */
23 @Provider
24 @Priority(Priorities.ENTITY_CODER)
25 public class MessageSanitizerContainerResponseFilter implements ContainerResponseFilter {
26 @Override
27 public void filter(ContainerRequestContext requestContext,
28 ContainerResponseContext responseContext) throws IOException {
29
30 if (HttpResponseCodes.SC_BAD_REQUEST == responseContext.getStatus()) {
31 Object entity = responseContext.getEntity();
32 if (entity != null && entity instanceof String) {
33 ArrayList contentTypes = (ArrayList)responseContext.getHeaders().get("Content-Type");
34 if (contentTypes != null && containsHtmlText(contentTypes)) {
35 String escapedMsg = escapeXml((String) entity);
36 responseContext.setEntity(escapedMsg);
37 }
38 }
39 }
40 }
41
42
43 // set of replacement chars to hex encoding
44 private static final HashMap<String, String> replacementMap;
45 static {
46 replacementMap = new HashMap<String, String>();
47 replacementMap.put("/", "&#x2F;");
48 replacementMap.put("<", "&lt;");
49 replacementMap.put(">", "&gt;");
50 replacementMap.put("&", "&amp;");
51 replacementMap.put("\"", "&quot;");
52 replacementMap.put("'", "&#x27;");
53 }
54
55 /**
56 * Replace char with the hex encoding
57 * @param str
58 * @return
59 */
60 private String escapeXml(String str) {
61 StringBuilder sb = new StringBuilder();
62 if (!str.isEmpty()) {
63 // the vertical bar, |, is a special regular expression char that
64 // causes splitting on individual characters.
65 for (String key : str.split("|")) {
66 String value = replacementMap.get(key);
67 if (value == null) {
68 sb.append(key);
69 } else {
70 sb.append(value);
71 }
72
73 }
74 }
75 return sb.toString();
76 }
77
78 private boolean containsHtmlText(ArrayList<Object> list) {
79 for (Object o : list) {
80 if (o instanceof String) {
81 String mediaType = (String) o;
82 String[] partsType = mediaType.split("/");
83 if (partsType.length >= 2) {
84 String[] partsSubtype = partsType[1].split(";");
85 if (partsType[0].trim().equalsIgnoreCase("text") &&
86 partsSubtype[0].trim().toLowerCase().equals("html")) {
87 return true;
88 }
89 }
90 }
91 }
92 return false;
93 }
94 }
95
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import org.jboss.resteasy.annotations.ContentEncoding;
3
4 import javax.ws.rs.ConstrainedTo;
5 import javax.ws.rs.RuntimeType;
6 import javax.ws.rs.container.DynamicFeature;
7 import javax.ws.rs.container.ResourceInfo;
8 import javax.ws.rs.core.Configuration;
9 import javax.ws.rs.core.FeatureContext;
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.Method;
12 import java.util.HashSet;
13 import java.util.Set;
14
15 /**
16 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
17 * @version $Revision: 1 $
18 */
19 @ConstrainedTo(RuntimeType.SERVER)
20 public class ServerContentEncodingAnnotationFeature implements DynamicFeature
21 {
22 @Override
23 public void configure(ResourceInfo resourceInfo, FeatureContext configurable)
24 {
25 final Class declaring = resourceInfo.getResourceClass();
26 final Method method = resourceInfo.getResourceMethod();
27
28 if (declaring == null || method == null) return;
29 Set<String> encodings = getEncodings(method.getAnnotations());
30 if (encodings.size() <= 0)
31 {
32 encodings = getEncodings(declaring.getAnnotations());
33 if (encodings.size() <= 0) return;
34 }
35 // check if GZIP encoder has been registered
36 if (!isGZipRegistered(configurable.getConfiguration()))
37 {
38 encodings.remove("gzip");
39 }
40 configurable.register(createFilter(encodings));
41 }
42
43 protected boolean isGZipRegistered(Configuration configuration)
44 {
45 //TODO replace with the line below when dropping resteasy-legacy
46 //return configuration.isRegistered(GZIPEncodingInterceptor.class);
47 for (Class<?> c : configuration.getClasses()) {
48 if (GZIPEncodingInterceptor.class.isAssignableFrom(c)) {
49 return true;
50 }
51 }
52 return false;
53 }
54
55 protected ServerContentEncodingAnnotationFilter createFilter(Set<String> encodings)
56 {
57 return new ServerContentEncodingAnnotationFilter(encodings);
58 }
59
60 protected Set<String> getEncodings(Annotation[] annotations)
61 {
62 Set<String> encodings = new HashSet<String>();
63 for (Annotation annotation : annotations)
64 {
65 if (annotation.annotationType().isAnnotationPresent(ContentEncoding.class))
66 {
67 encodings.add(annotation.annotationType().getAnnotation(ContentEncoding.class).value().toLowerCase());
68 }
69 }
70 return encodings;
71 }
72 }
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import org.jboss.resteasy.spi.HttpRequest;
3 import org.jboss.resteasy.util.AcceptParser;
4
5 import javax.annotation.Priority;
6 import javax.ws.rs.ConstrainedTo;
7 import javax.ws.rs.Priorities;
8 import javax.ws.rs.RuntimeType;
9 import javax.ws.rs.WebApplicationException;
10 import javax.ws.rs.core.Context;
11 import javax.ws.rs.core.HttpHeaders;
12 import javax.ws.rs.ext.WriterInterceptor;
13 import javax.ws.rs.ext.WriterInterceptorContext;
14 import java.io.IOException;
15 import java.util.List;
16 import java.util.Set;
17
18 /**
19 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
20 * @version $Revision: 1 $
21 */
22 @ConstrainedTo(RuntimeType.SERVER)
23 @Priority(Priorities.HEADER_DECORATOR)
24 public class ServerContentEncodingAnnotationFilter implements WriterInterceptor
25 {
26 protected
27 @Context
28 HttpRequest request;
29
30 Set<String> encodings;
31
32 public ServerContentEncodingAnnotationFilter(Set<String> encodings)
33 {
34 this.encodings = encodings;
35 }
36
37 @Override
38 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
39 {
40 List<String> acceptEncoding = request.getHttpHeaders().getRequestHeaders().get(HttpHeaders.ACCEPT_ENCODING);
41 if (acceptEncoding != null)
42 {
43 StringBuffer buf = new StringBuffer();
44 for (String accept : acceptEncoding)
45 {
46 if (buf.length() > 0) buf.append(",");
47 buf.append(accept);
48 }
49 List<String> accepts = AcceptParser.parseAcceptHeader(buf.toString());
50 for (String encoding : accepts)
51 {
52 if (encodings.contains(encoding.toLowerCase()))
53 {
54 context.getHeaders().putSingle(HttpHeaders.CONTENT_ENCODING, encoding);
55 break;
56 }
57 }
58 }
59 context.proceed();
60 }
61 }
0 package org.jboss.resteasy.plugins.providers;
1
2 import java.util.concurrent.CompletionStage;
3
4 import org.jboss.resteasy.spi.AsyncResponseProvider;
5
6 public class CompletionStageProvider implements AsyncResponseProvider<CompletionStage<?>> {
7
8 @SuppressWarnings("rawtypes")
9 @Override
10 public CompletionStage toCompletionStage(CompletionStage<?> asyncResponse)
11 {
12 return asyncResponse;
13 }
14
15 }
105105 int count = in.read(buffer, 0, buffer.length);
106106 if (count > -1) {
107107 tempFile = File.createTempFile("resteasy-provider-datasource", null);
108 FileOutputStream fos = new FileOutputStream(tempFile);
109108 Cleanables cleanables = ResteasyProviderFactory.getContextData(Cleanables.class);
110109 if (cleanables != null)
111110 {
112111 cleanables.addCleanable(new TempFileCleanable(tempFile));
113112 }
113 FileOutputStream fos = new FileOutputStream(tempFile);
114114 fos.write(buffer, 0, count);
115115 try
116116 {
236236
237237 @Override
238238 public void clean() throws Exception {
239 if(tempFile.exists())
240 {
241 if (!tempFile.delete()) //set delete on exit only if the file can't be deleted now
242 {
243 tempFile.deleteOnExit();
244 }
245 }
239 if(tempFile.exists())
240 {
241 if (!tempFile.delete()) //set delete on exit only if the file can't be deleted now
242 {
243 tempFile.deleteOnExit();
244 }
245 }
246246 }
247247 }
248248 }
0 package org.jboss.resteasy.plugins.providers;
1
2 import java.io.IOException;
3 import java.io.OutputStream;
4 import java.io.UnsupportedEncodingException;
5 import java.lang.annotation.Annotation;
6 import java.lang.reflect.Type;
7 import java.nio.charset.StandardCharsets;
8
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.WebApplicationException;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.MultivaluedMap;
13 import javax.ws.rs.ext.MessageBodyWriter;
14 import javax.ws.rs.ext.Provider;
15
16 /**
17 * @author <a href="mailto:ema@redhat.com">Jim Ma</a>
18 */
19 @SuppressWarnings("rawtypes")
20 @Provider
21 @Produces("text/plain")
22 public class DefaultBooleanWriter implements MessageBodyWriter<Boolean>
23 {
24
25 @Override
26 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
27 {
28 return !String.class.equals(type) && !type.isArray();
29 }
30
31 @Override
32 public void writeTo(Boolean t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
33 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException,
34 WebApplicationException
35 {
36 String charset = mediaType.getParameters().get("charset");
37 if (charset == null)
38 {
39 charset = StandardCharsets.UTF_8.name();
40 }
41 try
42 {
43 entityStream.write(t.toString().getBytes(charset));
44 }
45 catch (UnsupportedEncodingException e)
46 {
47 // Use default encoding.
48 entityStream.write(t.toString().getBytes());
49 }
50 }
51
52 public long getSize(Boolean o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType)
53 {
54 String charset = mediaType.getParameters().get("charset");
55 if (charset != null)
56 try
57 {
58 return o.toString().getBytes(charset).length;
59 }
60 catch (UnsupportedEncodingException e)
61 {
62 // Use default encoding.
63 }
64 return o.toString().getBytes(StandardCharsets.UTF_8).length;
65 }
66
67 }
55 import java.lang.annotation.Annotation;
66 import java.lang.reflect.Type;
77 import java.math.BigDecimal;
8 import java.math.BigInteger;
89 import java.nio.charset.StandardCharsets;
910
1011 import javax.ws.rs.Produces;
136137 return BigDecimal.class.cast(n).toString().getBytes();
137138 }
138139 }
140
141 if (n instanceof BigInteger)
142 {
143 try
144 {
145 return BigInteger.class.cast(n).toString().getBytes(charset);
146 }
147 catch (UnsupportedEncodingException e)
148 {
149 return BigInteger.class.cast(n).toString().getBytes();
150 }
151 }
139152
140153 throw new RuntimeException(Messages.MESSAGES.unexpectedNumberSubclass(n.getClass().getName()));
141154 }
22 import org.jboss.resteasy.plugins.server.servlet.Cleanable;
33 import org.jboss.resteasy.plugins.server.servlet.Cleanables;
44 import org.jboss.resteasy.resteasy_jaxrs.i18n.*;
5 import org.jboss.logging.Logger;
56 import org.jboss.resteasy.spi.ResteasyProviderFactory;
67 import org.jboss.resteasy.util.NoContent;
78
3940 public class FileProvider implements MessageBodyReader<File>,
4041 MessageBodyWriter<File>
4142 {
43 private static final Logger LOG = Logger.getLogger(FileProvider.class);
44
4245 private static final String PREFIX = "pfx";
4346
4447 private static final String SUFFIX = "sfx";
0 package org.jboss.resteasy.plugins.providers;
1
2 import org.jboss.resteasy.spi.AsyncStreamProvider;
3 import org.reactivestreams.Publisher;
4
5 public class ReactiveStreamProvider implements AsyncStreamProvider<Publisher<?>> {
6
7 @SuppressWarnings("rawtypes")
8 @Override
9 public Publisher toAsyncStream(Publisher<?> asyncResponse)
10 {
11 return asyncResponse;
12 }
13
14 }
00 package org.jboss.resteasy.plugins.providers;
11
2 import org.jboss.resteasy.core.ThreadLocalResteasyProviderFactory;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import javax.ws.rs.ext.Providers;
7
82 import java.io.BufferedReader;
3 import java.io.IOException;
94 import java.io.InputStream;
105 import java.io.InputStreamReader;
116 import java.net.URL;
127 import java.nio.charset.StandardCharsets;
8 import java.security.AccessController;
9 import java.security.PrivilegedAction;
10 import java.security.PrivilegedActionException;
11 import java.security.PrivilegedExceptionAction;
1312 import java.util.Enumeration;
1413 import java.util.HashMap;
1514 import java.util.Map;
1615 import java.util.Map.Entry;
16
17 import javax.ws.rs.ext.Providers;
18
19 import org.jboss.resteasy.core.ThreadLocalResteasyProviderFactory;
20 import org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter;
21 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor;
22 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor;
23 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
24 import org.jboss.resteasy.spi.ResteasyProviderFactory;
1725
1826 /**
1927 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
4553
4654 public static void registerProviders(ResteasyProviderFactory factory) throws Exception
4755 {
48 Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources("META-INF/services/" + Providers.class.getName());
56 Enumeration<URL> en;
57 if (System.getSecurityManager() == null)
58 {
59 en = Thread.currentThread().getContextClassLoader().getResources("META-INF/services/" + Providers.class.getName());
60 }
61 else
62 {
63 en = AccessController.doPrivileged(new PrivilegedExceptionAction<Enumeration<URL>>()
64 {
65 @Override
66 public Enumeration<URL> run() throws IOException
67 {
68 return Thread.currentThread().getContextClassLoader().getResources("META-INF/services/" + Providers.class.getName());
69 }
70 });
71 }
72
4973 Map<String, URL> origins = new HashMap<String, URL>();
5074 while (en.hasMoreElements())
5175 {
52 URL url = en.nextElement();
53 InputStream is = url.openStream();
76 final URL url = en.nextElement();
77 InputStream is;
78 if (System.getSecurityManager() == null)
79 {
80 is = url.openStream();
81 }
82 else
83 {
84 is = AccessController.doPrivileged(new PrivilegedExceptionAction<InputStream>()
85 {
86 @Override
87 public InputStream run() throws IOException
88 {
89 return url.openStream();
90 }
91 });
92 }
93
5494 try
5595 {
5696 BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
67107 is.close();
68108 }
69109 }
70 for (Entry<String, URL> entry : origins.entrySet())
110 for (final Entry<String, URL> entry : origins.entrySet())
71111 {
72 String line = entry.getKey();
112 final String line = entry.getKey();
73113 try
74114 {
75 Class clazz = Thread.currentThread().getContextClassLoader().loadClass(line);
115 Class clazz;
116 if (System.getSecurityManager() == null)
117 {
118 clazz = Thread.currentThread().getContextClassLoader().loadClass(line);
119 }
120 else
121 {
122 clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class>()
123 {
124 @Override
125 public Class run() throws ClassNotFoundException
126 {
127 return Thread.currentThread().getContextClassLoader().loadClass(line);
128 }
129 });
130 }
131
76132 factory.registerProvider(clazz, true);
77133 }
78134 catch (NoClassDefFoundError e)
79135 {
80136 LogMessages.LOGGER.noClassDefFoundErrorError(line, entry.getValue(), e);
81137 }
82 catch (ClassNotFoundException e)
138 catch (ClassNotFoundException | PrivilegedActionException ex)
83139 {
84 LogMessages.LOGGER.classNotFoundException(line, entry.getValue(), e);
140 LogMessages.LOGGER.classNotFoundException(line, entry.getValue(), ex);
85141 }
142 }
143 if (AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
144 @Override
145 public Boolean run() {
146 final String value = System.getProperty("resteasy.allowGzip");
147 if ("".equals(value)) return Boolean.FALSE;
148 return Boolean.parseBoolean(value);
149 }
150 })) {
151 factory.registerProvider(AcceptEncodingGZIPFilter.class, true);
152 factory.registerProvider(GZIPDecodingInterceptor.class, true);
153 factory.registerProvider(GZIPEncodingInterceptor.class, true);
86154 }
87155 }
88156
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.io.ByteArrayOutputStream;
3 import java.util.Arrays;
4
5 public class EventByteArrayOutputStream extends ByteArrayOutputStream
6 {
7 public synchronized byte[] getEventPayLoad()
8 {
9 // delimiter is \r or \n
10 if (count >= 2 && this.buf[count - 2] == this.buf[count - 1])
11 {
12 return Arrays.copyOf(buf, count - 1);
13 }
14 //delimiter is \r\n
15 if (count >= 2 && buf[count - 2] == '\r' && buf[count - 1] == '\n')
16 {
17 return Arrays.copyOf(buf, count - 2);
18 }
19 return Arrays.copyOf(buf, count);
20 }
21 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 public interface EventInput
3 {
4
5 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.io.ByteArrayInputStream;
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.lang.annotation.Annotation;
6 import java.util.Arrays;
7
8 import javax.ws.rs.ProcessingException;
9 import javax.ws.rs.core.GenericType;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.MultivaluedMap;
12 import javax.ws.rs.ext.MessageBodyReader;
13 import javax.ws.rs.sse.InboundSseEvent;
14
15 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
16 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
17 import org.jboss.resteasy.spi.ResteasyProviderFactory;
18
19 public class InboundSseEventImpl implements InboundSseEvent
20 {
21 private final String name;
22
23 private final String id;
24
25 private final String comment;
26
27 private final byte[] data;
28
29 private final long reconnectDelay;
30
31 private final Annotation[] annotations;
32
33 private final MediaType mediaType;
34
35 private final MultivaluedMap<String, String> headers;
36
37 static class Builder
38 {
39 private String name;
40
41 private String id;
42
43 private long reconnectDelay = -1;
44
45 private final ByteArrayOutputStream dataStream;
46
47 private final Annotation[] annotations;
48
49 private final MediaType mediaType;
50
51 private final MultivaluedMap<String, String> headers;
52
53 private final StringBuilder commentBuilder;
54
55 public Builder(Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers)
56 {
57 this.annotations = annotations;
58 this.mediaType = mediaType;
59 this.headers = headers;
60
61 this.commentBuilder = new StringBuilder();
62 this.dataStream = new ByteArrayOutputStream();
63 }
64
65 public Builder name(String name)
66 {
67 this.name = name;
68 return this;
69 }
70
71 public Builder id(String id)
72 {
73 this.id = id;
74 return this;
75 }
76
77 public Builder commentLine(final CharSequence commentLine)
78 {
79 if (commentLine != null)
80 {
81 commentBuilder.append(commentLine).append('\n');
82 }
83
84 return this;
85 }
86
87 public Builder reconnectDelay(long milliseconds)
88 {
89 this.reconnectDelay = milliseconds;
90 return this;
91 }
92
93 public Builder write(byte[] data)
94 {
95 if (data == null || data.length == 0)
96 {
97 return this;
98 }
99 try
100 {
101 this.dataStream.write(data);
102 }
103 catch (IOException ex)
104 {
105 throw new ProcessingException(Messages.MESSAGES.failedToWriteDataToInboudEvent(), ex);
106 }
107 return this;
108 }
109
110 public InboundSseEvent build()
111 {
112 //from https://html.spec.whatwg.org/multipage/server-sent-events.html#processField
113 //If the data buffer's last character is a U+000A LINE FEED (LF) character,
114 //then remove the last character from the data buffer
115 return new InboundSseEventImpl(name, id, commentBuilder.length() > 0 ? commentBuilder.substring(0,
116 commentBuilder.length() - 1) : null, reconnectDelay, dataStream.toByteArray(), annotations, mediaType,
117 headers);
118 }
119 }
120
121 private InboundSseEventImpl(final String name, final String id, final String comment, final long reconnectDelay,
122 final byte[] data, final Annotation[] annotations, final MediaType mediaType,
123 final MultivaluedMap<String, String> headers)
124 {
125 this.name = name;
126 this.id = id;
127 this.comment = comment;
128 this.reconnectDelay = reconnectDelay;
129 this.data = data;
130 this.annotations = annotations;
131 this.mediaType = mediaType;
132 this.headers = headers;
133 }
134
135 public String getName()
136 {
137 return name;
138 }
139
140 public String getId()
141 {
142 return id;
143 }
144
145 public String getComment()
146 {
147 return comment;
148 }
149
150 public long getReconnectDelay()
151 {
152 if (reconnectDelay < 0)
153 {
154 return -1;
155 }
156 return reconnectDelay;
157 }
158
159 public boolean isReconnectDelaySet()
160 {
161 return reconnectDelay > -1;
162 }
163
164 public boolean isEmpty()
165 {
166 return data.length == 0;
167 }
168
169 public String readData()
170 {
171 return readData(SseConstants.STRING_AS_GENERIC_TYPE);
172 }
173
174 public <T> T readData(Class<T> type)
175 {
176 return readData(new GenericType<T>(type), MediaType.TEXT_PLAIN_TYPE);
177 }
178
179 public <T> T readData(GenericType<T> type)
180 {
181 return readData(type, MediaType.TEXT_PLAIN_TYPE);
182 }
183
184 public <T> T readData(Class<T> messageType, MediaType mediaType)
185 {
186 return readData(new GenericType<T>(messageType), mediaType);
187 }
188
189 public <T> T readData(GenericType<T> type, MediaType mediaType)
190 {
191 //System.out.println("Thread " + Thread.currentThread().getName() + "read data");
192 final MediaType effectiveMediaType = mediaType == null ? this.mediaType : mediaType;
193 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
194 RegisterBuiltin.register(factory);
195 final MessageBodyReader reader = factory.getClientMessageBodyReader(type.getRawType(), type.getType(),
196 annotations, mediaType);
197 if (reader == null)
198 {
199 throw new IllegalStateException(Messages.MESSAGES.notFoundMBR(type.getClass().getName()));
200 }
201 return readAndCast(type, effectiveMediaType, reader);
202 }
203
204 @SuppressWarnings("unchecked")
205 private <T> T readAndCast(GenericType<T> type, MediaType effectiveMediaType, MessageBodyReader reader)
206 {
207 try
208 {
209 return (T) reader.readFrom(type.getRawType(), type.getType(), annotations, effectiveMediaType, headers,
210 new ByteArrayInputStream(data));
211 }
212 catch (IOException ex)
213 {
214 throw new ProcessingException(Messages.MESSAGES.failedToReadData(), ex);
215 }
216 }
217
218 public byte[] getRawData()
219 {
220 if (data.length == 0)
221 {
222 return data;
223 }
224
225 return Arrays.copyOf(data, data.length);
226 }
227
228 @Override
229 public String toString()
230 {
231 String s;
232
233 try
234 {
235 s = readData();
236 }
237 catch (ProcessingException e)
238 {
239 s = "Exception:" + e.getLocalizedMessage();
240 }
241
242 return "InboundSseEvent{id=" + id + '\'' + ", comment=" + (comment == null ? "[]" : '\'' + comment + '\'')
243 + ", data=" + s + '}';
244 }
245
246 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.lang.reflect.Type;
3
4 import javax.ws.rs.core.GenericEntity;
5 import javax.ws.rs.core.GenericType;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.sse.OutboundSseEvent;
8 import javax.ws.rs.sse.Sse;
9 import javax.ws.rs.sse.SseEvent;
10
11 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
12
13 public class OutboundSseEventImpl implements OutboundSseEvent
14 {
15 private final String name;
16
17 private final String comment;
18
19 private final String id;
20
21 private final Class<?> type;
22
23 private final Type genericType;
24
25 private final MediaType mediaType;
26
27 private final Object data;
28
29 private final long reconnectDelay;
30
31 public static class BuilderImpl implements Builder
32 {
33 private String name;
34
35 private String comment;
36
37 private String id;
38
39 private long reconnectDelay = SseEvent.RECONNECT_NOT_SET;
40
41 private Class<?> type;
42
43 private Type genericType;
44
45 private Object data;
46
47 private MediaType mediaType = MediaType.TEXT_PLAIN_TYPE;
48
49 public Builder name(String name)
50 {
51 this.name = name;
52 return this;
53 }
54
55 public Builder id(String id)
56 {
57 this.id = id;
58 return this;
59 }
60
61 public Builder reconnectDelay(long milliseconds)
62 {
63 if (milliseconds < 0)
64 {
65 milliseconds = SseEvent.RECONNECT_NOT_SET;
66 }
67 this.reconnectDelay = milliseconds;
68 return this;
69 }
70
71 public Builder mediaType(final MediaType mediaType)
72 {
73 if (mediaType == null)
74 {
75 throw new NullPointerException(Messages.MESSAGES.nullValueSetToCreateOutboundSseEvent("mediaType"));
76 }
77 this.mediaType = mediaType;
78 return this;
79 }
80
81 public Builder comment(String comment)
82 {
83 this.comment = comment;
84 return this;
85 }
86
87 public Builder data(Class type, Object data)
88 {
89 if (type == null)
90 {
91 throw new NullPointerException(Messages.MESSAGES.nullValueSetToCreateOutboundSseEvent("type"));
92 }
93 if (data == null)
94 {
95 throw new NullPointerException(Messages.MESSAGES.nullValueSetToCreateOutboundSseEvent("data"));
96 }
97
98 this.type = type;
99 this.genericType = type;
100 this.data = data;
101 return this;
102 }
103
104 public Builder data(GenericType type, Object data)
105 {
106 if (type == null)
107 {
108 throw new NullPointerException(Messages.MESSAGES.nullValueSetToCreateOutboundSseEvent("type"));
109 }
110 if (data == null)
111 {
112 throw new NullPointerException(Messages.MESSAGES.nullValueSetToCreateOutboundSseEvent("data"));
113 }
114
115 this.type = type.getRawType();
116 this.genericType = type.getType();
117 this.data = data;
118 return this;
119 }
120
121 public Builder data(Object data)
122 {
123 if (data == null)
124 {
125 throw new NullPointerException(Messages.MESSAGES.nullValueSetToCreateOutboundSseEvent("data"));
126 }
127
128 if (data instanceof GenericEntity)
129 {
130 GenericEntity<?> genericEntity = (GenericEntity<?>) data;
131 this.type = genericEntity.getRawType();
132 this.genericType = genericEntity.getType();
133 this.data = genericEntity.getEntity();
134 }
135 else
136 {
137 data(data.getClass(), data);
138 }
139
140 return this;
141 }
142
143 public OutboundSseEvent build()
144 {
145 if (this.comment == null && this.data == null)
146 {
147 throw new IllegalArgumentException(Messages.MESSAGES.nullValueSetToCreateOutboundSseEvent("comment or data"));
148 }
149 return new OutboundSseEventImpl(name, id, reconnectDelay, type, genericType, mediaType, data, comment);
150 }
151 }
152
153 OutboundSseEventImpl(final String name, final String id, final long reconnectDelay, final Class<?> type, Type genericType,
154 final MediaType mediaType, final Object data, final String comment)
155 {
156 this.name = name;
157 this.comment = comment;
158 this.id = id;
159 this.reconnectDelay = reconnectDelay;
160 this.type = type;
161 this.genericType = genericType;
162 this.mediaType = mediaType;
163 this.data = data;
164 }
165
166 public String getName()
167 {
168 return name;
169 }
170
171 public String getId()
172 {
173 return id;
174 }
175
176 public long getReconnectDelay()
177 {
178 return reconnectDelay;
179 }
180
181 public boolean isReconnectDelaySet()
182 {
183 return reconnectDelay > -1;
184 }
185
186 public Class<?> getType()
187 {
188 return type;
189 }
190
191 public Type getGenericType()
192 {
193 return genericType;
194 }
195
196 public MediaType getMediaType()
197 {
198 return mediaType;
199 }
200
201 public String getComment()
202 {
203 return comment;
204 }
205
206 public Object getData()
207 {
208 return data;
209 }
210
211 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.util.List;
3 import java.util.concurrent.CompletableFuture;
4 import java.util.concurrent.CompletionStage;
5 import java.util.concurrent.ConcurrentLinkedQueue;
6 import java.util.concurrent.CopyOnWriteArrayList;
7 import java.util.function.BiConsumer;
8 import java.util.function.Consumer;
9
10 import javax.ws.rs.sse.OutboundSseEvent;
11 import javax.ws.rs.sse.SseBroadcaster;
12 import javax.ws.rs.sse.SseEventSink;
13
14 public class SseBroadcasterImpl implements SseBroadcaster
15 {
16 private ConcurrentLinkedQueue<SseEventSink> outputQueue = new ConcurrentLinkedQueue<SseEventSink>();
17
18 private final List<BiConsumer<SseEventSink, Throwable>> onErrorConsumers = new CopyOnWriteArrayList<>();
19
20 private final List<Consumer<SseEventSink>> closeConsumers = new CopyOnWriteArrayList<>();
21
22 public SseBroadcasterImpl()
23 {
24
25 }
26
27 @Override
28 public void close()
29 {
30 //Javadoc says close the broadcaster and all subscribed {@link SseEventSink} instances.
31 //is it necessay to close the subsribed SseEventSink ?
32 outputQueue.forEach(evenSink -> {
33 evenSink.close();
34 closeConsumers.forEach(consumer -> {
35 consumer.accept(evenSink);
36 });
37 });
38 outputQueue.clear();
39 }
40
41 @Override
42 public void onError(BiConsumer<SseEventSink, Throwable> onError)
43 {
44 onErrorConsumers.add(onError);
45 }
46
47 @Override
48 public void onClose(Consumer<SseEventSink> onClose)
49 {
50 closeConsumers.add(onClose);
51 }
52
53 @Override
54 public void register(SseEventSink sseEventSink)
55 {
56 outputQueue.add(sseEventSink);
57
58 }
59
60 @Override
61 public CompletionStage<?> broadcast(OutboundSseEvent event)
62 {
63 //return event immediately and doesn't block anything
64 return CompletableFuture.runAsync(() -> {
65 outputQueue.forEach(eventSink -> {
66 SseEventOutputImpl outputImpl = (SseEventOutputImpl) eventSink;
67 if (!outputImpl.isClosed())
68 {
69 outputImpl.send(event, callAllErrConsumers());
70 }
71 else
72 {
73 outputQueue.remove(eventSink);
74 }
75 });
76 });
77 }
78
79 BiConsumer<SseEventSink, Throwable> callAllErrConsumers()
80 {
81 return (eventSink, err) -> {
82 onErrorConsumers.forEach(consumer -> {
83 consumer.accept(eventSink, err);
84 });
85 };
86
87 }
88
89 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.nio.charset.StandardCharsets;
3
4 import javax.ws.rs.core.GenericType;
5
6 public class SseConstants
7 {
8 public static final String LAST_EVENT_ID_HEADER = "Last-Event-ID";
9
10 public static final GenericType<String> STRING_AS_GENERIC_TYPE = new GenericType<>(String.class);
11
12 public static final byte[] COMMENT_LEAD = ": ".getBytes(StandardCharsets.UTF_8);
13
14 public static final byte[] NAME_LEAD = "event: ".getBytes(StandardCharsets.UTF_8);
15
16 public static final byte[] ID_LEAD = "id: ".getBytes(StandardCharsets.UTF_8);
17
18 public static final byte[] RETRY_LEAD = "retry: ".getBytes(StandardCharsets.UTF_8);
19
20 public static final byte[] DATA_LEAD = "data: ".getBytes(StandardCharsets.UTF_8);
21
22 public static final byte[] EOL = "\n".getBytes(StandardCharsets.UTF_8);
23
24 //event delimiter can be '\r\r', '\n\n' or '\r\n\r\n'
25 public static final byte[] EVENT_DELIMITER = "\r\n\r\n".getBytes(StandardCharsets.UTF_8);
26
27 public enum EVENT {
28 START, COMMENT, FIELD,
29 }
30 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.io.ByteArrayInputStream;
3 import java.io.ByteArrayOutputStream;
4 import java.io.Closeable;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.lang.annotation.Annotation;
9 import java.nio.charset.Charset;
10 import java.nio.charset.StandardCharsets;
11
12 import javax.ws.rs.core.MediaType;
13 import javax.ws.rs.core.MultivaluedMap;
14 import javax.ws.rs.sse.InboundSseEvent;
15
16 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
17 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
18
19 public class SseEventInputImpl implements EventInput, Closeable
20 {
21 private Annotation[] annotations;
22
23 private MediaType mediaType;
24
25 private MultivaluedMap<String, String> httpHeaders;
26
27 private InputStream inputStream;
28
29 private volatile boolean isClosed = false;
30
31 private boolean lastFieldWasData;
32
33 private final String DELIMITER = new String(SseConstants.EVENT_DELIMITER, StandardCharsets.UTF_8);
34
35 public SseEventInputImpl(Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
36 InputStream inputStream)
37 {
38 this.annotations = annotations;
39 this.mediaType = mediaType;
40 this.httpHeaders = httpHeaders;
41 this.inputStream = inputStream;
42 }
43
44 @Override
45 public void close() throws IOException
46 {
47 this.inputStream.close();
48 isClosed = true;
49 }
50
51 public boolean isClosed()
52 {
53 return isClosed;
54 }
55
56 public InboundSseEvent read() throws IllegalStateException
57 {
58 byte[] chunk = null;
59 try
60 {
61 lastFieldWasData = false;
62 chunk = readEvent(inputStream);
63 if (chunk == null)
64 {
65 close();
66 return null;
67 }
68 }
69 catch (IOException e1)
70 {
71 try
72 {
73 close();
74 }
75 catch (IOException e)
76 {
77 //TODO: add a log message
78 }
79 throw new RuntimeException(Messages.MESSAGES.readEventException(), e1);
80 }
81
82 final ByteArrayInputStream entityStream = new ByteArrayInputStream(chunk);
83 final ByteArrayOutputStream temSave = new ByteArrayOutputStream();
84 Charset charset = StandardCharsets.UTF_8;
85 if (mediaType != null && mediaType.getParameters().get(MediaType.CHARSET_PARAMETER) != null)
86 {
87 charset = Charset.forName(mediaType.getParameters().get(MediaType.CHARSET_PARAMETER));
88 }
89
90 final InboundSseEventImpl.Builder eventBuilder = new InboundSseEventImpl.Builder(annotations, mediaType,
91 httpHeaders);
92 //TODO: Look at if this can be improved
93 int b = -1;
94 SseConstants.EVENT currentState = SseConstants.EVENT.START;
95 while ((b = entityStream.read()) != -1)
96 {
97 try
98 {
99 if (currentState == SseConstants.EVENT.START)
100 {
101 if (b == '\r' || b == '\n')
102 {
103 continue;
104 }
105
106 if (b == ':')
107 {
108 currentState = SseConstants.EVENT.COMMENT;
109 continue;
110 }
111 else
112 {
113 temSave.write(b);
114 currentState = SseConstants.EVENT.FIELD;
115 continue;
116 }
117 }
118 if (currentState == SseConstants.EVENT.COMMENT)
119 {
120
121 b = readLine(entityStream, '\n', temSave);
122 String commentLine = temSave.toString(charset.name());
123 eventBuilder.commentLine(commentLine);
124 temSave.reset();
125 currentState = SseConstants.EVENT.START;
126 continue;
127 }
128 if (currentState == SseConstants.EVENT.FIELD)
129 {
130 temSave.write(b);
131 b = readLine(entityStream, ':', temSave);
132 String fieldName = temSave.toString(StandardCharsets.UTF_8.name());
133 temSave.reset();
134 if (b == ':')
135 {
136 //spec says there is space after colon
137 do
138 {
139 b = entityStream.read();
140 }
141 while (b == ' ');
142
143 if (b != '\n' && b != '\r' && b != -1)
144 {
145 temSave.write(b);
146 b = readLine(entityStream, '\n', temSave);
147 }
148 }
149
150 processField(eventBuilder, fieldName, mediaType, temSave.toByteArray());
151 temSave.reset();
152 currentState = SseConstants.EVENT.START;
153 continue;
154 }
155 }
156 catch (IOException e)
157 {
158 throw new RuntimeException(Messages.MESSAGES.readEventException(), e);
159 }
160 }
161 return eventBuilder.build();
162 }
163
164 private int readLine(final InputStream in, final int delimiter, final OutputStream out) throws IOException
165 {
166 int b;
167 while ((b = in.read()) != -1)
168 {
169 if (b == delimiter || b == '\n' || b == '\r')
170 {
171 break;
172 }
173 else if (out != null)
174 {
175 out.write(b);
176 }
177 }
178 return b;
179 }
180
181 private void processField(final InboundSseEventImpl.Builder inboundEventBuilder, final String name,
182 final MediaType mediaType, final byte[] value)
183 {
184 Charset charset = StandardCharsets.UTF_8;
185 if (mediaType != null && mediaType.getParameters().get(MediaType.CHARSET_PARAMETER) != null)
186 {
187 charset = Charset.forName(mediaType.getParameters().get(MediaType.CHARSET_PARAMETER));
188 }
189 String valueString = new String(value, charset);
190 boolean newLastFieldWasData = false;
191 if ("event".equals(name))
192 {
193 inboundEventBuilder.name(valueString);
194 }
195 else if ("data".equals(name))
196 {
197 if (lastFieldWasData)
198 inboundEventBuilder.write(SseConstants.EOL);
199 inboundEventBuilder.write(value);
200 newLastFieldWasData = true;
201 }
202 else if ("id".equals(name))
203 {
204 inboundEventBuilder.id(valueString);
205 }
206 else if ("retry".equals(name))
207 {
208 try
209 {
210 inboundEventBuilder.reconnectDelay(Long.parseLong(valueString));
211 }
212 catch (final NumberFormatException ex)
213 {
214 LogMessages.LOGGER.skipIllegalField("retry", valueString);
215 }
216 }
217 else
218 {
219 LogMessages.LOGGER.skipUnkownFiled(name);
220 }
221 lastFieldWasData = newLastFieldWasData;
222 }
223
224 public byte[] readEvent(final InputStream in) throws IOException
225 {
226 @SuppressWarnings("resource")
227 EventByteArrayOutputStream buffer = new EventByteArrayOutputStream();
228 int data;
229 int pos = 0;
230 boolean boundary = false;
231 byte[] eolBuffer = new byte[5];
232 while ((data = in.read()) != -1)
233 {
234 byte b = (byte) data;
235 if (b == '\r' || b == '\n')
236 {
237 eolBuffer[pos] = b;
238 //if it meets \r\r , \n\n , \r\n\r\n or \n\r\n\r\n
239 if ((pos > 0 && eolBuffer[pos] == eolBuffer[pos - 1])
240 || (pos >= 3 && new String(eolBuffer, 0, pos, StandardCharsets.UTF_8).contains(DELIMITER)))
241 {
242 boundary = true;
243 }
244 //take it a boundary if there are 5 unexpected eols
245 if (pos++ > 4)
246 {
247 boundary = true;
248 }
249 }
250 else
251 {
252 pos = 0;
253 }
254 buffer.write(b);
255 if (boundary && buffer.size() > pos)
256 {
257 return buffer.getEventPayLoad();
258 }
259 //if it's emtpy
260 if (boundary && buffer.size() == pos)
261 {
262 pos = 0;
263 boundary = false;
264 buffer.reset();
265 continue;
266 }
267 }
268 return null;
269 }
270 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.io.ByteArrayOutputStream;
3 import java.io.IOException;
4 import java.lang.annotation.Annotation;
5 import java.util.Map;
6 import java.util.concurrent.CompletableFuture;
7 import java.util.concurrent.CompletionStage;
8 import java.util.function.BiConsumer;
9
10 import javax.ws.rs.ProcessingException;
11 import javax.ws.rs.core.GenericType;
12 import javax.ws.rs.core.MediaType;
13 import javax.ws.rs.core.Response;
14 import javax.ws.rs.ext.MessageBodyWriter;
15 import javax.ws.rs.sse.OutboundSseEvent;
16 import javax.ws.rs.sse.SseEventSink;
17
18 import org.jboss.resteasy.core.ServerResponseWriter;
19 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
20 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
21 import org.jboss.resteasy.specimpl.BuiltResponse;
22 import org.jboss.resteasy.spi.HttpRequest;
23 import org.jboss.resteasy.spi.HttpResponse;
24 import org.jboss.resteasy.spi.ResteasyAsynchronousContext;
25 import org.jboss.resteasy.spi.ResteasyAsynchronousResponse;
26 import org.jboss.resteasy.spi.ResteasyProviderFactory;
27
28 public class SseEventOutputImpl extends GenericType<OutboundSseEvent> implements SseEventSink
29 {
30 private final MessageBodyWriter<OutboundSseEvent> writer;
31
32 private final ResteasyAsynchronousContext asyncContext;
33
34 private final HttpResponse response;
35
36 private final HttpRequest request;
37
38 private volatile boolean closed;
39
40 private final Map<Class<?>, Object> contextDataMap;
41
42 private boolean responseFlushed = false;
43
44 private final Object lock = new Object();
45
46 public SseEventOutputImpl(final MessageBodyWriter<OutboundSseEvent> writer)
47 {
48 this.writer = writer;
49 contextDataMap = ResteasyProviderFactory.getContextDataMap();
50
51 request = ResteasyProviderFactory.getContextData(org.jboss.resteasy.spi.HttpRequest.class);
52 asyncContext = request.getAsyncContext();
53
54 if (!asyncContext.isSuspended())
55 {
56 try
57 {
58 asyncContext.suspend();
59 }
60 catch (IllegalStateException ex)
61 {
62 LogMessages.LOGGER.failedToSetRequestAsync();
63 }
64 }
65
66 response = ResteasyProviderFactory.getContextData(HttpResponse.class);
67 }
68
69 @Override
70 public void close()
71 {
72 synchronized (lock)
73 {
74 closed = true;
75 if (asyncContext.isSuspended())
76 {
77 ResteasyAsynchronousResponse asyncResponse = asyncContext.getAsyncResponse();
78 if (asyncResponse != null)
79 {
80 asyncResponse.complete();
81 }
82 }
83 }
84 }
85
86 protected void flushResponseToClient()
87 {
88 synchronized (lock)
89 {
90 if (!responseFlushed)
91 {
92 BuiltResponse jaxrsResponse = null;
93 if(this.closed)
94 {
95 jaxrsResponse = (BuiltResponse) Response.noContent().build();
96 }
97 else
98 {
99 //set back to client 200 OK to implies the SseEventOutput is ready
100 jaxrsResponse = (BuiltResponse) Response.ok().type(MediaType.SERVER_SENT_EVENTS).build();
101 }
102
103 try
104 {
105 ServerResponseWriter.writeNomapResponse(jaxrsResponse, request, response,
106 ResteasyProviderFactory.getInstance(), t -> {
107 }, true);
108 response.getOutputStream().write(SseConstants.EOL);
109 response.getOutputStream().write(SseConstants.EOL);
110 response.flushBuffer();
111 responseFlushed = true;
112 }
113 catch (IOException e)
114 {
115 close();
116 throw new ProcessingException(Messages.MESSAGES.failedToCreateSseEventOutput(), e);
117 }
118 }
119 }
120 }
121
122 @Override
123 public boolean isClosed()
124 {
125 return closed;
126 }
127
128 @Override
129 public CompletionStage<?> send(OutboundSseEvent event)
130 {
131 return send(event, (a, b) -> {
132 });
133 }
134
135 //We need this to make it async enough
136 public CompletionStage<?> send(OutboundSseEvent event, BiConsumer<SseEventSink, Throwable> errorConsumer)
137 {
138 synchronized (lock)
139 {
140 if (closed)
141 {
142 throw new IllegalStateException(Messages.MESSAGES.sseEventSinkIsClosed());
143 }
144 try
145 {
146 flushResponseToClient();
147 writeEvent(event);
148
149 }
150 catch (Exception ex)
151 {
152 errorConsumer.accept(this, ex);
153 return CompletableFuture.completedFuture(ex);
154 }
155 return CompletableFuture.completedFuture(event);
156 }
157 }
158
159 protected void writeEvent(OutboundSseEvent event) throws IOException
160 {
161 synchronized (lock)
162 {
163 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
164 try
165 {
166 if (event != null)
167 {
168 ByteArrayOutputStream bout = new ByteArrayOutputStream();
169 writer.writeTo(event, event.getClass(), null, new Annotation[]
170 {}, event.getMediaType(), null, bout);
171 response.getOutputStream().write(bout.toByteArray());
172 response.flushBuffer();
173 }
174 }
175 catch (IOException e)
176 {
177 //The connection could be broken or closed. whenever IO error happens, mark closed to true to
178 //stop event writing
179 close();
180 LogMessages.LOGGER.failedToWriteSseEvent(event.toString(), e);
181 throw e;
182 }
183 catch (Exception e)
184 {
185 LogMessages.LOGGER.failedToWriteSseEvent(event.toString(), e);
186 throw new ProcessingException(e);
187 }
188 finally
189 {
190 ResteasyProviderFactory.removeContextDataLevel();
191 }
192 }
193 }
194
195 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.io.IOException;
3 import java.io.OutputStream;
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.Type;
6
7 import javax.ws.rs.WebApplicationException;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.MultivaluedMap;
10 import javax.ws.rs.ext.MessageBodyWriter;
11 import javax.ws.rs.ext.Provider;
12 import javax.ws.rs.sse.SseEventSink;
13
14 //TODO: look at if this is some deprecated thing we should remove
15 @Provider
16 public class SseEventOutputProvider implements MessageBodyWriter<SseEventSink>
17 {
18 @Override
19 public boolean isWriteable(Class<?> cls, Type type, Annotation[] anns, MediaType mt)
20 {
21 return SseEventSink.class.isAssignableFrom(cls);
22 }
23
24 @Override
25 public long getSize(final SseEventSink output, final Class<?> type, final Type genericType,
26 final Annotation[] annotations, final MediaType mediaType)
27 {
28 return -1;
29 }
30
31 @Override
32 public void writeTo(final SseEventSink output, final Class<?> type, final Type genericType,
33 final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
34 final OutputStream entityStream) throws IOException, WebApplicationException
35 {
36 //no operation
37 }
38 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.io.OutputStream;
5 import java.lang.annotation.Annotation;
6 import java.lang.reflect.Type;
7 import java.nio.charset.Charset;
8 import java.nio.charset.StandardCharsets;
9
10 import javax.ws.rs.Consumes;
11 import javax.ws.rs.Produces;
12 import javax.ws.rs.ServerErrorException;
13 import javax.ws.rs.WebApplicationException;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.core.MultivaluedMap;
16 import javax.ws.rs.core.Response;
17 import javax.ws.rs.ext.MessageBodyReader;
18 import javax.ws.rs.ext.MessageBodyWriter;
19 import javax.ws.rs.ext.Provider;
20 import javax.ws.rs.sse.OutboundSseEvent;
21
22 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
23 import org.jboss.resteasy.spi.ResteasyProviderFactory;
24
25 @Provider
26 @Produces(
27 {"text/event-stream"})
28 @Consumes(
29 {"text/event-stream"})
30 public class SseEventProvider implements MessageBodyWriter<OutboundSseEvent>, MessageBodyReader<SseEventInputImpl>
31 {
32 @Override
33 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
34 {
35 return OutboundSseEvent.class.isAssignableFrom(type) && MediaType.SERVER_SENT_EVENTS_TYPE.isCompatible(mediaType);
36 }
37
38 @Override
39 public long getSize(OutboundSseEvent t, Class<?> type, Type genericType, Annotation[] annotations,
40 MediaType mediaType)
41 {
42 return -1;
43 }
44
45 @Override
46 @SuppressWarnings(
47 {"unchecked"})
48 public void writeTo(OutboundSseEvent event, Class<?> type, Type genericType, Annotation[] annotations,
49 MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
50 throws IOException, WebApplicationException
51 {
52 Charset charset = StandardCharsets.UTF_8;
53 if (event.getComment() != null)
54 {
55 for (final String comment : event.getComment().split("\n"))
56 {
57 entityStream.write(SseConstants.COMMENT_LEAD);
58 entityStream.write(comment.getBytes(charset));
59 entityStream.write(SseConstants.EOL);
60 }
61 }
62
63 if (event.getType() != null)
64 {
65 if (event.getName() != null)
66 {
67 entityStream.write(SseConstants.NAME_LEAD);
68 entityStream.write(event.getName().getBytes(charset));
69 entityStream.write(SseConstants.EOL);
70 }
71 if (event.getId() != null)
72 {
73 entityStream.write(SseConstants.ID_LEAD);
74 entityStream.write(event.getId().getBytes(charset));
75 entityStream.write(SseConstants.EOL);
76 }
77 if (event.getReconnectDelay() > -1)
78 {
79 entityStream.write(SseConstants.RETRY_LEAD);
80 entityStream.write(Long.toString(event.getReconnectDelay()).getBytes(StandardCharsets.UTF_8));
81 entityStream.write(SseConstants.EOL);
82 }
83
84 if (event.getData() != null)
85 {
86 Class<?> payloadClass = event.getType();
87 Type payloadType = event.getGenericType();
88 if (payloadType == null)
89 {
90 payloadType = payloadClass;
91 }
92
93 if (payloadType == null && payloadClass == null)
94 {
95 payloadType = Object.class;
96 payloadClass = Object.class;
97 }
98
99 entityStream.write(SseConstants.DATA_LEAD);
100 MessageBodyWriter writer = ResteasyProviderFactory.getInstance().getMessageBodyWriter(payloadClass,
101 payloadType, annotations, event.getMediaType());
102
103 if (writer == null)
104 {
105 throw new ServerErrorException(Messages.MESSAGES.notFoundMBW(payloadClass.getName()),
106 Response.Status.INTERNAL_SERVER_ERROR);
107 }
108 writer.writeTo(event.getData(), payloadClass, payloadType, annotations, event.getMediaType(), httpHeaders,
109 new OutputStream()
110 {
111 boolean isNewLine = false;
112
113 @Override
114 public void write(int b) throws IOException
115 {
116 if (b == '\n' || b == '\r')
117 {
118 if (!isNewLine)
119 {
120 entityStream.write(SseConstants.EOL);
121 }
122 isNewLine = true;
123 }
124 else
125 {
126 if (isNewLine)
127 {
128 entityStream.write(SseConstants.DATA_LEAD);
129 }
130 entityStream.write(b);
131 isNewLine = false;
132 }
133 }
134
135 @Override
136 public void flush() throws IOException
137 {
138 entityStream.flush();
139 }
140
141 @Override
142 public void close() throws IOException
143 {
144 entityStream.close();
145 }
146 });
147 entityStream.write(SseConstants.EOL);
148
149 }
150
151 }
152 entityStream.write(SseConstants.EOL);
153 }
154
155 @Override
156 public boolean isReadable(Class<?> cls, Type type, Annotation[] annotations, MediaType mediaType)
157 {
158 return SseEventInputImpl.class.isAssignableFrom(cls) && MediaType.SERVER_SENT_EVENTS_TYPE.isCompatible(mediaType);
159 }
160
161 @Override
162 public SseEventInputImpl readFrom(Class<SseEventInputImpl> cls, Type type, Annotation[] annotations,
163 MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException,
164 WebApplicationException
165 {
166 return new SseEventInputImpl(annotations, mediaType, httpHeaders, entityStream);
167 }
168
169 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import java.io.IOException;
3
4 import javax.annotation.Priority;
5 import javax.ws.rs.container.ContainerRequestContext;
6 import javax.ws.rs.container.ContainerRequestFilter;
7 import javax.ws.rs.ext.Provider;
8 import javax.ws.rs.sse.SseEventSink;
9
10 import org.jboss.resteasy.core.interception.PostMatchContainerRequestContext;
11 import org.jboss.resteasy.core.PostResourceMethodInvoker;
12 import org.jboss.resteasy.core.PostResourceMethodInvokers;
13 import org.jboss.resteasy.spi.ResteasyProviderFactory;
14
15 @Provider
16 @Priority(Integer.MAX_VALUE)
17 public class SseEventSinkInterceptor implements ContainerRequestFilter
18 {
19 @Override
20 public void filter(ContainerRequestContext requestContext) throws IOException
21 {
22 if (requestContext instanceof PostMatchContainerRequestContext && ((PostMatchContainerRequestContext) requestContext).getResourceMethod().isSse())
23 {
24 SseEventOutputImpl sink = new SseEventOutputImpl(new SseEventProvider());
25 ResteasyProviderFactory.getContextDataMap().put(SseEventSink.class, sink);
26 ResteasyProviderFactory.getContextData(PostResourceMethodInvokers.class).addInvokers(new PostResourceMethodInvoker()
27 {
28 @Override
29 public void invoke()
30 {
31 sink.flushResponseToClient();
32 }
33 });
34 }
35 }
36
37 }
0 package org.jboss.resteasy.plugins.providers.sse;
1
2 import javax.ws.rs.sse.OutboundSseEvent;
3 import javax.ws.rs.sse.Sse;
4 import javax.ws.rs.sse.SseBroadcaster;
5
6 public class SseImpl implements Sse
7 {
8
9 @Override
10 public OutboundSseEvent.Builder newEventBuilder()
11 {
12 return new OutboundSseEventImpl.BuilderImpl();
13 }
14
15 @Override
16 public SseBroadcaster newBroadcaster()
17 {
18 return new SseBroadcasterImpl();
19 }
20 }
0 package org.jboss.resteasy.plugins.providers.validation;
1
2 import java.lang.reflect.Method;
3 import java.util.Iterator;
4
5 import javax.validation.ConstraintViolation;
6 import javax.validation.ElementKind;
7 import javax.validation.Path.Node;
8
9 import org.jboss.resteasy.api.validation.ConstraintType;
10 import org.jboss.resteasy.plugins.providers.validation.ConstraintTypeUtil;
11 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
12 import java.security.AccessController;
13 import java.security.PrivilegedActionException;
14 import java.security.PrivilegedExceptionAction;
15
16 /**
17 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
18 * @version $Revision: 1.1 $
19 *
20 * Copyright Mar 6, 2012
21 */
22 public class ConstraintTypeUtil11 implements ConstraintTypeUtil
23 {
24 public ConstraintType.Type getConstraintType(Object o)
25 {
26 if (!(o instanceof ConstraintViolation))
27 {
28 throw new RuntimeException(Messages.MESSAGES.unknownObjectPassedAsConstraintViolation(o));
29 }
30 ConstraintViolation<?> v = ConstraintViolation.class.cast(o);
31
32 Iterator<Node> nodes = v.getPropertyPath().iterator();
33 Node firstNode = nodes.next();
34 if (firstNode.getKind() == ElementKind.METHOD)
35 {
36 Node secondNode = nodes.next();
37
38 if (secondNode.getKind() == ElementKind.PARAMETER ||
39 secondNode.getKind() == ElementKind.CROSS_PARAMETER)
40 {
41 return ConstraintType.Type.PARAMETER;
42 }
43 else if (secondNode.getKind() == ElementKind.RETURN_VALUE)
44 {
45 return ConstraintType.Type.RETURN_VALUE;
46 }
47 else
48 {
49 throw new RuntimeException(Messages.MESSAGES.unexpectedPathNodeViolation(secondNode.getKind()));
50 }
51 }
52
53 if (firstNode.getKind() == ElementKind.BEAN)
54 {
55 return ConstraintType.Type.CLASS;
56 }
57
58 if (firstNode.getKind() == ElementKind.PROPERTY)
59 {
60 String fieldName = firstNode.getName();
61 try
62 {
63 String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
64 getMethod(v.getRootBeanClass(), getterName);
65 return ConstraintType.Type.PROPERTY;
66 }
67 catch (NoSuchMethodException e)
68 {
69 try
70 {
71 String getterName = "is" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
72 Method m = getMethod(v.getLeafBean().getClass(), getterName);
73 if (m.getReturnType().equals(boolean.class))
74 {
75 return ConstraintType.Type.PROPERTY;
76 }
77 else
78 {
79 return ConstraintType.Type.FIELD;
80 }
81 }
82 catch (NoSuchMethodException e1)
83 {
84 return ConstraintType.Type.FIELD;
85 }
86 }
87 }
88
89 throw new RuntimeException(Messages.MESSAGES.unexpectedPathNode(firstNode.getKind()));
90 }
91
92 private static Method getMethod(Class<?> clazz, String methodName) throws NoSuchMethodException
93 {
94 Method method = null;
95 method = checkMethodAccess(clazz, methodName);
96
97 while (method == null)
98 {
99 clazz = clazz.getSuperclass();
100 if (clazz == null)
101 {
102 break;
103 }
104
105 method = checkMethodAccess(clazz, methodName);
106 }
107 if (method == null)
108 {
109 throw new NoSuchMethodException(methodName);
110 }
111 return method;
112 }
113
114 private static Method checkMethodAccess(final Class<?> clazz, final String methodName) {
115 Method method = null;
116 try
117 {
118 if (System.getSecurityManager() == null)
119 {
120 method = clazz.getDeclaredMethod(methodName);
121 }
122 else
123 {
124 method = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() {
125 @Override
126 public Method run() throws Exception {
127 return clazz.getDeclaredMethod(methodName);
128 }
129 });
130 }
131 }
132 catch(PrivilegedActionException pae) {
133 }
134 catch (NoSuchMethodException e)
135 {
136 // Ignore.
137 }
138
139 return method;
140 }
141 }
183183 }
184184 return decodedFormParameters;
185185 }
186
187 public boolean formParametersRead()
188 {
189 return decodedFormParameters != null;
190 }
186191
187192 @Override
188193 public HttpHeaders getHttpHeaders()
6565
6666 public void putSingle(String key, Object value)
6767 {
68 if (value == null)
69 {
70 return;
71 }
6872 cachedHeaders.putSingle(key, value);
6973 RuntimeDelegate.HeaderDelegate delegate = factory.getHeaderDelegate(value.getClass());
7074 if (delegate != null)
8791
8892 protected void addResponseHeader(String key, Object value)
8993 {
94 if (value == null)
95 {
96 return;
97 }
9098 RuntimeDelegate.HeaderDelegate delegate = factory.getHeaderDelegate(value.getClass());
9199 if (delegate != null)
92100 {
163171
164172 protected void putResponseHeader(String key, Object value)
165173 {
174 if (value == null)
175 {
176 return;
177 }
166178 RuntimeDelegate.HeaderDelegate delegate = factory.getHeaderDelegate(value.getClass());
167179 if (delegate != null)
168180 {
2121 protected OutputStream outputStream = new DeferredOutputStream();
2222
2323 /**
24 * RESTEASY-684 wants to defer access to outputstream until a write happens
24 * RESTEASY-684 wants to defer access to outputstream until a write/flush/close happens
2525 *
2626 */
2727 protected class DeferredOutputStream extends OutputStream
4747 @Override
4848 public void flush() throws IOException
4949 {
50 //NOOP (RESTEASY-1650)
50 response.getOutputStream().flush();
5151 }
5252
5353 @Override
5454 public void close() throws IOException
5555 {
56 //NOOP (RESTEASY-1650)
56 response.getOutputStream().close();
5757 }
5858 }
5959
117117 outputHeaders = new HttpServletResponseHeaders(response, factory);
118118 }
119119
120 @Override
121 public void flushBuffer() throws IOException
122 {
123 response.flushBuffer();
124 }
125
120126 }
8585 if (done) return false;
8686 if (cancelled) return false;
8787 AsyncContext asyncContext = getAsyncContext();
88 try
89 {
90 return internalResume(entity);
91 }
92 finally
93 {
94 done = true;
95 asyncContext.complete();
96 }
88 done = true;
89 return internalResume(entity, t -> asyncContext.complete());
90 }
91
92 }
93
94 @Override
95 public void complete()
96 {
97 synchronized (responseLock)
98 {
99 if (done) return;
100 if (cancelled) return;
101 AsyncContext asyncContext = getAsyncContext();
102 done = true;
103 asyncContext.complete();
97104 }
98105
99106 }
106113 if (done) return false;
107114 if (cancelled) return false;
108115 AsyncContext asyncContext = getAsyncContext();
109 try
116 done = true;
117 return internalResume(exc, t -> {
118 if(t instanceof UnhandledException)
119 {
120 internalResume(Response.status(500).build(), t2 -> asyncContext.complete());
121 }
122 else
123 {
124 asyncContext.complete();
125 }
126 });
127 }
128 }
129
130 @Override
131 public void initialRequestThreadFinished()
132 {
133 // done
134 }
135
136 @Override
137 public boolean setTimeout(long time, TimeUnit unit) throws IllegalStateException
138 {
139 //getAsyncContext().setTimeout(-1);
140 synchronized (responseLock)
141 {
142 if (done || cancelled)
143 return false;
144
145 // this is to get around TCK tests that call setTimeout in a separate thread which is illegal.
146 if (timeoutFuture != null && !timeoutFuture.cancel(false))
110147 {
111 return internalResume(exc);
148 return false;
112149 }
113 catch (UnhandledException unhandled)
150 if (time <= 0) return true;
151 Runnable task = new Runnable()
114152 {
115 return internalResume(Response.status(500).build());
116 }
117 finally
118 {
119 done = true;
120 asyncContext.complete();
121 }
122 }
123 }
124
125 @Override
126 public void initialRequestThreadFinished()
127 {
128 // done
129 }
130
131 @Override
132 public boolean setTimeout(long time, TimeUnit unit) throws IllegalStateException
133 {
134 synchronized (responseLock)
135 {
136 if (done || cancelled) return false;
137 Thread thread = creatingThread.get();
138 if (thread != null && thread != Thread.currentThread()) {
139 // this is to get around TCK tests that call setTimeout in a separate thread which is illegal.
140 if (timeoutFuture != null && !timeoutFuture.cancel(false)) {
141 return false;
153 @Override
154 public void run()
155 {
156 LogMessages.LOGGER.debug(Messages.MESSAGES.scheduledTimeout());
157 handleTimeout();
142158 }
143 Runnable task = new Runnable() {
144 @Override
145 public void run()
146 {
147 LogMessages.LOGGER.debug(Messages.MESSAGES.scheduledTimeout());
148 handleTimeout();
149 }
150 };
151 LogMessages.LOGGER.debug(Messages.MESSAGES.schedulingTimeout());
152 timeoutFuture = asyncScheduler.schedule(task, time, unit);
153 } else {
154 AsyncContext asyncContext = getAsyncContext();
155 long l = unit.toMillis(time);
156 asyncContext.setTimeout(l);
157 }
158
159 };
160 LogMessages.LOGGER.debug(Messages.MESSAGES.schedulingTimeout());
161 timeoutFuture = asyncScheduler.schedule(task, time, unit);
159162 }
160163 return true;
161164 }
177180 done = true;
178181 cancelled = true;
179182 AsyncContext asyncContext = getAsyncContext();
180 try
181 {
182 LogMessages.LOGGER.debug(Messages.MESSAGES.cancellingWith503());
183 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).build());
184 }
185 finally
186 {
187 asyncContext.complete();
188 }
183 LogMessages.LOGGER.debug(Messages.MESSAGES.cancellingWith503());
184 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).build(), t -> asyncContext.complete());
189185 }
190186 }
191187
199195 done = true;
200196 cancelled = true;
201197 AsyncContext asyncContext = getAsyncContext();
202 try
203 {
204 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build());
205 }
206 finally
207 {
208 asyncContext.complete();
209 }
198 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(),
199 t -> asyncContext.complete());
210200 }
211201 }
212202
220210 done = true;
221211 cancelled = true;
222212 AsyncContext asyncContext = getAsyncContext();
223 try
224 {
225 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build());
226 }
227 finally
228 {
229 asyncContext.complete();
230 }
213 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(),
214 t -> asyncContext.complete());
231215 }
232216 }
233217
335319 AsyncContext asyncContext = servletRequest.startAsync();
336320 asyncContext.addListener(asynchronousResponse);
337321 wasSuspended = true;
322 //set time out to -1 and resteasy will take care of timeout
323 asyncContext.setTimeout(-1);
338324 return asyncContext;
339325 }
340326
2020 import javax.ws.rs.NotFoundException;
2121 import javax.ws.rs.core.Application;
2222 import javax.ws.rs.core.SecurityContext;
23 import javax.ws.rs.ext.Provider;
2423
2524 import java.io.IOException;
2625 import java.util.ArrayList;
213212 return;
214213 }
215214
216 try (HttpResponse theResponse = responseFactory.createResteasyHttpResponse(response))
217 {
218 HttpRequest in = requestFactory.createResteasyHttpRequest(httpMethod, request, headers, uriInfo, theResponse, response);
219
215 HttpResponse theResponse = responseFactory.createResteasyHttpResponse(response);
216 HttpRequest in = requestFactory.createResteasyHttpRequest(httpMethod, request, headers, uriInfo, theResponse, response);
217
218 try
219 {
220220 ResteasyProviderFactory.pushContext(HttpServletRequest.class, request);
221221 ResteasyProviderFactory.pushContext(HttpServletResponse.class, response);
222222
1010 import org.jboss.logging.annotations.LogMessage;
1111 import org.jboss.logging.annotations.Message;
1212 import org.jboss.logging.annotations.Message.Format;
13 import org.jboss.logging.annotations.MessageLogger;
1314 import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
14 import org.jboss.logging.annotations.MessageLogger;
1515
1616 /**
1717 *
5858
5959 @LogMessage(level = Level.ERROR)
6060 @Message(id = BASE + 25, value = "Unknown exception while executing {0} {1}", format=Format.MESSAGE_FORMAT)
61 void unknownException(String method, String path, @Cause Throwable cause);
61 void unknownException(String method, String path, @Cause Throwable cause);
62
63 @LogMessage(level = Level.ERROR)
64 @Message(id = BASE + 30, value = "Failed to write event {0}", format=Format.MESSAGE_FORMAT)
65 void failedToWriteSseEvent(String event, @Cause Throwable cause);
6266
6367 ///////////////////////////////////////////////////////////////////////////////////////////////////////////
6468 // WARN //
7983 @LogMessage(level = Level.WARN)
8084 @Message(id = BASE + 115, value = "Attempting to register unassignable contract for %s")
8185 void attemptingToRegisterUnassignableContract(String className);
86
87 @LogMessage(level = Level.WARN)
88 @Message(id = BASE + 117, value = "Charset %s unavailable.")
89 void charsetUnavailable(String charset);
8290
8391 @LogMessage(level = Level.WARN)
8492 @Message(id = BASE + 120, value = "ClassNotFoundException: Unable to load builtin provider {0} from {1}", format=Format.MESSAGE_FORMAT)
8593 void classNotFoundException(String line, URL url, @Cause Throwable cause);
86
94
8795 @LogMessage(level = Level.WARN)
8896 @Message(id = BASE + 123, value = "Could not bind to specified download directory %s so will use temp dir.")
8997 void couldNotBindToDirectory(String directory);
144152 @Message(id = BASE + 175, value = "The use of %s is deprecated, please use javax.ws.rs.Application as a context-param instead")
145153 void useOfApplicationClass(String className);
146154
155 @LogMessage(level = Level.WARN)
156 @Message(id = BASE + 180, value = "Skip illegal field [%s] in value: [%s]")
157 void skipIllegalField(String filed, String value);
158
159 @LogMessage(level = Level.WARN)
160 @Message(id = BASE + 185, value = "Skip unkown field [%s]")
161 void skipUnkownFiled(String filed);
162
163 @LogMessage(level = Level.WARN)
164 @Message(id = BASE + 186, value = "Failed to set servlet request into asynchronous mode, server sent events may not work")
165 void failedToSetRequestAsync();
166
167 @LogMessage(level = Level.WARN)
168 @Message(id = BASE + 190, value = "Annotation, @PreMaching, not valid on ClientRequestFilter implementation, [%s]. Annotation is being ignored.")
169 void warningPreMatchingSupport(String clazzname);
170
171 @LogMessage(level = Level.WARN)
172 @Message(id = BASE + 195, value = "The following sub-resource methods and sub-resource locators have the same path, [%s]. The paths should be unique. [%s]")
173 void uriAmbiguity(String path, String methodList);
174
147175 ///////////////////////////////////////////////////////////////////////////////////////////////////////////
148176 // INFO //
149177 ///////////////////////////////////////////////////////////////////////////////////////////////////////////
33 import java.lang.reflect.Method;
44 import java.lang.reflect.Type;
55 import java.net.URI;
6 import java.net.URL;
7
6
7 import javax.validation.ElementKind;
88 import javax.ws.rs.core.MediaType;
99 import javax.ws.rs.core.Response.Status;
1010
1111 import org.jboss.logging.annotations.Message;
1212 import org.jboss.logging.annotations.Message.Format;
1313 import org.jboss.logging.annotations.MessageBundle;
14 import org.jboss.resteasy.api.validation.ConstraintType;
15 import org.jboss.resteasy.logging.Logger.LoggerType;
1416 import org.jboss.resteasy.util.WeightedLanguage;
1517
1618 /**
2628 Messages MESSAGES = org.jboss.logging.Messages.getBundle(Messages.class);
2729 int BASE = 3000;
2830 int BASE_ASYNC = 9500;
31 int BASE_VALIDATOR_11 = 8500;
32
33 @Message(id = BASE_VALIDATOR_11 + 0, value = "ResteasyViolationException has invalid format: %s")
34 String exceptionHasInvalidFormat(String line);
35
36 @Message(id = BASE_VALIDATOR_11 + 25, value = "Unable to parse ResteasyViolationException")
37 String unableToParseException();
38
39 @Message(id = BASE_VALIDATOR_11 + 30, value = "unexpected path node type: %s")
40 String unexpectedPathNode(ElementKind kind);
41
42 @Message(id = BASE_VALIDATOR_11 + 35, value = "unexpected path node type in method violation: %s")
43 String unexpectedPathNodeViolation(ElementKind kind);
44
45 @Message(id = BASE_VALIDATOR_11 + 40, value = "unexpected violation type: %s")
46 String unexpectedViolationType(ConstraintType.Type type);
47
48 @Message(id = BASE_VALIDATOR_11 + 45, value = "unknown object passed as constraint violation: %s")
49 String unknownObjectPassedAsConstraintViolation(Object o);
2950
3051 @Message(id = BASE_ASYNC + 0, value = "-- already canceled")
3152 String alreadyCanceled();
6990 @Message(id = BASE + 15, value = "application param was null")
7091 String applicationParamNull();
7192
72 @Message(id = BASE + 17, value = "ClassCastException: attempting to cast {0} to {1}", format=Format.MESSAGE_FORMAT)
73 String attemptingToCast(URL from, URL to);
74
7593 @Message(id = BASE + 20, value = "Bad arguments passed to %s")
7694 String badArguments(String methodName);
7795
199217 String couldNotIntrospectClass(String className);
200218
201219 @Message(id = BASE + 230, value = "Could not match up an implementation for LoggerType: %s")
202 String couldNotMatchUpLoggerTypeImplementation(Class<?> loggerType);
220 String couldNotMatchUpLoggerTypeImplementation(LoggerType loggerType);
203221
204222 @Message(id = BASE + 235, value = "Could not process method %s")
205223 String couldNotProcessMethod(Method method);
710728
711729 @Message(id = BASE + 1070, value = "Wrong password for: %s")
712730 String wrongPassword(String user);
731
732 @Message(id = BASE + 1080, value = "WebTarget is not set for creating SseEventSource")
733 String webTargetIsNotSetForEventSource();
734 @Message(id = BASE + 1081, value = "EventSource is not ready to open")
735 String eventSourceIsNotReadyForOpen();
736 @Message(id = BASE + 1082, value = "No suitable message body writer for class : %s")
737 String notFoundMBW(String className);
738 @Message(id = BASE + 1083, value = "Sever sent event feature requries HttpServlet30Dispatcher")
739 String asyncServletIsRequired();
740 @Message(id = BASE + 1084, value = "Failed to read SseEvent")
741 String readEventException();
742 @Message(id = BASE + 1085, value = "%s is not set for OutboundSseEvent builder")
743 String nullValueSetToCreateOutboundSseEvent(String field);
744 @Message(id = BASE + 1086, value = "Failed to write data to InBoundSseEvent")
745 String failedToWriteDataToInboudEvent();
746 @Message(id = BASE + 1087, value = "No suitable message body reader for class : %s")
747 String notFoundMBR(String className);
748 @Message(id = BASE + 1088, value = "Failed to read data from InboundSseEvent")
749 String failedToReadData();
750 @Message(id = BASE + 1089, value = "Failed to create SseEventOutput")
751 String failedToCreateSseEventOutput();
752
753 @Message(id = BASE + 1090, value = "Unable to instantiate AsyncResponseProvider")
754 String unableToInstantiateAsyncResponseProvider();
755 @Message(id = BASE + 1091, value = "Unable to instantiate AsyncStreamProvider")
756 String unableToInstantiateAsyncStreamProvider();
757 @Message(id = BASE + 1092, value = "SseEventSink is closed")
758 String sseEventSinkIsClosed();
713759 }
4141 {
4242 protected Object entity;
4343 protected int status = HttpResponseCodes.SC_OK;
44 protected String reason = "Unknown Code";
4445 protected Headers<Object> metadata = new Headers<Object>();
4546 protected Annotation[] annotations;
4647 protected Class entityClass;
4748 protected Type genericType;
4849 protected HeaderValueProcessor processor;
49 protected boolean isClosed;
50 protected volatile boolean isClosed;
5051
5152 public BuiltResponse()
5253 {
5354 }
5455
5556 public BuiltResponse(int status, Headers<Object> metadata, Object entity, Annotation[] entityAnnotations)
57 {
58 this(status, null, metadata, entity, entityAnnotations);
59 }
60
61 public BuiltResponse(int status, String reason, Headers<Object> metadata, Object entity, Annotation[] entityAnnotations)
5662 {
5763 setEntity(entity);
5864 this.status = status;
5965 this.metadata = metadata;
6066 this.annotations = entityAnnotations;
67 if (reason != null) {
68 this.reason = reason;
69 }
6170 }
6271
6372 public Class getEntityClass()
8796 public int getStatus()
8897 {
8998 return status;
99 }
100
101 public String getReasonPhrase()
102 {
103 return reason;
90104 }
91105
92106 @Override
112126 @Override
113127 public String getReasonPhrase()
114128 {
115 return "Unknown Code";
129 return reason;
116130 }
117131 };
118132 }
152166 public void setStatus(int status)
153167 {
154168 this.status = status;
169 }
170
171 public void setReasonPhrase(String reason)
172 {
173 this.reason = reason;
155174 }
156175
157176 public void setMetadata(MultivaluedMap<String, Object> metadata)
1717 public class LinkBuilderImpl implements Link.Builder
1818 {
1919 /**
20 * A map for all the link parameters such as "rel", "type", etc.
20 * A map for all the link parameters such as "rel", "type", etc.
2121 */
2222 protected final Map<String, String> map = new HashMap<String, String>();
2323 protected UriBuilder uriBuilder;
9595 public Link build(Object... values) throws UriBuilderException
9696 {
9797 if (values == null) throw new IllegalArgumentException(Messages.MESSAGES.valuesParamWasNull());
98 return new LinkImpl(this.uriBuilder.build(values), this.map);
98 URI built = null;
99 if (uriBuilder == null)
100 {
101 built = baseUri;
102 }
103 else
104 {
105 built = this.uriBuilder.build(values);
106 }
107 if (!built.isAbsolute() && baseUri != null)
108 {
109 built = baseUri.resolve(built);
110 }
111 return new LinkImpl(built, this.map);
99112 }
100113
101114 @Override
122135 this.baseUri = URI.create(uri);
123136 return this;
124137 }
125 }
138 }
3232
3333 LinkImpl(URI uri, Map<String, String> map)
3434 {
35 this.uri = uri;
36 this.map = map.isEmpty() ? Collections.<String, String> emptyMap() : Collections
37 .unmodifiableMap(new HashMap<String, String>(map));
38 }
35 this.uri = uri;
36 this.map = map.isEmpty() ? Collections.<String, String> emptyMap() : Collections
37 .unmodifiableMap(new HashMap<String, String>(map));
38 }
3939
4040 @Override
4141 public URI getUri() {
1212 import javax.ws.rs.core.MediaType;
1313 import javax.ws.rs.core.MultivaluedMap;
1414 import javax.ws.rs.core.NewCookie;
15
1516 import javax.ws.rs.core.Response;
1617 import javax.ws.rs.core.Variant;
1718 import java.lang.annotation.Annotation;
3435 protected Object entity;
3536 protected Annotation[] entityAnnotations;
3637 protected int status = -1;
38 protected String reasonPhrase;
3739 protected Headers<Object> metadata = new Headers<Object>();
3840
3941 @Override
4143 {
4244 if (status == -1 && entity == null) status = 204;
4345 else if (status == -1) status = 200;
44 return new BuiltResponse(status, metadata, entity, entityAnnotations);
46 return new BuiltResponse(status, reasonPhrase, metadata, entity, entityAnnotations);
4547 }
4648
4749 @Override
5658 }
5759
5860 @Override
61 public Response.ResponseBuilder status(int status, String reasonPhrase)
62 {
63 this.status = status;
64 this.reasonPhrase = reasonPhrase;
65 return this;
66 }
67
68 @Override
5969 public Response.ResponseBuilder status(int status)
6070 {
61 this.status = status;
62 return this;
71 return status(status, null);
6372 }
6473
6574 @Override
391400 metadata.putAll(headers);
392401 return this;
393402 }
403
394404 }
8888 public static final Pattern opaqueUri = Pattern.compile("^([^:/?#]+):([^/].*)");
8989 public static final Pattern hierarchicalUri = Pattern.compile("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
9090 private static final Pattern hostPortPattern = Pattern.compile("([^/:]+):(\\d+)");
91 private static final Pattern squareHostBrackets = Pattern.compile( "(\\[(([0-9A-Fa-f]{0,4}:){2,7})([0-9A-Fa-f]{0,4})%?.*\\]):(\\d+)" );
9192
9293 public static boolean compare(String s1, String s2)
9394 {
188189 host = host.substring(at + 1);
189190 this. userInfo = user;
190191 }
192
191193 Matcher hostPortMatch = hostPortPattern.matcher(host);
192194 if (hostPortMatch.matches())
193195 {
194196 this.host = hostPortMatch.group(1);
195197 int val = 0;
196 try {
198 try
199 {
197200 this.port = Integer.parseInt(hostPortMatch.group(2));
198 }
199 catch (NumberFormatException e) {
201 } catch (NumberFormatException e)
202 {
200203 throw new IllegalArgumentException(Messages.MESSAGES.illegalUriTemplate(uriTemplate), e);
201204 }
202 }
203 else
204 {
205 } else
206 {
207 if (host.startsWith("["))
208 {
209 // Must support an IPv6 hostname of format "[::1]" or [0:0:0:0:0:0:0:0]
210 // and IPv6 link-local format [fe80::1234%1] [ff08::9abc%interface10]
211 Matcher bracketsMatch = squareHostBrackets.matcher(host);
212 if (bracketsMatch.matches())
213 {
214 host = bracketsMatch.group(1);
215 try
216 {
217 this.port = Integer.parseInt(bracketsMatch.group(5));
218 } catch (NumberFormatException e)
219 {
220 throw new IllegalArgumentException(Messages.MESSAGES.illegalUriTemplate(uriTemplate), e);
221 }
222 }
223 }
205224 this.host = host;
206225 }
207226 }
630649
631650 public static Matcher createUriParamMatcher(String string)
632651 {
633 Matcher matcher = PathHelper.URI_PARAM_PATTERN.matcher(PathHelper.replaceEnclosedCurlyBraces(string));
652 Matcher matcher = PathHelper.URI_PARAM_PATTERN.matcher(PathHelper.replaceEnclosedCurlyBracesCS(string));
634653 return matcher;
635654 }
636655
751770
752771 private void addToPathParamList(List<String> params, HashSet<String> set, String string)
753772 {
754 Matcher matcher = PathHelper.URI_PARAM_PATTERN.matcher(PathHelper.replaceEnclosedCurlyBraces(string));
773 Matcher matcher = PathHelper.URI_PARAM_PATTERN.matcher(PathHelper.replaceEnclosedCurlyBracesCS(string));
755774 while (matcher.find())
756775 {
757776 String param = matcher.group(1);
820839 ArrayList<String> pathParams = new ArrayList<String>();
821840 boolean foundParam = false;
822841
823 String pathWithoutEnclosedCurlyBraces = PathHelper.replaceEnclosedCurlyBraces(this.path);
842 CharSequence pathWithoutEnclosedCurlyBraces = PathHelper.replaceEnclosedCurlyBracesCS(this.path);
824843 Matcher matcher = PathHelper.URI_TEMPLATE_PATTERN.matcher(pathWithoutEnclosedCurlyBraces);
825844 StringBuilder newSegment = new StringBuilder();
826845 int from = 0;
10821101 if (templateValues == null) throw new IllegalArgumentException(Messages.MESSAGES.templateValuesParamNull());
10831102 if (templateValues.containsKey(null)) throw new IllegalArgumentException(Messages.MESSAGES.mapKeyNull());
10841103 String str = buildString(templateValues, false, true, true);
1085 return uriTemplate(str);
1104 return fromTemplate(str);
10861105 }
10871106
10881107 @Override
10931112 HashMap<String, Object> vals = new HashMap<String, Object>();
10941113 vals.put(name, value);
10951114 String str = buildString(vals, false, true, encodeSlashInPath);
1096 return uriTemplate(str);
1115 return fromTemplate(str);
10971116 }
10981117
10991118 @Override
11041123 HashMap<String, Object> vals = new HashMap<String, Object>();
11051124 vals.put(name, value);
11061125 String str = buildString(vals, true, true, true);
1107 return uriTemplate(str);
1126 return fromTemplate(str);
11081127 }
11091128
11101129 @Override
11131132 if (templateValues == null) throw new IllegalArgumentException(Messages.MESSAGES.templateValuesParamNull());
11141133 if (templateValues.containsKey(null)) throw new IllegalArgumentException(Messages.MESSAGES.mapKeyNull());
11151134 String str = buildString(templateValues, false, true, encodeSlashInPath);
1116 return uriTemplate(str);
1135 return fromTemplate(str);
11171136 }
11181137
11191138 @Override
11221141 if (templateValues == null) throw new IllegalArgumentException(Messages.MESSAGES.templateValuesParamNull());
11231142 if (templateValues.containsKey(null)) throw new IllegalArgumentException(Messages.MESSAGES.mapKeyNull());
11241143 String str = buildString(templateValues, true, true, true);
1125 return uriTemplate(str);
1144 return fromTemplate(str);
11261145 }
11271146 }
0 package org.jboss.resteasy.spi;
1
2 import java.util.concurrent.CompletionStage;
3
4 public interface AsyncResponseProvider<T> {
5 public CompletionStage toCompletionStage(T asyncResponse);
6 }
0 package org.jboss.resteasy.spi;
1
2 import org.reactivestreams.Publisher;
3
4 public interface AsyncStreamProvider<T> {
5 public Publisher toAsyncStream(T asyncResponse);
6 }
1414 public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
1515 public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
1616 public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
17 public static final String VARY = "Vary";
1718 }
+0
-25
resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/DecoratorProcessor.java less more
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.MediaType;
3 import java.lang.annotation.Annotation;
4
5 /**
6 * Part of a generic decorator framework.
7 * <p/>
8 * Decorate a target. For example, decorate a JAXB Marshaller with property values.
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 public interface DecoratorProcessor<T, A extends Annotation>
14 {
15 /**
16 * @param target i.e. a Marshaller instance
17 * @param annotation the annotation that triggered the decorator
18 * @param type
19 * @param annotations
20 * @param mediaType
21 * @return should never return null
22 */
23 T decorate(T target, A annotation, Class type, Annotation[] annotations, MediaType mediaType);
24 }
+0
-249
resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/FactoryFinder.java less more
0 package org.jboss.resteasy.spi;
1
2 import java.io.BufferedReader;
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.security.AccessController;
9 import java.security.PrivilegedAction;
10 import java.security.PrivilegedActionException;
11 import java.security.PrivilegedExceptionAction;
12 import java.util.Properties;
13 import java.util.logging.Level;
14 import java.util.logging.Logger;
15
16 final class FactoryFinder {
17
18 private static final Logger LOGGER = Logger.getLogger(FactoryFinder.class.getName());
19 private static final String RESTEASY_JAXRS_API_MODULE = "org.jboss.resteasy.resteasy-jaxrs-api";
20
21 private FactoryFinder() {
22 // prevents instantiation
23 }
24
25 static ClassLoader getContextClassLoader() {
26 return AccessController.doPrivileged(
27 new PrivilegedAction<ClassLoader>() {
28
29 @Override
30 public ClassLoader run() {
31 ClassLoader cl = null;
32 try {
33 cl = Thread.currentThread().getContextClassLoader();
34 } catch (SecurityException ex) {
35 LOGGER.log(
36 Level.WARNING,
37 "Unable to get context classloader instance.",
38 ex);
39 }
40 return cl;
41 }
42 });
43 }
44
45 /**
46 * Creates an instance of the specified class using the specified
47 * {@code ClassLoader} object.
48 *
49 * @param className name of the class to be instantiated.
50 * @param classLoader class loader to be used.
51 * @return instance of the specified class.
52 * @throws ClassNotFoundException if the given class could not be found
53 * or could not be instantiated.
54 */
55 private static Object newInstance(final String className,
56 final ClassLoader classLoader) throws ClassNotFoundException {
57 try {
58 Class spiClass;
59 if (classLoader == null) {
60 spiClass = Class.forName(className);
61 } else {
62 try {
63 spiClass = Class.forName(className, false, classLoader);
64 } catch (ClassNotFoundException ex) {
65 LOGGER.log(
66 Level.FINE,
67 "Unable to load provider class " + className
68 + " using custom classloader " + classLoader.getClass().getName()
69 + " trying again with current classloader.",
70 ex);
71 spiClass = Class.forName(className);
72 }
73 }
74 return spiClass.newInstance();
75 } catch (ClassNotFoundException x) {
76 throw x;
77 } catch (Exception x) {
78 throw new ClassNotFoundException("Provider " + className + " could not be instantiated: " + x, x);
79 }
80 }
81
82 /**
83 * Finds the implementation {@code Class} object for the given
84 * factory name, or if that fails, finds the {@code Class} object
85 * for the given fallback class name. The arguments supplied MUST be
86 * used in order. If using the first argument is successful, the second
87 * one will not be used.
88 * <p>
89 * This method is package private so that this code can be shared.
90 * </p>
91 *
92 * @param factoryId the name of the factory to find, which is
93 * a system property.
94 * @param fallbackClassName the implementation class name, which is
95 * to be used only if nothing else.
96 * is found; {@code null} to indicate that
97 * there is no fallback class name.
98 * @return the {@code Class} object of the specified message factory;
99 * may not be {@code null}.
100 * @throws ClassNotFoundException if there is an error.
101 */
102 static Object find(final String factoryId, final String fallbackClassName) throws ClassNotFoundException {
103 ClassLoader classLoader = getContextClassLoader();
104
105 String serviceId = "META-INF/services/" + factoryId;
106 BufferedReader rd = null;
107 InputStream is = null;
108 // try to find services in CLASSPATH
109 try {
110 if (classLoader == null) {
111 is = ClassLoader.getSystemResourceAsStream(serviceId);
112 } else {
113 is = classLoader.getResourceAsStream(serviceId);
114 }
115
116 if (is != null) {
117 rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
118
119 String factoryClassName = rd.readLine();
120
121 if (factoryClassName != null && !"".equals(factoryClassName)) {
122 return newInstance(factoryClassName, classLoader);
123 }
124 }
125 } catch (Exception ex) {
126 LOGGER.log(Level.FINER, "Failed to load service " + factoryId + " from " + serviceId, ex);
127 } finally {
128 try {
129 if (rd != null)
130 rd.close();
131
132 if (is != null)
133 is.close();
134 } catch (IOException ex) {
135 LOGGER.log(Level.FINER, "Failed to close BufferedReader/InputStream.", ex);
136 }
137 }
138
139 FileInputStream fis = null;
140 // try to read from $java.home/lib/jaxrs.properties
141 try {
142 String javah = System.getProperty("java.home");
143 String configFile = javah + File.separator
144 + "lib" + File.separator + "jaxrs.properties";
145 File f = new File(configFile);
146 if (f.exists()) {
147 Properties props = new Properties();
148 fis = new FileInputStream(f);
149 props.load(fis);
150 String factoryClassName = props.getProperty(factoryId);
151 return newInstance(factoryClassName, classLoader);
152 }
153 } catch (Exception ex) {
154 LOGGER.log(Level.FINER, "Failed to load service " + factoryId
155 + " from $java.home/lib/jaxrs.properties", ex);
156 } finally {
157 try {
158 if (fis != null)
159 fis.close();
160 } catch (IOException ex) {
161 LOGGER.log(Level.FINER, "Failed to close FileInputStream.", ex);
162 }
163 }
164
165 // Use the system property
166 try {
167 String systemProp = System.getProperty(factoryId);
168 if (systemProp != null) {
169 return newInstance(systemProp, classLoader);
170 }
171 } catch (SecurityException se) {
172 LOGGER.log(Level.FINER, "Failed to load service " + factoryId
173 + " from a system property", se);
174 }
175
176 ClassLoader moduleClassLoader = getModuleClassLoader();
177 rd = null;
178 is = null;
179 if (moduleClassLoader != null) {
180 try {
181 is = moduleClassLoader.getResourceAsStream(serviceId);
182
183 if( is!=null ) {
184 rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
185
186 String factoryClassName = rd.readLine();
187
188 if (factoryClassName != null &&
189 ! "".equals(factoryClassName)) {
190 return newInstance(factoryClassName, moduleClassLoader);
191 }
192 }
193 } catch( Exception ex ) {
194 } finally {
195 try {
196 if (rd != null)
197 rd.close();
198
199 if (is != null)
200 is.close();
201 } catch (IOException ex) {
202 LOGGER.log(Level.FINER, "Failed to close BufferedReader/InputStream.", ex);
203 }
204 }
205 }
206
207 if (fallbackClassName == null) {
208 throw new ClassNotFoundException(
209 "Provider for " + factoryId + " cannot be found", null);
210 }
211
212 return newInstance(fallbackClassName, classLoader);
213 }
214
215 private static ClassLoader getModuleClassLoader() {
216 try {
217 final Class<?> moduleClass = Class.forName("org.jboss.modules.Module");
218 final Class<?> moduleIdentifierClass = Class.forName("org.jboss.modules.ModuleIdentifier");
219 final Class<?> moduleLoaderClass = Class.forName("org.jboss.modules.ModuleLoader");
220 final Object moduleLoader;
221 final SecurityManager sm = System.getSecurityManager();
222 if (sm == null) {
223 moduleLoader = moduleClass.getMethod("getBootModuleLoader").invoke(null);
224 } else {
225 try {
226 moduleLoader = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
227 public Object run() throws Exception {
228 return moduleClass.getMethod("getBootModuleLoader").invoke(null);
229 }
230 });
231 } catch (PrivilegedActionException pae) {
232 throw pae.getException();
233 }
234 }
235 Object moduleIdentifier = moduleIdentifierClass.getMethod("create", String.class).invoke(null, RESTEASY_JAXRS_API_MODULE);
236 Object module = moduleLoaderClass.getMethod("loadModule", moduleIdentifierClass).invoke(moduleLoader, moduleIdentifier);
237 return (ClassLoader)moduleClass.getMethod("getClassLoader").invoke(module);
238 } catch (ClassNotFoundException e) {
239 //ignore, JBoss Modules might not be available at all
240 return null;
241 } catch (RuntimeException e) {
242 throw e;
243 } catch (Exception e) {
244 throw new RuntimeException(e);
245 }
246 }
247
248 }
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Unauthorized (403) is encountered
6 *
7 * @deprecated Replaced by javax.ws.rs.ForbiddenException in jaxrs-api module.
8 *
9 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
10 * @see javax.ws.rs.ForbiddenException
11 */
12 @Deprecated
13 public class ForbiddenException extends LoggableFailure
14 {
15 public ForbiddenException()
16 {
17 super(403);
18 }
19
20 public ForbiddenException(String s)
21 {
22 super(s, 403);
23 }
24
25 public ForbiddenException(String s, Response response)
26 {
27 super(s, response);
28 }
29
30 public ForbiddenException(String s, Throwable throwable, Response response)
31 {
32 super(s, throwable, response);
33 }
34
35 public ForbiddenException(String s, Throwable throwable)
36 {
37 super(s, throwable, 403);
38 }
39
40 public ForbiddenException(Throwable throwable)
41 {
42 super(throwable, 403);
43 }
44
45 public ForbiddenException(Throwable throwable, Response response)
46 {
47 super(throwable, response);
48 }
49
50
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Unauthorized (403) is encountered
6 *
7 * @deprecated Replaced by javax.ws.rs.ForbiddenException in jaxrs-api module.
8 *
9 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
10 * @see javax.ws.rs.ForbiddenException
11 */
12 @Deprecated
13 public class ForbiddenException extends LoggableFailure
14 {
15 public ForbiddenException()
16 {
17 super(403);
18 }
19
20 public ForbiddenException(String s)
21 {
22 super(s, 403);
23 }
24
25 public ForbiddenException(String s, Response response)
26 {
27 super(s, response);
28 }
29
30 public ForbiddenException(String s, Throwable throwable, Response response)
31 {
32 super(s, throwable, response);
33 }
34
35 public ForbiddenException(String s, Throwable throwable)
36 {
37 super(s, throwable, 403);
38 }
39
40 public ForbiddenException(Throwable throwable)
41 {
42 super(throwable, 403);
43 }
44
45 public ForbiddenException(Throwable throwable, Response response)
46 {
47 super(throwable, response);
48 }
49
50
5151 }
11
22 import javax.ws.rs.core.MultivaluedMap;
33 import javax.ws.rs.core.NewCookie;
4
5 import java.io.Closeable;
64 import java.io.IOException;
75 import java.io.OutputStream;
86
1210 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
1311 * @version $Revision: 1 $
1412 */
15 public interface HttpResponse extends Closeable
13 public interface HttpResponse
1614 {
1715 int getStatus();
1816
3533 * reset status and headers. Will fail if response is committed
3634 */
3735 void reset();
38
39 default void close() throws IOException {
40 // RESTEASY-1650
41 getOutputStream().close();
42 }
36
37 void flushBuffer() throws IOException;
4338
4439 }
88 import java.lang.annotation.Annotation;
99 import java.lang.reflect.AccessibleObject;
1010 import java.lang.reflect.Constructor;
11 import java.lang.reflect.Method;
1112 import java.lang.reflect.Type;
1213
1314 /**
0 package org.jboss.resteasy.spi;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.specimpl.LinkBuilderImpl;
5 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
6
7 import javax.ws.rs.core.MultivaluedMap;
8 import java.util.List;
9 import java.util.Map;
10
11 /**
12 * Implementation of <a href="http://tools.ietf.org/html/draft-nottingham-http-link-header-06">Link Headers v6</a>
13 *
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 *
17 * @deprecated Replaced by javax.ws.rs.core.Link in jaxrs-api module.
18 *
19 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
20 * @see javax.ws.rs.core.Link
21 */
22 @Deprecated
23 public class Link
24 {
25 protected String title;
26 protected String relationship;
27 protected String href;
28 protected String type;
29 protected MultivaluedMap<String, String> extensions = new MultivaluedMapImpl<String, String>();
30 protected ClientExecutor executor;
31
32 public Link()
33 {
34 }
35
36 public Link(String title, String relationship, String href, String type, MultivaluedMap<String, String> extensions)
37 {
38 this.relationship = relationship;
39 this.href = href;
40 this.type = type;
41 this.title = title;
42 if (extensions != null) this.extensions = extensions;
43 }
44
45 public javax.ws.rs.core.Link toJaxrsLink()
46 {
47 javax.ws.rs.core.Link.Builder builder = new LinkBuilderImpl();
48 builder.rel(getRelationship());
49 builder.title(getTitle());
50 builder.type(getType());
51 builder.uri(getHref());
52 for (Map.Entry<String, List<String>> entry : getExtensions().entrySet())
53 {
54 for (String val : entry.getValue())
55 {
56 builder.param(entry.getKey(), val);
57 }
58 }
59 return builder.build();
60 }
61
62 public String getRelationship()
63 {
64 return relationship;
65 }
66
67 public void setRelationship(String relationship)
68 {
69 this.relationship = relationship;
70 }
71
72 public String getHref()
73 {
74 return href;
75 }
76
77 public void setHref(String href)
78 {
79 this.href = href;
80 }
81
82 public String getType()
83 {
84 return type;
85 }
86
87 public void setType(String type)
88 {
89 this.type = type;
90 }
91
92 public String getTitle()
93 {
94 return title;
95 }
96
97 public void setTitle(String title)
98 {
99 this.title = title;
100 }
101
102 public MultivaluedMap<String, String> getExtensions()
103 {
104 return extensions;
105 }
106
107 public ClientExecutor getExecutor()
108 {
109 return executor;
110 }
111
112 public void setExecutor(ClientExecutor executor)
113 {
114 this.executor = executor;
115 }
116
117 public ClientRequest request()
118 {
119 if (executor != null)
120 {
121 return new ClientRequest(href, executor);
122 }
123 else
124 {
125 return new ClientRequest(href);
126 }
127 }
128
129 public ClientRequest request(ClientExecutor executor)
130 {
131 return new ClientRequest(href, executor);
132 }
133
134 public String toString()
135 {
136 StringBuffer buf = new StringBuffer("<");
137 buf.append(href).append(">");
138 if (relationship != null)
139 {
140 buf.append("; rel=\"").append(relationship).append("\"");
141 }
142 if (type != null)
143 {
144 buf.append("; type=\"").append(type).append("\"");
145 }
146 if (title != null)
147 {
148 buf.append("; title=\"").append(title).append("\"");
149 }
150 for (String key : getExtensions().keySet())
151 {
152 List<String> values = getExtensions().get(key);
153 for (String val : values)
154 {
155 buf.append("; ").append(key).append("=\"").append(val).append("\"");
156 }
157 }
158 return buf.toString();
159 }
160
161 }
00 package org.jboss.resteasy.spi;
11
22 import org.jboss.resteasy.plugins.delegates.LinkHeaderDelegate;
3 import org.jboss.resteasy.specimpl.LinkBuilderImpl;
43
54 import java.util.ArrayList;
65 import java.util.HashMap;
76 import java.util.List;
87 import java.util.Map;
9 import javax.ws.rs.core.Link;
108
119 /**
1210 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
2624
2725 public LinkHeader addLink(final String title, final String rel, final String href, final String type)
2826 {
29 final Link link = new LinkBuilderImpl().uri(href).rel(rel).title(title).type(type).build();
27 final Link link = new Link(title, rel, href, type, null);
3028 return addLink(link);
3129 }
3230
2727 for (String val : values)
2828 {
2929 LinkHeader linkHeader = new LinkHeaderDelegate().fromString(val);
30 for (Link link : linkHeader.getLinks())
30 for (org.jboss.resteasy.spi.Link link : linkHeader.getLinks())
3131 {
32 addLink(link);
32 addLink(link.toJaxrsLink());
3333 }
3434 }
3535 return this;
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Method Not Allowed (405) is encountered
6 * JAX-RS now has this exception
7 *
8 * @deprecated Replaced by javax.ws.rs.NotAllowedException in jaxrs-api module.
9 *
10 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
11 * @see javax.ws.rs.NotAllowedException
12 */
13 @Deprecated
14 public class MethodNotAllowedException extends LoggableFailure
15 {
16
17 public MethodNotAllowedException(String s)
18 {
19 super(s, 405);
20 }
21
22 public MethodNotAllowedException(String s, Response response)
23 {
24 super(s, response);
25 }
26
27 public MethodNotAllowedException(String s, Throwable throwable, Response response)
28 {
29 super(s, throwable, response);
30 }
31
32 public MethodNotAllowedException(String s, Throwable throwable)
33 {
34 super(s, throwable, 405);
35 }
36
37 public MethodNotAllowedException(Throwable throwable)
38 {
39 super(throwable, 405);
40 }
41
42 public MethodNotAllowedException(Throwable throwable, Response response)
43 {
44 super(throwable, response);
45 }
46
47
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Method Not Allowed (405) is encountered
6 * JAX-RS now has this exception
7 *
8 * @deprecated Replaced by javax.ws.rs.NotAllowedException in jaxrs-api module.
9 *
10 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
11 * @see javax.ws.rs.NotAllowedException
12 */
13 @Deprecated
14 public class MethodNotAllowedException extends LoggableFailure
15 {
16
17 public MethodNotAllowedException(String s)
18 {
19 super(s, 405);
20 }
21
22 public MethodNotAllowedException(String s, Response response)
23 {
24 super(s, response);
25 }
26
27 public MethodNotAllowedException(String s, Throwable throwable, Response response)
28 {
29 super(s, throwable, response);
30 }
31
32 public MethodNotAllowedException(String s, Throwable throwable)
33 {
34 super(s, throwable, 405);
35 }
36
37 public MethodNotAllowedException(Throwable throwable)
38 {
39 super(throwable, 405);
40 }
41
42 public MethodNotAllowedException(Throwable throwable, Response response)
43 {
44 super(throwable, response);
45 }
46
47
4848 }
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Not Acceptable (406) is encountered
6 * JAX-RS now has this exception
7 *
8 * @deprecated Replaced by javax.ws.rs.NotAcceptableException in jaxrs-api module.
9 *
10 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
11 * @see javax.ws.rs.NotAcceptableException
12 */
13 @Deprecated
14 public class NotAcceptableException extends LoggableFailure
15 {
16 public NotAcceptableException(String s)
17 {
18 super(s, 406);
19 }
20
21 public NotAcceptableException(String s, Response response)
22 {
23 super(s, response);
24 }
25
26 public NotAcceptableException(String s, Throwable throwable, Response response)
27 {
28 super(s, throwable, response);
29 }
30
31 public NotAcceptableException(String s, Throwable throwable)
32 {
33 super(s, throwable, 406);
34 }
35
36 public NotAcceptableException(Throwable throwable)
37 {
38 super(throwable, 406);
39 }
40
41 public NotAcceptableException(Throwable throwable, Response response)
42 {
43 super(throwable, response);
44 }
45
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Not Acceptable (406) is encountered
6 * JAX-RS now has this exception
7 *
8 * @deprecated Replaced by javax.ws.rs.NotAcceptableException in jaxrs-api module.
9 *
10 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
11 * @see javax.ws.rs.NotAcceptableException
12 */
13 @Deprecated
14 public class NotAcceptableException extends LoggableFailure
15 {
16 public NotAcceptableException(String s)
17 {
18 super(s, 406);
19 }
20
21 public NotAcceptableException(String s, Response response)
22 {
23 super(s, response);
24 }
25
26 public NotAcceptableException(String s, Throwable throwable, Response response)
27 {
28 super(s, throwable, response);
29 }
30
31 public NotAcceptableException(String s, Throwable throwable)
32 {
33 super(s, throwable, 406);
34 }
35
36 public NotAcceptableException(Throwable throwable)
37 {
38 super(throwable, 406);
39 }
40
41 public NotAcceptableException(Throwable throwable, Response response)
42 {
43 super(throwable, response);
44 }
45
4646 }
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Not Found (404) is encountered
6 *
7 * JAX-RS now has this exception
8 *
9 * @deprecated Replaced by javax.ws.rs.NotFoundException in jaxrs-api module.
10 *
11 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
12 * @see javax.ws.rs.NotFoundException
13 */
14 @Deprecated
15 public class NotFoundException extends Failure
16 {
17
18 public NotFoundException(String s)
19 {
20 super(s, 404);
21 }
22
23 public NotFoundException(String s, Response response)
24 {
25 super(s, response);
26 }
27
28 public NotFoundException(String s, Throwable throwable, Response response)
29 {
30 super(s, throwable, response);
31 }
32
33 public NotFoundException(String s, Throwable throwable)
34 {
35 super(s, throwable, 404);
36 }
37
38 public NotFoundException(Throwable throwable)
39 {
40 super(throwable, 404);
41 }
42
43 public NotFoundException(Throwable throwable, Response response)
44 {
45 super(throwable, response);
46 }
47
48
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Not Found (404) is encountered
6 *
7 * JAX-RS now has this exception
8 *
9 * @deprecated Replaced by javax.ws.rs.NotFoundException in jaxrs-api module.
10 *
11 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
12 * @see javax.ws.rs.NotFoundException
13 */
14 @Deprecated
15 public class NotFoundException extends Failure
16 {
17
18 public NotFoundException(String s)
19 {
20 super(s, 404);
21 }
22
23 public NotFoundException(String s, Response response)
24 {
25 super(s, response);
26 }
27
28 public NotFoundException(String s, Throwable throwable, Response response)
29 {
30 super(s, throwable, response);
31 }
32
33 public NotFoundException(String s, Throwable throwable)
34 {
35 super(s, throwable, 404);
36 }
37
38 public NotFoundException(Throwable throwable)
39 {
40 super(throwable, 404);
41 }
42
43 public NotFoundException(Throwable throwable, Response response)
44 {
45 super(throwable, response);
46 }
47
48
4949 }
104104 void addJndiResource(String jndiName, ResourceClass resourceClass);
105105
106106 void addJndiResource(String jndiName, ResourceClass resourceClass, String basePath);
107
108 void checkAmbiguousUri();
107109 }
3434
3535 void setMethod(ResourceMethodInvoker method);
3636
37 void complete();
38
39 void completionCallbacks(Throwable throwable);
3740 }
2424 import javax.ws.rs.core.Feature;
2525 import javax.ws.rs.core.FeatureContext;
2626
27 import java.lang.reflect.Method;
2827 import java.util.ArrayList;
2928 import java.util.HashMap;
3029 import java.util.List;
8180 @SuppressWarnings(value = "unchecked")
8281 public void start()
8382 {
83 try
84 {
85 startInternal();
86 }
87 finally
88 {
89 ThreadLocalResteasyProviderFactory.pop();
90 }
91 }
92
93 @SuppressWarnings(value = {"unchecked", "deprecation"})
94 protected void startInternal()
95 {
8496 // it is very important that each deployment create their own provider factory
8597 // this allows each WAR to have their own set of providers
86 if (providerFactory == null) providerFactory = ResteasyProviderFactory.newInstance();
98 if (providerFactory == null) providerFactory = new ResteasyProviderFactory();
8799 providerFactory.setRegisterBuiltins(registerBuiltin);
88100
89101 if (deploymentSensitiveFactoryEnabled)
99111 threadLocalProviderFactory = new ThreadLocalResteasyProviderFactory(providerFactory);
100112 ResteasyProviderFactory.setInstance(threadLocalProviderFactory);
101113 }
114 else
115 {
116 ThreadLocalResteasyProviderFactory.push(providerFactory);
117 }
118 }
119 else
120 {
121 ThreadLocalResteasyProviderFactory.push(providerFactory);
102122 }
103123 }
104124 else
201221 }
202222
203223 // Interceptor preferences should come before provider registration or builtin.
204
224
205225 if (interceptorPrecedences != null)
206226 {
207227 for (String precedence : interceptorPrecedences)
479499 {
480500 registry.addResourceFactory(factory);
481501 }
502 registry.checkAmbiguousUri();
482503 }
483504
484505 protected void registerJndiComponentResource(String resource)
00 package org.jboss.resteasy.spi;
11
2 import org.jboss.resteasy.annotations.interception.ClientInterceptor;
3 import org.jboss.resteasy.annotations.interception.DecoderPrecedence;
4 import org.jboss.resteasy.annotations.interception.EncoderPrecedence;
5 import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
6 import org.jboss.resteasy.annotations.interception.RedirectPrecedence;
7 import org.jboss.resteasy.annotations.interception.SecurityPrecedence;
8 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
9 import org.jboss.resteasy.client.core.ClientErrorInterceptor;
10 import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper;
11 import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper;
212 import org.jboss.resteasy.core.InjectorFactoryImpl;
313 import org.jboss.resteasy.core.MediaTypeMap;
4 import org.jboss.resteasy.core.interception.jaxrs.ClientResponseFilterRegistry;
5 import org.jboss.resteasy.core.interception.jaxrs.ContainerRequestFilterRegistry;
6 import org.jboss.resteasy.core.interception.jaxrs.ContainerResponseFilterRegistry;
7 import org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistry;
8 import org.jboss.resteasy.core.interception.jaxrs.ReaderInterceptorRegistry;
9 import org.jboss.resteasy.core.interception.jaxrs.WriterInterceptorRegistry;
14 import org.jboss.resteasy.core.interception.jaxrs.ClientRequestFilterRegistry;
15 import org.jboss.resteasy.core.interception.ClientResponseFilterRegistry;
16 import org.jboss.resteasy.core.interception.ContainerRequestFilterRegistry;
17 import org.jboss.resteasy.core.interception.ContainerResponseFilterRegistry;
18 import org.jboss.resteasy.core.interception.InterceptorRegistry;
19 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
20 import org.jboss.resteasy.core.interception.LegacyPrecedence;
21 import org.jboss.resteasy.core.interception.ReaderInterceptorRegistry;
22 import org.jboss.resteasy.core.interception.WriterInterceptorRegistry;
1023 import org.jboss.resteasy.plugins.delegates.CacheControlDelegate;
1124 import org.jboss.resteasy.plugins.delegates.CookieHeaderDelegate;
1225 import org.jboss.resteasy.plugins.delegates.DateDelegate;
2437 import org.jboss.resteasy.specimpl.ResponseBuilderImpl;
2538 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
2639 import org.jboss.resteasy.specimpl.VariantListBuilderImpl;
40 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
41 import org.jboss.resteasy.spi.interception.MessageBodyReaderInterceptor;
42 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
43 import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
44 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
2745 import org.jboss.resteasy.util.FeatureContextDelegate;
2846 import org.jboss.resteasy.util.PickConstructor;
2947 import org.jboss.resteasy.util.ThreadLocalStack;
3755 import javax.ws.rs.RuntimeType;
3856 import javax.ws.rs.client.ClientRequestFilter;
3957 import javax.ws.rs.client.ClientResponseFilter;
58 import javax.ws.rs.client.RxInvoker;
59 import javax.ws.rs.client.RxInvokerProvider;
4060 import javax.ws.rs.container.ContainerRequestFilter;
4161 import javax.ws.rs.container.ContainerResponseFilter;
4262 import javax.ws.rs.container.DynamicFeature;
6080 import java.lang.reflect.ParameterizedType;
6181 import java.lang.reflect.Type;
6282 import java.net.URI;
63 import java.net.URL;
6483 import java.util.ArrayList;
6584 import java.util.Collection;
6685 import java.util.Collections;
7190 import java.util.Locale;
7291 import java.util.Map;
7392 import java.util.Set;
93 import java.util.TreeSet;
94 import java.util.Map.Entry;
7495 import java.util.concurrent.ConcurrentHashMap;
7596 import java.util.concurrent.CopyOnWriteArrayList;
7697 import java.util.concurrent.CopyOnWriteArraySet;
83104 @SuppressWarnings("unchecked")
84105 public class ResteasyProviderFactory extends RuntimeDelegate implements Providers, HeaderValueProcessor, Configurable<ResteasyProviderFactory>, Configuration
85106 {
107 public static final boolean EE8_PREVIEW_MODE;
108 static {
109 boolean sseAvailable = false;
110 try
111 {
112 Class<?> sse = Class.forName("javax.ws.rs.sse.Sse");
113 sseAvailable = true;
114 }
115 catch (ClassNotFoundException e)
116 {
117 //ignore
118 }
119 EE8_PREVIEW_MODE = sseAvailable;
120 }
121
86122 /**
87123 * Allow us to sort message body implementations that are more specific for their types
88124 * i.e. MessageBodyWriter<Object> is less specific than MessageBodyWriter<String>.
99135
100136 public Class<?> template = null;
101137
102
103 private SortedKey(Class<?> intf, T reader, Class<?> readerClass, boolean isBuiltin)
138 public int priority = Priorities.USER;
139
140 protected SortedKey(Class<?> intf, T reader, Class<?> readerClass, int priority, boolean isBuiltin)
141 {
142 this(intf, reader, readerClass);
143 this.priority = priority;
144 this.isBuiltin = isBuiltin;
145 }
146
147 protected SortedKey(Class<?> intf, T reader, Class<?> readerClass, boolean isBuiltin)
104148 {
105149 this(intf, reader, readerClass);
106150 this.isBuiltin = isBuiltin;
107151 }
108152
109153
110 private SortedKey(Class<?> intf, T reader, Class<?> readerClass)
154 protected SortedKey(Class<?> intf, T reader, Class<?> readerClass)
111155 {
112156 this.readerClass = readerClass;
113157 this.obj = reader;
120164 {
121165 // Sort user provider before builtins
122166 if (this == tMessageBodyKey) return 0;
123 if (isBuiltin == tMessageBodyKey.isBuiltin) return 0;
167 if (isBuiltin == tMessageBodyKey.isBuiltin)
168 {
169 if (this.priority < tMessageBodyKey.priority)
170 {
171 return -1;
172 }
173 if (this.priority == tMessageBodyKey.priority)
174 {
175 return 0;
176 }
177 if (this.priority > tMessageBodyKey.priority)
178 {
179 return 1;
180 }
181 }
124182 if (isBuiltin) return 1;
125183 else return -1;
126184 }
128186 public Class<?> getType()
129187 {
130188 return template;
189 }
190
191 public T getObj() {
192 return obj;
193 }
194 }
195
196 protected static class ExtSortedKey<T> extends SortedKey<T>
197 {
198 protected ExtSortedKey(Class<?> intf, T reader, Class<?> readerClass, int priority, boolean isBuiltin)
199 {
200 super(intf, reader, readerClass, priority, isBuiltin);
201 }
202
203 protected ExtSortedKey(Class<?> intf, T reader, Class<?> readerClass, boolean isBuiltin)
204 {
205 super(intf, reader, readerClass, isBuiltin);
206 }
207
208 protected ExtSortedKey(Class<?> intf, T reader, Class<?> readerClass)
209 {
210 super(intf, reader, readerClass);
211 }
212
213 @Override
214 public int compareTo(SortedKey<T> tMessageBodyKey)
215 {
216 int c = super.compareTo(tMessageBodyKey);
217 if (c != 0)
218 {
219 return c;
220 }
221 if (this.obj == tMessageBodyKey.obj)
222 {
223 return 0;
224 }
225 return -1;
131226 }
132227 }
133228
141236 protected MediaTypeMap<SortedKey<MessageBodyWriter>> serverMessageBodyWriters;
142237 protected MediaTypeMap<SortedKey<MessageBodyReader>> clientMessageBodyReaders;
143238 protected MediaTypeMap<SortedKey<MessageBodyWriter>> clientMessageBodyWriters;
239 protected Map<Class<?>, SortedKey<ExceptionMapper>> sortedExceptionMappers;
144240 protected Map<Class<?>, ExceptionMapper> exceptionMappers;
241 protected Map<Class<?>, ClientExceptionMapper> clientExceptionMappers;
242 protected Map<Class<?>, AsyncResponseProvider> asyncResponseProviders;
243 protected Map<Class<?>, AsyncStreamProvider> asyncStreamProviders;
145244 protected Map<Class<?>, MediaTypeMap<SortedKey<ContextResolver>>> contextResolvers;
146245 protected Map<Class<?>, StringConverter> stringConverters;
246 protected Set<ExtSortedKey<ParamConverterProvider>> sortedParamConverterProviders;
147247 protected List<ParamConverterProvider> paramConverterProviders;
148248 protected Map<Class<?>, Class<? extends StringParameterUnmarshaller>> stringParameterUnmarshallers;
149249 protected Map<Class<?>, Map<Class<?>, Integer>> classContracts;
150250
151251 protected Map<Class<?>, HeaderDelegate> headerDelegates;
152252
253 protected LegacyPrecedence precedence;
153254 protected ReaderInterceptorRegistry serverReaderInterceptorRegistry;
154255 protected WriterInterceptorRegistry serverWriterInterceptorRegistry;
155256 protected ContainerRequestFilterRegistry containerRequestFilterRegistry;
156257 protected ContainerResponseFilterRegistry containerResponseFilterRegistry;
157258
259 protected ClientRequestFilterRegistry clientRequestFilterRegistry;
260
261 @Deprecated // variable is maintained for jaxrs-leagcy code support only
158262 protected JaxrsInterceptorRegistry<ClientRequestFilter> clientRequestFilters;
159263 protected ClientResponseFilterRegistry clientResponseFilters;
160264 protected ReaderInterceptorRegistry clientReaderInterceptorRegistry;
161265 protected WriterInterceptorRegistry clientWriterInterceptorRegistry;
266 protected InterceptorRegistry<ClientExecutionInterceptor> clientExecutionInterceptorRegistry;
267
268 protected List<ClientErrorInterceptor> clientErrorInterceptors;
162269
163270 protected boolean builtinsRegistered = false;
164271 protected boolean registerBuiltins = true;
196303
197304 /**
198305 * If local is true, copies components needed by client configuration,
199 * so that parent is not referenced.
306 * so that parent is not referenced.
200307 * @param parent
201308 * @param local
202309 */
210317 properties = new ConcurrentHashMap<String, Object>();
211318 properties.putAll(parent.getProperties());
212319 enabledFeatures = new CopyOnWriteArraySet<Feature>();
213
320
214321 if (local)
215322 {
216323 classContracts = new ConcurrentHashMap<Class<?>, Map<Class<?>, Integer>>();
240347 serverMessageBodyWriters = new MediaTypeMap<SortedKey<MessageBodyWriter>>();
241348 clientMessageBodyReaders = new MediaTypeMap<SortedKey<MessageBodyReader>>();
242349 clientMessageBodyWriters = new MediaTypeMap<SortedKey<MessageBodyWriter>>();
350 sortedExceptionMappers = new ConcurrentHashMap<Class<?>, SortedKey<ExceptionMapper>>();
243351 exceptionMappers = new ConcurrentHashMap<Class<?>, ExceptionMapper>();
352 clientExceptionMappers = new ConcurrentHashMap<Class<?>, ClientExceptionMapper>();
353 asyncResponseProviders = new ConcurrentHashMap<Class<?>, AsyncResponseProvider>();
354 asyncStreamProviders = new ConcurrentHashMap<Class<?>, AsyncStreamProvider>();
244355 contextResolvers = new ConcurrentHashMap<Class<?>, MediaTypeMap<SortedKey<ContextResolver>>>();
245 paramConverterProviders = new CopyOnWriteArrayList<ParamConverterProvider>();
356 sortedParamConverterProviders = Collections.synchronizedSortedSet(new TreeSet<ExtSortedKey<ParamConverterProvider>>());
246357 stringConverters = new ConcurrentHashMap<Class<?>, StringConverter>();
247358 stringParameterUnmarshallers = new ConcurrentHashMap<Class<?>, Class<? extends StringParameterUnmarshaller>>();
248359
249360 headerDelegates = new ConcurrentHashMap<Class<?>, HeaderDelegate>();
250361
251 initializeRegistriesAndFilters();
362 precedence = new LegacyPrecedence();
363 serverReaderInterceptorRegistry = new ReaderInterceptorRegistry(this, precedence);
364 serverWriterInterceptorRegistry = new WriterInterceptorRegistry(this, precedence);
365 containerRequestFilterRegistry = new ContainerRequestFilterRegistry(this, precedence);
366 containerResponseFilterRegistry = new ContainerResponseFilterRegistry(this, precedence);
367
368 clientRequestFilterRegistry = new ClientRequestFilterRegistry(this);
369 clientRequestFilters = new JaxrsInterceptorRegistry<ClientRequestFilter>(this, ClientRequestFilter.class);
370 clientResponseFilters = new ClientResponseFilterRegistry(this);
371 clientReaderInterceptorRegistry = new ReaderInterceptorRegistry(this, precedence);
372 clientWriterInterceptorRegistry = new WriterInterceptorRegistry(this, precedence);
373 clientExecutionInterceptorRegistry = new InterceptorRegistry<ClientExecutionInterceptor>(ClientExecutionInterceptor.class, this);
374
375 clientErrorInterceptors = new CopyOnWriteArrayList<ClientErrorInterceptor>();
252376
253377 builtinsRegistered = false;
254378 registerBuiltins = true;
255379
256380 injectorFactory = new InjectorFactoryImpl();
381 registerDefaultInterceptorPrecedences();
257382 addHeaderDelegate(MediaType.class, new MediaTypeHeaderDelegate());
258383 addHeaderDelegate(NewCookie.class, new NewCookieHeaderDelegate());
259384 addHeaderDelegate(Cookie.class, new CookieHeaderDelegate());
265390 addHeaderDelegate(javax.ws.rs.core.Link.class, new LinkDelegate());
266391 addHeaderDelegate(Date.class, new DateDelegate());
267392 }
268
269 protected void initializeRegistriesAndFilters()
270 {
271 serverReaderInterceptorRegistry = new ReaderInterceptorRegistry(this);
272 serverWriterInterceptorRegistry = new WriterInterceptorRegistry(this);
273 containerRequestFilterRegistry = new ContainerRequestFilterRegistry(this);
274 containerResponseFilterRegistry = new ContainerResponseFilterRegistry(this);
275
276 clientRequestFilters = new JaxrsInterceptorRegistry<ClientRequestFilter>(this, ClientRequestFilter.class);
277 clientResponseFilters = new ClientResponseFilterRegistry(this);
278 clientReaderInterceptorRegistry = new ReaderInterceptorRegistry(this);
279 clientWriterInterceptorRegistry = new WriterInterceptorRegistry(this);
280
281 }
282393
283394 public Set<DynamicFeature> getServerDynamicFeatures()
284395 {
321432
322433 public Map<Class<?>, ExceptionMapper> getExceptionMappers()
323434 {
324 if (exceptionMappers == null && parent != null) return parent.getExceptionMappers();
325 return exceptionMappers;
435 if (exceptionMappers != null)
436 {
437 return exceptionMappers;
438 }
439 Map<Class<?>, ExceptionMapper> map = new ConcurrentHashMap<Class<?>, ExceptionMapper>();
440 for (Entry<Class<?>, SortedKey<ExceptionMapper>> entry : getSortedExceptionMappers().entrySet())
441 {
442 map.put(entry.getKey(), entry.getValue().getObj());
443 }
444 exceptionMappers = map;
445 return map;
446 }
447
448 protected Map<Class<?>, SortedKey<ExceptionMapper>> getSortedExceptionMappers()
449 {
450 if (sortedExceptionMappers == null && parent != null) return parent.getSortedExceptionMappers();
451 return sortedExceptionMappers;
452 }
453
454 protected Map<Class<?>, ClientExceptionMapper> getClientExceptionMappers()
455 {
456 if (clientExceptionMappers == null && parent != null) return parent.getClientExceptionMappers();
457 return clientExceptionMappers;
458 }
459
460 public Map<Class<?>, AsyncResponseProvider> getAsyncResponseProviders()
461 {
462 if (asyncResponseProviders == null && parent != null) return parent.getAsyncResponseProviders();
463 return asyncResponseProviders;
464 }
465
466 public Map<Class<?>, AsyncStreamProvider> getAsyncStreamProviders()
467 {
468 if (asyncStreamProviders == null && parent != null) return parent.getAsyncStreamProviders();
469 return asyncStreamProviders;
326470 }
327471
328472 protected Map<Class<?>, MediaTypeMap<SortedKey<ContextResolver>>> getContextResolvers()
330474 if (contextResolvers == null && parent != null) return parent.getContextResolvers();
331475 return contextResolvers;
332476 }
333
477
334478 protected Map<Class<?>, StringConverter> getStringConverters()
335479 {
336480 if (stringConverters == null && parent != null) return parent.getStringConverters();
337481 return stringConverters;
338482 }
339 protected List<ParamConverterProvider> getParamConverterProviders()
340 {
341 if (paramConverterProviders == null && parent != null) return parent.getParamConverterProviders();
342 return paramConverterProviders;
343 }
344
483
484 public List<ParamConverterProvider> getParamConverterProviders()
485 {
486 if (paramConverterProviders != null)
487 {
488 return paramConverterProviders;
489 }
490 List<ParamConverterProvider> list = new CopyOnWriteArrayList<ParamConverterProvider>();
491 for (SortedKey<ParamConverterProvider> key : getSortedParamConverterProviders())
492 {
493 list.add(key.getObj());
494 }
495 paramConverterProviders = list;
496 return list;
497 }
498
499 protected Set<ExtSortedKey<ParamConverterProvider>> getSortedParamConverterProviders()
500 {
501 if (sortedParamConverterProviders == null && parent != null) return parent.getSortedParamConverterProviders();
502 return sortedParamConverterProviders;
503 }
345504
346505 protected Map<Class<?>, Class<? extends StringParameterUnmarshaller>> getStringParameterUnmarshallers()
347506 {
393552 classContracts = map;
394553 return classContracts;
395554 }
396
555
556 protected LegacyPrecedence getPrecedence()
557 {
558 if (precedence == null && parent != null) return parent.getPrecedence();
559 return precedence;
560 }
561
397562 public ResteasyProviderFactory getParent()
398563 {
399564 return parent;
565 }
566
567 protected void registerDefaultInterceptorPrecedences(InterceptorRegistry registry)
568 {
569 // legacy
570 registry.appendPrecedence(SecurityPrecedence.PRECEDENCE_STRING);
571 registry.appendPrecedence(HeaderDecoratorPrecedence.PRECEDENCE_STRING);
572 registry.appendPrecedence(EncoderPrecedence.PRECEDENCE_STRING);
573 registry.appendPrecedence(RedirectPrecedence.PRECEDENCE_STRING);
574 registry.appendPrecedence(DecoderPrecedence.PRECEDENCE_STRING);
575
576 }
577
578 protected void registerDefaultInterceptorPrecedences()
579 {
580 precedence.addPrecedence(SecurityPrecedence.PRECEDENCE_STRING, Priorities.AUTHENTICATION);
581 precedence.addPrecedence(HeaderDecoratorPrecedence.PRECEDENCE_STRING, Priorities.HEADER_DECORATOR);
582 precedence.addPrecedence(EncoderPrecedence.PRECEDENCE_STRING, Priorities.ENTITY_CODER);
583 precedence.addPrecedence(RedirectPrecedence.PRECEDENCE_STRING, Priorities.ENTITY_CODER + 50);
584 precedence.addPrecedence(DecoderPrecedence.PRECEDENCE_STRING, Priorities.ENTITY_CODER);
585
586 registerDefaultInterceptorPrecedences(getClientExecutionInterceptorRegistry());
400587 }
401588
402589 /**
407594 @Deprecated
408595 public void appendInterceptorPrecedence(String precedence)
409596 {
410 //NOOP, here only for backward compatibility (used in ResteasyDeployment)
597 if (this.precedence == null)
598 {
599 this.precedence = parent.getPrecedence().clone();
600 }
601 if (clientExecutionInterceptorRegistry == null)
602 {
603 clientExecutionInterceptorRegistry = parent.getClientExecutionInterceptorRegistry().cloneTo(this);
604 }
605 this.precedence.appendPrecedence(precedence);
606 clientExecutionInterceptorRegistry.appendPrecedence(precedence);
411607 }
412608
413609 /**
417613 @Deprecated
418614 public void insertInterceptorPrecedenceAfter(String after, String newPrecedence)
419615 {
420 //NOOP, here only for backward compatibility (used in ResteasyDeployment)
421 }
422
423 /**
616 if (this.precedence == null)
617 {
618 this.precedence = parent.getPrecedence().clone();
619 }
620 if (clientExecutionInterceptorRegistry == null)
621 {
622 clientExecutionInterceptorRegistry = parent.getClientExecutionInterceptorRegistry().cloneTo(this);
623 }
624 this.precedence.insertPrecedenceAfter(after, newPrecedence);
625
626 getClientExecutionInterceptorRegistry().insertPrecedenceAfter(after, newPrecedence);
627 }
628
629 /**
424630 * @param before put newPrecedence before this
425631 * @param newPrecedence
426632 */
427633 @Deprecated
428634 public void insertInterceptorPrecedenceBefore(String before, String newPrecedence)
429635 {
430 //NOOP, here only for backward compatibility (used in ResteasyDeployment)
636 if (this.precedence == null)
637 {
638 this.precedence = parent.getPrecedence().clone();
639 }
640 if (clientExecutionInterceptorRegistry == null)
641 {
642 clientExecutionInterceptorRegistry = parent.getClientExecutionInterceptorRegistry().cloneTo(this);
643 }
644 this.precedence.insertPrecedenceBefore(before, newPrecedence);
645
646 getClientExecutionInterceptorRegistry().insertPrecedenceBefore(before, newPrecedence);
431647 }
432648
433649
552768 }
553769 return instance;
554770 }
555
556 public static ResteasyProviderFactory newInstance()
557 {
558 ResteasyProviderFactory result;
559 RuntimeDelegate runtimeDelegate = getRuntimeDelegate();
560 if (runtimeDelegate instanceof ResteasyProviderFactory)
561 {
562 result = (ResteasyProviderFactory) runtimeDelegate;
563 }
564 else
565 {
566 result = new ResteasyProviderFactory();
567 }
568 return result;
569 }
570
571 private static RuntimeDelegate getRuntimeDelegate() {
572 try {
573 Object delegate =
574 FactoryFinder.find(JAXRS_RUNTIME_DELEGATE_PROPERTY,
575 "org.jboss.resteasy.spi.ResteasyProviderFactory");
576 if (!(delegate instanceof RuntimeDelegate)) {
577 Class<?> pClass = RuntimeDelegate.class;
578 String classnameAsResource = pClass.getName().replace('.', '/') + ".class";
579 ClassLoader loader = pClass.getClassLoader();
580 if (loader == null) {
581 loader = ClassLoader.getSystemClassLoader();
582 }
583 URL targetTypeURL = loader.getResource(classnameAsResource);
584 loader = delegate.getClass().getClassLoader();
585 if (loader == null) {
586 loader = ClassLoader.getSystemClassLoader();
587 }
588 String delegateAsResource = delegate.getClass().getName().replace('.', '/') + ".class";
589 URL delegateURL = loader.getResource(delegateAsResource);
590 throw new LinkageError(Messages.MESSAGES.attemptingToCast(delegateURL, targetTypeURL));
591 }
592 return (RuntimeDelegate) delegate;
593 } catch (Exception ex) {
594 throw new RuntimeException(ex);
595 }
596 }
597771
598772 public static void setRegisterBuiltinByDefault(boolean registerBuiltinByDefault)
599773 {
622796 this.injectorFactory = injectorFactory;
623797 }
624798
799 public InterceptorRegistry<ClientExecutionInterceptor> getClientExecutionInterceptorRegistry()
800 {
801 if (clientExecutionInterceptorRegistry == null && parent != null)
802 return parent.getClientExecutionInterceptorRegistry();
803 return clientExecutionInterceptorRegistry;
804 }
805
625806 public ReaderInterceptorRegistry getServerReaderInterceptorRegistry()
626807 {
627808 if (serverReaderInterceptorRegistry == null && parent != null) return parent.getServerReaderInterceptorRegistry();
658839 return clientWriterInterceptorRegistry;
659840 }
660841
842 public ClientRequestFilterRegistry getClientRequestFilterRegistry()
843 {
844 if (clientRequestFilterRegistry == null && parent != null) return parent.getClientRequestFilterRegistry();
845 return clientRequestFilterRegistry;
846 }
847
848 /**
849 * This method retained for jaxrs-legacy code. This method is deprecated and is replace
850 * by method, getClientRequestFilterRegistry().
851 * @return
852 */
853 @Deprecated
661854 public JaxrsInterceptorRegistry<ClientRequestFilter> getClientRequestFilters()
662855 {
663856 if (clientRequestFilters == null && parent != null) return parent.getClientRequestFilters();
699892 {
700893 if (tClass == null) throw new IllegalArgumentException(Messages.MESSAGES.tClassParameterNull());
701894 if (headerDelegates == null && parent != null) return parent.createHeaderDelegate(tClass);
702
895
703896 Class<?> clazz = tClass;
704897 while (clazz != null)
705898 {
715908 }
716909 clazz = clazz.getSuperclass();
717910 }
718
911
719912 return createHeaderDelegateFromInterfaces(tClass.getInterfaces());
720913 }
721
914
722915 protected <T> HeaderDelegate<T> createHeaderDelegateFromInterfaces(Class<?>[] interfaces)
723916 {
724917 HeaderDelegate<T> delegate = null;
754947 headerDelegates.put(clazz, header);
755948 }
756949
757 protected void addMessageBodyReader(Class<? extends MessageBodyReader> provider, boolean isBuiltin)
950 protected void addMessageBodyReader(Class<? extends MessageBodyReader> provider, int priority, boolean isBuiltin)
758951 {
759952 MessageBodyReader reader = createProviderInstance(provider);
760 addMessageBodyReader(reader, provider, isBuiltin);
953 addMessageBodyReader(reader, provider, priority, isBuiltin);
761954 }
762955
763956 protected void addMessageBodyReader(MessageBodyReader provider)
764957 {
765 addMessageBodyReader(provider, false);
766 }
767
768 protected void addMessageBodyReader(MessageBodyReader provider, boolean isBuiltin)
769 {
770 addMessageBodyReader(provider, provider.getClass(), isBuiltin);
958 addMessageBodyReader(provider, Priorities.USER, false);
959 }
960
961 protected void addMessageBodyReader(MessageBodyReader provider, int priority, boolean isBuiltin)
962 {
963 addMessageBodyReader(provider, provider.getClass(), priority, isBuiltin);
771964 }
772965
773966 /**
779972 * @param isBuiltin
780973 */
781974
782 protected void addMessageBodyReader(MessageBodyReader provider, Class<?> providerClass, boolean isBuiltin)
783 {
784 SortedKey<MessageBodyReader> key = new SortedKey<MessageBodyReader>(MessageBodyReader.class, provider, providerClass, isBuiltin);
975 protected void addMessageBodyReader(MessageBodyReader provider, Class<?> providerClass, int priority, boolean isBuiltin)
976 {
977 SortedKey<MessageBodyReader> key = new SortedKey<MessageBodyReader>(MessageBodyReader.class, provider, providerClass, priority, isBuiltin);
785978 injectProperties(providerClass, provider);
786979 Consumes consumeMime = provider.getClass().getAnnotation(Consumes.class);
787980 RuntimeType type = null;
8431036 }
8441037 }
8451038
846 protected void addMessageBodyWriter(Class<? extends MessageBodyWriter> provider, boolean isBuiltin)
1039 protected void addMessageBodyWriter(Class<? extends MessageBodyWriter> provider, int priority, boolean isBuiltin)
8471040 {
8481041 MessageBodyWriter writer = createProviderInstance(provider);
849 addMessageBodyWriter(writer, provider, isBuiltin);
1042 addMessageBodyWriter(writer, provider, priority, isBuiltin);
8501043 }
8511044
8521045 protected void addMessageBodyWriter(MessageBodyWriter provider)
8531046 {
854 addMessageBodyWriter(provider, provider.getClass(), false);
1047 addMessageBodyWriter(provider, provider.getClass(), Priorities.USER, false);
8551048 }
8561049
8571050 /**
8621055 * @param providerClass
8631056 * @param isBuiltin
8641057 */
865 protected void addMessageBodyWriter(MessageBodyWriter provider, Class<?> providerClass, boolean isBuiltin)
1058 protected void addMessageBodyWriter(MessageBodyWriter provider, Class<?> providerClass, int priority, boolean isBuiltin)
8661059 {
8671060 injectProperties(providerClass, provider);
8681061 Produces consumeMime = provider.getClass().getAnnotation(Produces.class);
869 SortedKey<MessageBodyWriter> key = new SortedKey<MessageBodyWriter>(MessageBodyWriter.class, provider, providerClass, isBuiltin);
1062 SortedKey<MessageBodyWriter> key = new SortedKey<MessageBodyWriter>(MessageBodyWriter.class, provider, providerClass, priority, isBuiltin);
8701063 RuntimeType type = null;
8711064 ConstrainedTo constrainedTo = providerClass.getAnnotation(ConstrainedTo.class);
8721065 if (constrainedTo != null) type = constrainedTo.value();
9881181
9891182 protected void addExceptionMapper(Class<? extends ExceptionMapper> providerClass)
9901183 {
1184 addExceptionMapper(providerClass, false);
1185 }
1186
1187 protected void addExceptionMapper(ExceptionMapper provider)
1188 {
1189 addExceptionMapper(provider, false);
1190 }
1191
1192 protected void addExceptionMapper(ExceptionMapper provider, Class providerClass)
1193 {
1194 addExceptionMapper(provider, providerClass, false);
1195 }
1196
1197 protected void addExceptionMapper(ExceptionMapper provider, Type exceptionType)
1198 {
1199 addExceptionMapper(provider, exceptionType, provider.getClass(), false);
1200 }
1201
1202 protected void addExceptionMapper(Class<? extends ExceptionMapper> providerClass, boolean isBuiltin)
1203 {
9911204 ExceptionMapper provider = createProviderInstance(providerClass);
992 addExceptionMapper(provider, providerClass);
993 }
994
995 protected void addExceptionMapper(ExceptionMapper provider)
996 {
997 addExceptionMapper(provider, provider.getClass());
998 }
999
1000 protected void addExceptionMapper(ExceptionMapper provider, Class providerClass)
1001 {
1205 addExceptionMapper(provider, providerClass, isBuiltin);
1206 }
1207
1208 protected void addExceptionMapper(ExceptionMapper provider, boolean isBuiltin)
1209 {
1210 addExceptionMapper(provider, provider.getClass(), isBuiltin);
1211 }
1212
1213 protected void addExceptionMapper(ExceptionMapper provider, Class providerClass, boolean isBuiltin)
1214 {
1215 // Check for weld proxy.
1216 if (providerClass.isSynthetic())
1217 {
1218 providerClass = providerClass.getSuperclass();
1219 }
10021220 Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(providerClass, ExceptionMapper.class)[0];
1003 addExceptionMapper(provider, exceptionType);
1004 }
1005
1006
1007 protected void addExceptionMapper(ExceptionMapper provider, Type exceptionType)
1008 {
1009 injectProperties(provider.getClass(), provider);
1221 addExceptionMapper(provider, exceptionType, providerClass, isBuiltin);
1222 }
1223
1224 protected void addExceptionMapper(ExceptionMapper provider, Type exceptionType, Class providerClass, boolean isBuiltin)
1225 {
1226 // Check for weld proxy.
1227 if (providerClass.isSynthetic())
1228 {
1229 providerClass = providerClass.getSuperclass();
1230 }
1231 injectProperties(providerClass, provider);
10101232
10111233 Class<?> exceptionClass = Types.getRawType(exceptionType);
10121234 if (!Throwable.class.isAssignableFrom(exceptionClass))
10131235 {
10141236 throw new RuntimeException(Messages.MESSAGES.incorrectTypeParameterExceptionMapper());
10151237 }
1016 if (exceptionMappers == null)
1017 {
1018 exceptionMappers = new ConcurrentHashMap<Class<?>, ExceptionMapper>();
1019 exceptionMappers.putAll(parent.getExceptionMappers());
1020 }
1021 exceptionMappers.put(exceptionClass, provider);
1238 if (sortedExceptionMappers == null)
1239 {
1240 sortedExceptionMappers = new ConcurrentHashMap<Class<?>, SortedKey<ExceptionMapper>>();
1241 sortedExceptionMappers.putAll(parent.getSortedExceptionMappers());
1242 }
1243 int priority = getPriority(null, null, ExceptionMapper.class, providerClass);
1244 SortedKey<ExceptionMapper> candidateExceptionMapper = new SortedKey<>(null, provider, providerClass, priority, isBuiltin);
1245 SortedKey<ExceptionMapper> registeredExceptionMapper;
1246 if ((registeredExceptionMapper = sortedExceptionMappers.get(exceptionClass)) != null
1247 && (candidateExceptionMapper.compareTo(registeredExceptionMapper) > 0)) {
1248 return;
1249 }
1250 sortedExceptionMappers.put(exceptionClass, candidateExceptionMapper);
1251 exceptionMappers = null;
1252 }
1253
1254 public void addClientExceptionMapper(Class<? extends ClientExceptionMapper<?>> providerClass)
1255 {
1256 ClientExceptionMapper<?> provider = createProviderInstance(providerClass);
1257 addClientExceptionMapper(provider, providerClass);
1258 }
1259
1260 public void addClientExceptionMapper(ClientExceptionMapper<?> provider)
1261 {
1262 addClientExceptionMapper(provider, provider.getClass());
1263 }
1264
1265 public void addClientExceptionMapper(ClientExceptionMapper<?> provider, Class<?> providerClass)
1266 {
1267 Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(providerClass, ClientExceptionMapper.class)[0];
1268 addClientExceptionMapper(provider, exceptionType);
1269 }
1270
1271 public void addClientExceptionMapper(ClientExceptionMapper<?> provider, Type exceptionType)
1272 {
1273 injectProperties(provider.getClass());
1274
1275 Class<?> exceptionClass = Types.getRawType(exceptionType);
1276 if (!Throwable.class.isAssignableFrom(exceptionClass))
1277 {
1278 throw new RuntimeException(Messages.MESSAGES.incorrectTypeParameterClientExceptionMapper());
1279 }
1280 if (clientExceptionMappers == null)
1281 {
1282 clientExceptionMappers = new ConcurrentHashMap<Class<?>, ClientExceptionMapper>();
1283 clientExceptionMappers.putAll(parent.getClientExceptionMappers());
1284 }
1285 clientExceptionMappers.put(exceptionClass, provider);
1286 }
1287
1288 /**
1289 * Add a {@link ClientErrorInterceptor} to this provider factory instance.
1290 * Duplicate handlers are ignored. (For Client Proxy API only)
1291 */
1292 public void addClientErrorInterceptor(ClientErrorInterceptor handler)
1293 {
1294 if (clientErrorInterceptors == null)
1295 {
1296 clientErrorInterceptors = new CopyOnWriteArrayList<ClientErrorInterceptor>(parent.getClientErrorInterceptors());
1297 }
1298 if (!clientErrorInterceptors.contains(handler))
1299 {
1300 clientErrorInterceptors.add(handler);
1301 }
1302 }
1303
1304
1305 /**
1306 * Return the list of currently registered {@link ClientErrorInterceptor} instances.
1307 */
1308 public List<ClientErrorInterceptor> getClientErrorInterceptors()
1309 {
1310 if (clientErrorInterceptors == null && parent != null) return parent.getClientErrorInterceptors();
1311 return clientErrorInterceptors;
1312 }
1313
1314 protected void addAsyncResponseProvider(Class<? extends AsyncResponseProvider> providerClass)
1315 {
1316 AsyncResponseProvider provider = createProviderInstance(providerClass);
1317 addAsyncResponseProvider(provider, providerClass);
1318 }
1319
1320 protected void addAsyncResponseProvider(AsyncResponseProvider provider)
1321 {
1322 addAsyncResponseProvider(provider, provider.getClass());
1323 }
1324
1325 protected void addAsyncResponseProvider(AsyncResponseProvider provider, Class providerClass)
1326 {
1327 Type asyncType = Types.getActualTypeArgumentsOfAnInterface(providerClass, AsyncResponseProvider.class)[0];
1328 addAsyncResponseProvider(provider, asyncType);
1329 }
1330
1331 protected void addAsyncResponseProvider(AsyncResponseProvider provider, Type asyncType)
1332 {
1333 injectProperties(provider.getClass(), provider);
1334
1335 Class<?> asyncClass = Types.getRawType(asyncType);
1336 if (asyncResponseProviders == null)
1337 {
1338 asyncResponseProviders = new ConcurrentHashMap<Class<?>, AsyncResponseProvider>();
1339 asyncResponseProviders.putAll(parent.getAsyncResponseProviders());
1340 }
1341 asyncResponseProviders.put(asyncClass, provider);
1342 }
1343
1344 protected void addAsyncStreamProvider(Class<? extends AsyncStreamProvider> providerClass)
1345 {
1346 AsyncStreamProvider provider = createProviderInstance(providerClass);
1347 addAsyncStreamProvider(provider, providerClass);
1348 }
1349
1350 protected void addAsyncStreamProvider(AsyncStreamProvider provider)
1351 {
1352 addAsyncStreamProvider(provider, provider.getClass());
1353 }
1354
1355 protected void addAsyncStreamProvider(AsyncStreamProvider provider, Class providerClass)
1356 {
1357 Type asyncType = Types.getActualTypeArgumentsOfAnInterface(providerClass, AsyncStreamProvider.class)[0];
1358 addAsyncStreamProvider(provider, asyncType);
1359 }
1360
1361 protected void addAsyncStreamProvider(AsyncStreamProvider provider, Type asyncType)
1362 {
1363 injectProperties(provider.getClass(), provider);
1364
1365 Class<?> asyncClass = Types.getRawType(asyncType);
1366 if (asyncStreamProviders == null)
1367 {
1368 asyncStreamProviders = new ConcurrentHashMap<Class<?>, AsyncStreamProvider>();
1369 asyncStreamProviders.putAll(parent.getAsyncStreamProviders());
1370 }
1371 asyncStreamProviders.put(asyncClass, provider);
10221372 }
10231373
10241374 protected void addContextResolver(Class<? extends ContextResolver> resolver, boolean builtin)
10621412 contextResolvers.put(parameterClass, resolvers);
10631413 }
10641414 Produces produces = provider.getClass().getAnnotation(Produces.class);
1065 SortedKey<ContextResolver> key = new SortedKey<ContextResolver>(ContextResolver.class, provider, providerClass, builtin);
1415 int priority = this.getPriority(null, null, ContextResolver.class, providerClass);
1416 SortedKey<ContextResolver> key = new SortedKey<ContextResolver>(ContextResolver.class, provider, providerClass, priority, builtin);
10661417 if (produces != null)
10671418 {
10681419 for (String produce : produces.value())
11061457 stringConverters.put(parameterClass, provider);
11071458 }
11081459
1460
11091461 public void addStringParameterUnmarshaller(Class<? extends StringParameterUnmarshaller> provider)
11101462 {
11111463 if (stringParameterUnmarshallers == null)
11281480 }
11291481 }
11301482
1131 public StringConverter getStringConverter(Class<?> clazz)
1132 {
1133 if (getStringConverters().size() == 0) return null;
1134 return getStringConverters().get(clazz);
1135 }
1136
1137 public List<ContextResolver> getContextResolvers(Class<?> clazz, MediaType type)
1483 public List<ContextResolver> getContextResolvers(final Class<?> clazz, MediaType type)
11381484 {
11391485 MediaTypeMap<SortedKey<ContextResolver>> resolvers = getContextResolvers().get(clazz);
11401486 if (resolvers == null) return null;
11491495 // {
11501496 // rtn.add(list.get(i).obj);
11511497 // }
1152
1153 // Fix for RESTEASY-1609.
1154 // This is related to the fix in RESTEASY-1471, prior to which user ContextResolvers appeared
1155 // to be built-in. The original loop may have been in response to that bug, so the reversal
1156 // may not be necessary. In any case, this code will do the reversal but put user ContextResolvers
1157 // at the beginning of the list.
1158 for (int i = list.size() - 1; i >= 0; i--)
1159 {
1160 if (!list.get(i).isBuiltin)
1161 {
1162 rtn.add(list.get(i).obj);
1163 }
1164 }
1165 for (int i = list.size() - 1; i >= 0; i--)
1166 {
1167 if (list.get(i).isBuiltin)
1168 {
1169 rtn.add(list.get(i).obj);
1170 }
1171 }
1498
1499 // Fix for RESTEASY-1609.
1500 // This is related to the fix in RESTEASY-1471, prior to which user ContextResolvers appeared
1501 // to be built-in. The original loop may have been in response to that bug, so the reversal
1502 // may not be necessary. In any case, this code will do the reversal but put user ContextResolvers
1503 // at the beginning of the list.
1504 for (int i = list.size() - 1; i >= 0; i--)
1505 {
1506 if (!list.get(i).isBuiltin)
1507 {
1508 rtn.add(list.get(i).obj);
1509 }
1510 }
1511 for (int i = list.size() - 1; i >= 0; i--)
1512 {
1513 if (list.get(i).isBuiltin)
1514 {
1515 rtn.add(list.get(i).obj);
1516 }
1517 }
11721518 }
11731519 else
11741520 {
11821528
11831529 public ParamConverter getParamConverter(Class clazz, Type genericType, Annotation[] annotations)
11841530 {
1185 for (ParamConverterProvider provider : getParamConverterProviders())
1186 {
1187 ParamConverter converter = provider.getConverter(clazz, genericType, annotations);
1531 for (SortedKey<ParamConverterProvider> provider : getSortedParamConverterProviders())
1532 {
1533 ParamConverter converter = provider.getObj().getConverter(clazz, genericType, annotations);
11881534 if (converter != null) return converter;
11891535 }
11901536 return null;
1537 }
1538
1539 public StringConverter getStringConverter(Class<?> clazz)
1540 {
1541 if (getStringConverters().size() == 0) return null;
1542 return getStringConverters().get(clazz);
11911543 }
11921544
11931545 public <T> StringParameterUnmarshaller<T> createStringParameterUnmarshaller(Class<T> clazz)
13081660 Integer p = contracts.get(type);
13091661 if (p != null) return p;
13101662 }
1663 // Check for weld proxy.
1664 component = component.isSynthetic() ? component.getSuperclass() : component;
13111665 Priority priority = component.getAnnotation(Priority.class);
13121666 if (priority == null) return Priorities.USER;
13131667 return priority.value();
13291683 }
13301684 }
13311685 Map<Class<?>, Integer> newContracts = new HashMap<Class<?>, Integer>();
1332 processProviderContracts(provider, priorityOverride, isBuiltin, contracts, newContracts);
1333
1334 providerClasses.add(provider);
1335 getClassContracts().put(provider, newContracts);
1336 }
1337
1338 protected void processProviderContracts(Class provider, Integer priorityOverride, boolean isBuiltin,
1339 Map<Class<?>, Integer> contracts, Map<Class<?>, Integer> newContracts)
1340 {
1686
13411687 if (isA(provider, ParamConverterProvider.class, contracts))
13421688 {
13431689 ParamConverterProvider paramConverterProvider = (ParamConverterProvider) injectedInstance(provider);
13441690 injectProperties(provider);
1345 if (paramConverterProviders == null)
1346 {
1347 paramConverterProviders = new CopyOnWriteArrayList<ParamConverterProvider>(parent.getParamConverterProviders());
1348 }
1349 paramConverterProviders.add(paramConverterProvider);
1350 newContracts.put(ParamConverterProvider.class, getPriority(priorityOverride, contracts, ParamConverterProvider.class, provider));
1691 if (sortedParamConverterProviders == null)
1692 {
1693 sortedParamConverterProviders = Collections.synchronizedSortedSet(new TreeSet<>(parent.getSortedParamConverterProviders()));
1694 }
1695 int priority = getPriority(priorityOverride, contracts, ParamConverterProvider.class, provider);
1696 sortedParamConverterProviders.add(new ExtSortedKey<>(null, paramConverterProvider, provider, priority, isBuiltin));
1697 paramConverterProviders = null;
1698 newContracts.put(ParamConverterProvider.class, priority);
13511699 }
13521700 if (isA(provider, MessageBodyReader.class, contracts))
13531701 {
13541702 try
13551703 {
1356 addMessageBodyReader(provider, isBuiltin);
1357 newContracts.put(MessageBodyReader.class, getPriority(priorityOverride, contracts, MessageBodyReader.class, provider));
1704 int priority = getPriority(priorityOverride, contracts, MessageBodyReader.class, provider);
1705 addMessageBodyReader(provider, priority, isBuiltin);
1706 newContracts.put(MessageBodyReader.class, priority);
13581707 }
13591708 catch (Exception e)
13601709 {
13651714 {
13661715 try
13671716 {
1368 addMessageBodyWriter(provider, isBuiltin);
1369 newContracts.put(MessageBodyWriter.class, getPriority(priorityOverride, contracts, MessageBodyWriter.class, provider));
1717 int priority = getPriority(priorityOverride, contracts, MessageBodyWriter.class, provider);
1718 addMessageBodyWriter(provider, priority, isBuiltin);
1719 newContracts.put(MessageBodyWriter.class, priority);
13701720 }
13711721 catch (Exception e)
13721722 {
13771727 {
13781728 try
13791729 {
1380 addExceptionMapper(provider);
1730 addExceptionMapper(provider, isBuiltin);
13811731 newContracts.put(ExceptionMapper.class, getPriority(priorityOverride, contracts, ExceptionMapper.class, provider));
13821732 }
13831733 catch (Exception e)
13851735 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateExceptionMapper(), e);
13861736 }
13871737 }
1738
1739 if (isA(provider, ClientExceptionMapper.class, contracts))
1740 {
1741 try
1742 {
1743 addClientExceptionMapper(provider);
1744 newContracts.put(ClientExceptionMapper.class, getPriority(priorityOverride, contracts, ClientExceptionMapper.class, provider));
1745 }
1746 catch (Exception e)
1747 {
1748 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateClientExceptionMapper(), e);
1749 }
1750 }
1751 if (isA(provider, AsyncResponseProvider.class, contracts))
1752 {
1753 try
1754 {
1755 addAsyncResponseProvider(provider);
1756 newContracts.put(AsyncResponseProvider.class, getPriority(priorityOverride, contracts, AsyncResponseProvider.class, provider));
1757 }
1758 catch (Exception e)
1759 {
1760 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateAsyncResponseProvider(), e);
1761 }
1762 }
1763 if (isA(provider, AsyncStreamProvider.class, contracts))
1764 {
1765 try
1766 {
1767 addAsyncStreamProvider(provider);
1768 newContracts.put(AsyncStreamProvider.class, getPriority(priorityOverride, contracts, AsyncStreamProvider.class, provider));
1769 }
1770 catch (Exception e)
1771 {
1772 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateAsyncStreamProvider(), e);
1773 }
1774 }
13881775 if (isA(provider, ClientRequestFilter.class, contracts))
13891776 {
1390 if (clientRequestFilters == null)
1391 {
1392 clientRequestFilters = parent.getClientRequestFilters().clone(this);
1777 if (clientRequestFilterRegistry == null)
1778 {
1779 clientRequestFilterRegistry = parent.getClientRequestFilterRegistry().clone(this);
13931780 }
13941781 int priority = getPriority(priorityOverride, contracts, ClientRequestFilter.class, provider);
1395 clientRequestFilters.registerClass(provider, priority);
1782 clientRequestFilterRegistry.registerClass(provider, priority);
13961783 newContracts.put(ClientRequestFilter.class, priority);
1784
1785 { // code maintained for backward compatibility for jaxrs-legacy code
1786 if (clientRequestFilters == null)
1787 {
1788 clientRequestFilters = parent.getClientRequestFilters().clone(this);
1789 }
1790 clientRequestFilters.registerClass(provider, priority);
1791 }
1792
13971793 }
13981794 if (isA(provider, ClientResponseFilter.class, contracts))
13991795 {
14051801 clientResponseFilters.registerClass(provider, priority);
14061802 newContracts.put(ClientResponseFilter.class, priority);
14071803 }
1804 if (isA(provider, ClientExecutionInterceptor.class, contracts))
1805 {
1806 if (clientExecutionInterceptorRegistry == null)
1807 {
1808 clientExecutionInterceptorRegistry = parent.getClientExecutionInterceptorRegistry().cloneTo(this);
1809 }
1810 clientExecutionInterceptorRegistry.register(provider);
1811 newContracts.put(ClientExecutionInterceptor.class, 0);
1812 }
1813 if (isA(provider, PreProcessInterceptor.class, contracts))
1814 {
1815 if (containerRequestFilterRegistry == null)
1816 {
1817 containerRequestFilterRegistry = parent.getContainerRequestFilterRegistry().clone(this);
1818 }
1819 containerRequestFilterRegistry.registerLegacy(provider);
1820 newContracts.put(PreProcessInterceptor.class, 0);
1821 }
1822 if (isA(provider, PostProcessInterceptor.class, contracts))
1823 {
1824 if (containerResponseFilterRegistry == null)
1825 {
1826 containerResponseFilterRegistry = parent.getContainerResponseFilterRegistry().clone(this);
1827 }
1828 containerResponseFilterRegistry.registerLegacy(provider);
1829 newContracts.put(PostProcessInterceptor.class, 0);
1830 }
14081831 if (isA(provider, ContainerRequestFilter.class, contracts))
14091832 {
14101833 if (containerRequestFilterRegistry == null)
14951918 }
14961919 newContracts.put(WriterInterceptor.class, priority);
14971920 }
1921 if (isA(provider, MessageBodyWriterInterceptor.class, contracts))
1922 {
1923 if (provider.isAnnotationPresent(ServerInterceptor.class))
1924 {
1925 if (serverWriterInterceptorRegistry == null)
1926 {
1927 serverWriterInterceptorRegistry = parent.getServerWriterInterceptorRegistry().clone(this);
1928 }
1929 serverWriterInterceptorRegistry.registerLegacy(provider);
1930 }
1931 if (provider.isAnnotationPresent(ClientInterceptor.class))
1932 {
1933 if (clientWriterInterceptorRegistry == null)
1934 {
1935 clientWriterInterceptorRegistry = parent.getClientWriterInterceptorRegistry().clone(this);
1936 }
1937 clientWriterInterceptorRegistry.registerLegacy(provider);
1938 }
1939 if (!provider.isAnnotationPresent(ServerInterceptor.class) && !provider.isAnnotationPresent(ClientInterceptor.class))
1940 {
1941 throw new RuntimeException(Messages.MESSAGES.interceptorClassMustBeAnnotated());
1942 }
1943 newContracts.put(MessageBodyWriterInterceptor.class, 0);
1944
1945 }
1946 if (isA(provider, MessageBodyReaderInterceptor.class, contracts))
1947 {
1948 if (provider.isAnnotationPresent(ServerInterceptor.class))
1949 {
1950 if (serverReaderInterceptorRegistry == null)
1951 {
1952 serverReaderInterceptorRegistry = parent.getServerReaderInterceptorRegistry().clone(this);
1953 }
1954 serverReaderInterceptorRegistry.registerLegacy(provider);
1955 }
1956 if (provider.isAnnotationPresent(ClientInterceptor.class))
1957 {
1958 if (clientReaderInterceptorRegistry == null)
1959 {
1960 clientReaderInterceptorRegistry = parent.getClientReaderInterceptorRegistry().clone(this);
1961 }
1962 clientReaderInterceptorRegistry.registerLegacy(provider);
1963 }
1964 if (!provider.isAnnotationPresent(ServerInterceptor.class) && !provider.isAnnotationPresent(ClientInterceptor.class))
1965 {
1966 throw new RuntimeException(Messages.MESSAGES.interceptorClassMustBeAnnotated());
1967 }
1968 newContracts.put(MessageBodyReaderInterceptor.class, 0);
1969
1970 }
14981971 if (isA(provider, ContextResolver.class, contracts))
14991972 {
15001973 try
15792052 newContracts.put(Feature.class, priority);
15802053
15812054 }
2055 if (EE8_PREVIEW_MODE && isA(provider, RxInvokerProvider.class, contracts))
2056 {
2057 int priority = getPriority(priorityOverride, contracts, RxInvokerProvider.class, provider);
2058 newContracts.put(RxInvokerProvider.class, priority);
2059 }
2060 if (isA(provider, ResponseExceptionMapper.class, contracts))
2061 {
2062 try {
2063 Object mapper = provider.newInstance();
2064 registerProviderInstance(mapper, contracts, null, false);
2065
2066 if(contracts!=null) {
2067 Integer prio = contracts.get(ResponseExceptionMapper.class) != null ? contracts.get(ResponseExceptionMapper.class) :
2068 ((ResponseExceptionMapper) mapper).getPriority();
2069
2070 newContracts.put(ResponseExceptionMapper.class, prio);
2071 } else {
2072 newContracts.put(ResponseExceptionMapper.class, ((ResponseExceptionMapper) mapper).getPriority());
2073 }
2074 } catch (Throwable e) {
2075 e.printStackTrace();
2076 throw new RuntimeException("Failed to register provider", e);
2077 }
2078 }
2079 providerClasses.add(provider);
2080 getClassContracts().put(provider, newContracts);
15822081 }
15832082
15842083 /**
16072106 return;
16082107 }
16092108 Map<Class<?>, Integer> newContracts = new HashMap<Class<?>, Integer>();
1610 processProviderInstanceContracts(provider, contracts, priorityOverride, builtIn, newContracts);
1611 providerInstances.add(provider);
1612 getClassContracts().put(provider.getClass(), newContracts);
1613 }
1614
1615 protected void processProviderInstanceContracts(Object provider, Map<Class<?>, Integer> contracts,
1616 Integer priorityOverride, boolean builtIn, Map<Class<?>, Integer> newContracts)
1617 {
16182109 if (isA(provider, ParamConverterProvider.class, contracts))
16192110 {
16202111 injectProperties(provider);
1621 if (paramConverterProviders == null)
1622 {
1623 paramConverterProviders = new CopyOnWriteArrayList<ParamConverterProvider>(parent.getParamConverterProviders());
1624 }
1625 paramConverterProviders.add((ParamConverterProvider) provider);
2112 if (sortedParamConverterProviders == null)
2113 {
2114 sortedParamConverterProviders = Collections.synchronizedSortedSet(new TreeSet<>(parent.getSortedParamConverterProviders()));
2115 }
16262116 int priority = getPriority(priorityOverride, contracts, ParamConverterProvider.class, provider.getClass());
2117 sortedParamConverterProviders.add(new ExtSortedKey<>(null, (ParamConverterProvider) provider, provider.getClass(), priority, builtIn));
2118 paramConverterProviders = null;
16272119 newContracts.put(ParamConverterProvider.class, priority);
16282120 }
16292121 if (isA(provider, MessageBodyReader.class, contracts))
16302122 {
16312123 try
16322124 {
1633 addMessageBodyReader((MessageBodyReader) provider, builtIn);
16342125 int priority = getPriority(priorityOverride, contracts, MessageBodyReader.class, provider.getClass());
2126 addMessageBodyReader((MessageBodyReader) provider, priority, builtIn);
16352127 newContracts.put(MessageBodyReader.class, priority);
16362128 }
16372129 catch (Exception e)
16432135 {
16442136 try
16452137 {
1646 addMessageBodyWriter((MessageBodyWriter) provider, provider.getClass(), builtIn);
16472138 int priority = getPriority(priorityOverride, contracts, MessageBodyWriter.class, provider.getClass());
2139 addMessageBodyWriter((MessageBodyWriter) provider, provider.getClass(), priority, builtIn);
16482140 newContracts.put(MessageBodyWriter.class, priority);
16492141 }
16502142 catch (Exception e)
16562148 {
16572149 try
16582150 {
1659 addExceptionMapper((ExceptionMapper) provider);
2151 addExceptionMapper((ExceptionMapper) provider, builtIn);
16602152 int priority = getPriority(priorityOverride, contracts, ExceptionMapper.class, provider.getClass());
16612153 newContracts.put(ExceptionMapper.class, priority);
16622154 }
16632155 catch (Exception e)
16642156 {
16652157 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateExceptionMapper(), e);
2158 }
2159 }
2160 if (isA(provider, ClientExceptionMapper.class, contracts))
2161 {
2162 try
2163 {
2164 addClientExceptionMapper((ClientExceptionMapper) provider);
2165 newContracts.put(ClientExceptionMapper.class, 0);
2166 }
2167 catch (Exception e)
2168 {
2169 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateExceptionMapper(), e);
2170 }
2171 }
2172 if (isA(provider, AsyncResponseProvider.class, contracts))
2173 {
2174 try
2175 {
2176 addAsyncResponseProvider((AsyncResponseProvider) provider);
2177 int priority = getPriority(priorityOverride, contracts, AsyncResponseProvider.class, provider.getClass());
2178 newContracts.put(AsyncResponseProvider.class, priority);
2179 }
2180 catch (Exception e)
2181 {
2182 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateAsyncResponseProvider(), e);
2183 }
2184 }
2185 if (isA(provider, AsyncStreamProvider.class, contracts))
2186 {
2187 try
2188 {
2189 addAsyncStreamProvider((AsyncStreamProvider) provider);
2190 int priority = getPriority(priorityOverride, contracts, AsyncStreamProvider.class, provider.getClass());
2191 newContracts.put(AsyncStreamProvider.class, priority);
2192 }
2193 catch (Exception e)
2194 {
2195 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateAsyncStreamProvider(), e);
16662196 }
16672197 }
16682198 if (isA(provider, ContextResolver.class, contracts))
16802210 }
16812211 if (isA(provider, ClientRequestFilter.class, contracts))
16822212 {
1683 if (clientRequestFilters == null)
1684 {
1685 clientRequestFilters = parent.getClientRequestFilters().clone(this);
2213 if (clientRequestFilterRegistry == null)
2214 {
2215 clientRequestFilterRegistry = parent.getClientRequestFilterRegistry().clone(this);
16862216 }
16872217 int priority = getPriority(priorityOverride, contracts, ClientRequestFilter.class, provider.getClass());
1688 clientRequestFilters.registerSingleton((ClientRequestFilter) provider, priority);
2218 clientRequestFilterRegistry.registerSingleton((ClientRequestFilter) provider, priority);
16892219 newContracts.put(ClientRequestFilter.class, priority);
2220
2221 { // code maintained for backward compatibility for jaxrs-legacy code
2222 if (clientRequestFilters == null)
2223 {
2224 clientRequestFilters = parent.getClientRequestFilters().clone(this);
2225 }
2226 clientRequestFilters.registerSingleton((ClientRequestFilter) provider, priority);
2227 }
16902228 }
16912229 if (isA(provider, ClientResponseFilter.class, contracts))
16922230 {
16982236 clientResponseFilters.registerSingleton((ClientResponseFilter) provider, priority);
16992237 newContracts.put(ClientResponseFilter.class, priority);
17002238 }
2239 if (isA(provider, ClientExecutionInterceptor.class, contracts))
2240 {
2241 if (clientExecutionInterceptorRegistry == null)
2242 {
2243 clientExecutionInterceptorRegistry = parent.getClientExecutionInterceptorRegistry().cloneTo(this);
2244 }
2245 clientExecutionInterceptorRegistry.register((ClientExecutionInterceptor) provider);
2246 newContracts.put(ClientExecutionInterceptor.class, 0);
2247 }
2248 if (isA(provider, PreProcessInterceptor.class, contracts))
2249 {
2250 if (containerRequestFilterRegistry == null)
2251 {
2252 containerRequestFilterRegistry = parent.getContainerRequestFilterRegistry().clone(this);
2253 }
2254 containerRequestFilterRegistry.registerLegacy((PreProcessInterceptor) provider);
2255 newContracts.put(PreProcessInterceptor.class, 0);
2256 }
17012257 if (isA(provider, ContainerRequestFilter.class, contracts))
17022258 {
17032259 if (containerRequestFilterRegistry == null)
17082264 containerRequestFilterRegistry.registerSingleton((ContainerRequestFilter) provider, priority);
17092265 newContracts.put(ContainerRequestFilter.class, priority);
17102266 }
2267 if (isA(provider, PostProcessInterceptor.class, contracts))
2268 {
2269 if (containerResponseFilterRegistry == null)
2270 {
2271 containerResponseFilterRegistry = parent.getContainerResponseFilterRegistry().clone(this);
2272 }
2273 containerResponseFilterRegistry.registerLegacy((PostProcessInterceptor) provider);
2274 newContracts.put(PostProcessInterceptor.class, 0);
2275 }
17112276 if (isA(provider, ContainerResponseFilter.class, contracts))
17122277 {
17132278 if (containerResponseFilterRegistry == null)
17882353 }
17892354 newContracts.put(WriterInterceptor.class, priority);
17902355 }
2356 if (isA(provider, MessageBodyWriterInterceptor.class, contracts))
2357 {
2358 if (provider.getClass().isAnnotationPresent(ServerInterceptor.class))
2359 {
2360 if (serverWriterInterceptorRegistry == null)
2361 {
2362 serverWriterInterceptorRegistry = parent.getServerWriterInterceptorRegistry().clone(this);
2363 }
2364 serverWriterInterceptorRegistry.registerLegacy((MessageBodyWriterInterceptor) provider);
2365 }
2366 if (provider.getClass().isAnnotationPresent(ClientInterceptor.class))
2367 {
2368 if (clientWriterInterceptorRegistry == null)
2369 {
2370 clientWriterInterceptorRegistry = parent.getClientWriterInterceptorRegistry().clone(this);
2371 }
2372 clientWriterInterceptorRegistry.registerLegacy((MessageBodyWriterInterceptor) provider);
2373 }
2374 if (!provider.getClass().isAnnotationPresent(ServerInterceptor.class) && !provider.getClass().isAnnotationPresent(ClientInterceptor.class))
2375 {
2376 throw new RuntimeException(Messages.MESSAGES.interceptorClassMustBeAnnotatedWithClass(provider.getClass()));
2377 }
2378 newContracts.put(MessageBodyWriterInterceptor.class, 0);
2379 }
2380 if (isA(provider, MessageBodyReaderInterceptor.class, contracts))
2381 {
2382 if (provider.getClass().isAnnotationPresent(ServerInterceptor.class))
2383 {
2384 if (serverReaderInterceptorRegistry == null)
2385 {
2386 serverReaderInterceptorRegistry = parent.getServerReaderInterceptorRegistry().clone(this);
2387 }
2388 serverReaderInterceptorRegistry.registerLegacy((MessageBodyReaderInterceptor) provider);
2389 }
2390 if (provider.getClass().isAnnotationPresent(ClientInterceptor.class))
2391 {
2392 if (clientReaderInterceptorRegistry == null)
2393 {
2394 clientReaderInterceptorRegistry = parent.getClientReaderInterceptorRegistry().clone(this);
2395 }
2396 clientReaderInterceptorRegistry.registerLegacy((MessageBodyReaderInterceptor) provider);
2397 }
2398 if (!provider.getClass().isAnnotationPresent(ServerInterceptor.class) && !provider.getClass().isAnnotationPresent(ClientInterceptor.class))
2399 {
2400 throw new RuntimeException(Messages.MESSAGES.interceptorClassMustBeAnnotatedWithClass(provider.getClass()));
2401 }
2402 newContracts.put(MessageBodyReaderInterceptor.class, 0);
2403
2404 }
17912405 if (isA(provider, StringConverter.class, contracts))
17922406 {
17932407 addStringConverter((StringConverter) provider);
18462460 newContracts.put(Feature.class, priority);
18472461
18482462 }
1849 }
1850
2463 if (isA(provider, ResponseExceptionMapper.class, contracts))
2464 {
2465 if(contracts!=null) {
2466 Integer prio = contracts.get(ResponseExceptionMapper.class) != null ? contracts.get(ResponseExceptionMapper.class) :
2467 ((ResponseExceptionMapper) provider).getPriority();
2468 newContracts.put(ResponseExceptionMapper.class, prio);
2469 } else {
2470 newContracts.put(ResponseExceptionMapper.class, ((ResponseExceptionMapper) provider).getPriority());
2471 }
2472 }
2473 providerInstances.add(provider);
2474 getClassContracts().put(provider.getClass(), newContracts);
2475 }
2476
18512477 @Override
18522478 public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type)
18532479 {
18542480 Class exceptionType = type;
1855 ExceptionMapper<T> mapper = null;
2481 SortedKey<ExceptionMapper> mapper = null;
18562482 while (mapper == null)
18572483 {
18582484 if (exceptionType == null) break;
1859 mapper = getExceptionMappers().get(exceptionType);
2485 mapper = getSortedExceptionMappers().get(exceptionType);
18602486 if (mapper == null) exceptionType = exceptionType.getSuperclass();
2487 }
2488 return mapper != null ? mapper.getObj() : null;
2489 }
2490
2491 public <T extends Throwable> ClientExceptionMapper<T> getClientExceptionMapper(Class<T> type)
2492 {
2493 return getClientExceptionMappers().get(type);
2494 }
2495
2496 // @Override
2497 public <T> AsyncResponseProvider<T> getAsyncResponseProvider(Class<T> type)
2498 {
2499 Class asyncType = type;
2500 AsyncResponseProvider<T> mapper = null;
2501 while (mapper == null)
2502 {
2503 if (asyncType == null) break;
2504 mapper = getAsyncResponseProviders().get(asyncType);
2505 if (mapper == null) asyncType = asyncType.getSuperclass();
2506 }
2507 return mapper;
2508 }
2509
2510 // @Override
2511 public <T> AsyncStreamProvider<T> getAsyncStreamProvider(Class<T> type)
2512 {
2513 Class asyncType = type;
2514 AsyncStreamProvider<T> mapper = null;
2515 while (mapper == null)
2516 {
2517 if (asyncType == null) break;
2518 mapper = getAsyncStreamProviders().get(asyncType);
2519 if (mapper == null) asyncType = asyncType.getSuperclass();
18612520 }
18622521 return mapper;
18632522 }
18842543 }
18852544 return null;
18862545 }
1887
2546
18882547 public Map<MessageBodyWriter<?>, Class<?>> getPossibleMessageBodyWritersMap(Class type, Type genericType, Annotation[] annotations, MediaType accept)
18892548 {
18902549 Map<MessageBodyWriter<?>, Class<?>> map = new HashMap<MessageBodyWriter<?>, Class<?>>();
18942553 if (writer.obj.isWriteable(type, genericType, annotations, accept))
18952554 {
18962555 Class<?> mbwc = writer.obj.getClass();
1897 if (!mbwc.isInterface() && mbwc.getSuperclass() != null && !mbwc.getSuperclass().equals(Object.class) && WeldUtil.isWeldProxy(mbwc)) {
2556 if (!mbwc.isInterface() && mbwc.getSuperclass() != null && !mbwc.getSuperclass().equals(Object.class) && mbwc.isSynthetic()) {
18982557 mbwc = mbwc.getSuperclass();
18992558 }
19002559 Class writerType = Types.getTemplateParameterOfInterface(mbwc, MessageBodyWriter.class);
19042563 }
19052564 return map;
19062565 }
1907
2566
19082567 public <T> MessageBodyWriter<T> getServerMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
19092568 {
19102569 MediaTypeMap<SortedKey<MessageBodyWriter>> availableWriters = getServerMessageBodyWriters();
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Unauthorized (401) is encountered
6 *
7 * @deprecated Replaced by javax.ws.rs.NotAuthorizedException in jaxrs-api module.
8 *
9 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
10 * @see javax.ws.rs.NotAuthorizedException
11 */
12 @Deprecated
13 public class UnauthorizedException extends LoggableFailure
14 {
15 public UnauthorizedException()
16 {
17 super(401);
18 }
19
20 public UnauthorizedException(String s)
21 {
22 super(s, 401);
23 }
24
25 public UnauthorizedException(String s, Response response)
26 {
27 super(s, response);
28 }
29
30 public UnauthorizedException(String s, Throwable throwable, Response response)
31 {
32 super(s, throwable, response);
33 }
34
35 public UnauthorizedException(String s, Throwable throwable)
36 {
37 super(s, throwable, 401);
38 }
39
40 public UnauthorizedException(Throwable throwable)
41 {
42 super(throwable, 401);
43 }
44
45 public UnauthorizedException(Throwable throwable, Response response)
46 {
47 super(throwable, response);
48 }
49
50
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Unauthorized (401) is encountered
6 *
7 * @deprecated Replaced by javax.ws.rs.NotAuthorizedException in jaxrs-api module.
8 *
9 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
10 * @see javax.ws.rs.NotAuthorizedException
11 */
12 @Deprecated
13 public class UnauthorizedException extends LoggableFailure
14 {
15 public UnauthorizedException()
16 {
17 super(401);
18 }
19
20 public UnauthorizedException(String s)
21 {
22 super(s, 401);
23 }
24
25 public UnauthorizedException(String s, Response response)
26 {
27 super(s, response);
28 }
29
30 public UnauthorizedException(String s, Throwable throwable, Response response)
31 {
32 super(s, throwable, response);
33 }
34
35 public UnauthorizedException(String s, Throwable throwable)
36 {
37 super(s, throwable, 401);
38 }
39
40 public UnauthorizedException(Throwable throwable)
41 {
42 super(throwable, 401);
43 }
44
45 public UnauthorizedException(Throwable throwable, Response response)
46 {
47 super(throwable, response);
48 }
49
50
5151 }
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Unsupported Media Type (415) is encountered
6 * JAX-RS now has this exception
7 *
8 * @deprecated Replaced by javax.ws.rs.NotSupportedException in jaxrs-api module.
9 *
10 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
11 * @see javax.ws.rs.NotSupportedException
12 */
13 @Deprecated
14 public class UnsupportedMediaTypeException extends LoggableFailure
15 {
16
17 public UnsupportedMediaTypeException(String s)
18 {
19 super(s, 415);
20 }
21
22 public UnsupportedMediaTypeException(String s, Response response)
23 {
24 super(s, response);
25 }
26
27 public UnsupportedMediaTypeException(String s, Throwable throwable, Response response)
28 {
29 super(s, throwable, response);
30 }
31
32 public UnsupportedMediaTypeException(String s, Throwable throwable)
33 {
34 super(s, throwable, 415);
35 }
36
37 public UnsupportedMediaTypeException(Throwable throwable)
38 {
39 super(throwable, 415);
40 }
41
42 public UnsupportedMediaTypeException(Throwable throwable, Response response)
43 {
44 super(throwable, response);
45 }
46
47
0 package org.jboss.resteasy.spi;
1
2 import javax.ws.rs.core.Response;
3
4 /**
5 * Thrown by RESTEasy when HTTP Unsupported Media Type (415) is encountered
6 * JAX-RS now has this exception
7 *
8 * @deprecated Replaced by javax.ws.rs.NotSupportedException in jaxrs-api module.
9 *
10 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
11 * @see javax.ws.rs.NotSupportedException
12 */
13 @Deprecated
14 public class UnsupportedMediaTypeException extends LoggableFailure
15 {
16
17 public UnsupportedMediaTypeException(String s)
18 {
19 super(s, 415);
20 }
21
22 public UnsupportedMediaTypeException(String s, Response response)
23 {
24 super(s, response);
25 }
26
27 public UnsupportedMediaTypeException(String s, Throwable throwable, Response response)
28 {
29 super(s, throwable, response);
30 }
31
32 public UnsupportedMediaTypeException(String s, Throwable throwable)
33 {
34 super(s, throwable, 415);
35 }
36
37 public UnsupportedMediaTypeException(Throwable throwable)
38 {
39 super(throwable, 415);
40 }
41
42 public UnsupportedMediaTypeException(Throwable throwable, Response response)
43 {
44 super(throwable, response);
45 }
46
47
4848 }
+0
-29
resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/WeldUtil.java less more
0 package org.jboss.resteasy.spi;
1
2 class WeldUtil
3 {
4 private static final String WELD_PROXY_INTERFACE_NAME = "org.jboss.weld.bean.proxy.ProxyObject";
5
6 /**
7 * Whether the given class is a proxy created by Weld or not. This is
8 * the case if the given class implements the interface
9 * {@code org.jboss.weld.bean.proxy.ProxyObject}.
10 *
11 * This is needed because of https://issues.jboss.org/browse/WELD-1539 and
12 * https://issues.jboss.org/browse/WELD-1914 which are unsolved.
13 *
14 * @param clazz the class of interest
15 *
16 * @return {@code true} if the given class is a Weld proxy,
17 * {@code false} otherwise
18 */
19 static boolean isWeldProxy(Class<?> clazz) {
20 for ( Class<?> implementedInterface : clazz.getInterfaces() ) {
21 if ( implementedInterface.getName().equals( WELD_PROXY_INTERFACE_NAME ) ) {
22 return true;
23 }
24 }
25
26 return false;
27 }
28 }
0 package org.jboss.resteasy.spi.interception;
1
2 import java.lang.reflect.Method;
3
4 /**
5 * Implemented interface that can trigger the addition of an interceptor
6 *
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 *
10 * @deprecated The Resteasy interceptor facility introduced in release 2.x
11 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
12 *
13 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
14 */
15 @Deprecated
16 public interface AcceptedByMethod
17 {
18 public boolean accept(Class declaring, Method method);
19 }
0 package org.jboss.resteasy.spi.interception;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4
5 /**
6 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7 * @version $Revision: 1 $
8 *
9 * @deprecated The Resteasy interceptor facility introduced in release 2.x
10 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
11 *
12 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
13 */
14 @Deprecated
15 public interface ClientExecutionContext
16 {
17 ClientRequest getRequest();
18
19 ClientResponse proceed() throws Exception;
20 }
0 package org.jboss.resteasy.spi.interception;
1
2 import org.jboss.resteasy.client.ClientResponse;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 *
8 * @deprecated The Resteasy interceptor facility introduced in release 2.x
9 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
10 *
11 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
12 */
13 @Deprecated
14 public interface ClientExecutionInterceptor
15 {
16 ClientResponse execute(ClientExecutionContext ctx) throws Exception;
17 }
0 package org.jboss.resteasy.spi.interception;
1
2 import javax.ws.rs.core.MediaType;
3 import java.lang.annotation.Annotation;
4
5 /**
6 * Part of a generic decorator framework.
7 * <p/>
8 * Decorate a target. For example, decorate a JAXB Marshaller with property values.
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 public interface DecoratorProcessor<T, A extends Annotation>
14 {
15 /**
16 * @param target i.e. a Marshaller instance
17 * @param annotation the annotation that triggered the decorator
18 * @param type
19 * @param annotations
20 * @param mediaType
21 * @return should never return null
22 */
23 T decorate(T target, A annotation, Class type, Annotation[] annotations, MediaType mediaType);
24 }
0 package org.jboss.resteasy.spi.interception;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.lang.annotation.Annotation;
8 import java.lang.reflect.Type;
9
10 /**
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @version $Revision: 1 $
13 *
14 * @deprecated The Resteasy interceptor facility introduced in release 2.x
15 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
16 *
17 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
18 */
19 @Deprecated
20 public interface MessageBodyReaderContext
21 {
22 Class getType();
23
24 void setType(Class type);
25
26 Type getGenericType();
27
28 void setGenericType(Type genericType);
29
30 Annotation[] getAnnotations();
31
32 void setAnnotations(Annotation[] annotations);
33
34 MediaType getMediaType();
35
36 void setMediaType(MediaType mediaType);
37
38 MultivaluedMap<String, String> getHeaders();
39
40 InputStream getInputStream();
41
42 void setInputStream(InputStream is);
43
44 /**
45 * Allows you to pass values back and forth between interceptors
46 * On the server side, this is the HttpRequest attributes, on the client side, this is the ClientRequest/ClientResponse
47 * attributes.
48 *
49 * @return
50 */
51 Object getAttribute(String attribute);
52
53 void setAttribute(String name, Object value);
54
55 void removeAttribute(String name);
56
57 Object proceed() throws IOException, WebApplicationException;
58 }
0 package org.jboss.resteasy.spi.interception;
1
2 import javax.ws.rs.WebApplicationException;
3 import java.io.IOException;
4
5 /**
6 * Wraps around invocations of MessageBodyReader.readFrom().
7 *
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 *
11 * @deprecated The Resteasy interceptor facility introduced in release 2.x
12 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
13 *
14 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
15 * @see javax.ws.rs.ext.ReaderInterceptor
16 */
17 @Deprecated
18 public interface MessageBodyReaderInterceptor
19 {
20 /**
21 * @param context
22 * @return the object read
23 * @throws IOException
24 * @throws WebApplicationException
25 */
26 Object read(MessageBodyReaderContext context) throws IOException, WebApplicationException;
27
28 }
0 package org.jboss.resteasy.spi.interception;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import java.io.IOException;
6 import java.io.OutputStream;
7 import java.lang.annotation.Annotation;
8 import java.lang.reflect.Type;
9
10 /**
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @version $Revision: 1 $
13 *
14 * @deprecated The Resteasy interceptor facility introduced in release 2.x
15 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
16 *
17 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
18 */
19 @Deprecated
20 public interface MessageBodyWriterContext
21 {
22 Object getEntity();
23
24 void setEntity(Object entity);
25
26 Class getType();
27
28 void setType(Class type);
29
30 Type getGenericType();
31
32 void setGenericType(Type genericType);
33
34 Annotation[] getAnnotations();
35
36 void setAnnotations(Annotation[] annotations);
37
38 MediaType getMediaType();
39
40 void setMediaType(MediaType mediaType);
41
42 MultivaluedMap<String, Object> getHeaders();
43
44 OutputStream getOutputStream();
45
46 public void setOutputStream(OutputStream os);
47
48 /**
49 * Allows you to pass values back and forth between interceptors
50 * On the server side, this is the HttpRequest attributes, on the client side, this is the ClientRequest/ClientResponse
51 * attributes.
52 *
53 * @return
54 */
55 Object getAttribute(String attribute);
56
57 void setAttribute(String name, Object value);
58
59 void removeAttribute(String name);
60
61 void proceed() throws IOException, WebApplicationException;
62 }
0 package org.jboss.resteasy.spi.interception;
1
2 import javax.ws.rs.WebApplicationException;
3 import java.io.IOException;
4
5 /**
6 * Wraps around invocations of MessageBodyWriter.writeTo()
7 *
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 *
11 * @deprecated The Resteasy interceptor facility introduced in release 2.x
12 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
13 *
14 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
15 * @see javax.ws.rs.ext.WriterInterceptor
16 */
17 @Deprecated
18 public interface MessageBodyWriterInterceptor
19 {
20 void write(MessageBodyWriterContext context) throws IOException, WebApplicationException;
21
22 }
0 package org.jboss.resteasy.spi.interception;
1
2 import org.jboss.resteasy.core.ServerResponse;
3
4 /**
5 * Invoked in order, gives you access to the response before MessageBodyReader and Writers get invoked.
6 *
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 *
10 * @deprecated The Resteasy interceptor facility introduced in release 2.x
11 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
12 *
13 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
14 */
15 @Deprecated
16 public interface PostProcessInterceptor
17 {
18 void postProcess(ServerResponse response);
19 }
0 package org.jboss.resteasy.spi.interception;
1
2 import org.jboss.resteasy.core.ResourceMethodInvoker;
3 import org.jboss.resteasy.core.ServerResponse;
4 import org.jboss.resteasy.spi.Failure;
5 import org.jboss.resteasy.spi.HttpRequest;
6
7 import javax.ws.rs.WebApplicationException;
8
9 /**
10 * Executed before resource method (not resource locator methods though!)
11 * <p/>
12 * The interceptor can decide to return its own response. This will result in not invoking the resource method.
13 *
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 *
17 * @deprecated The Resteasy interceptor facility introduced in release 2.x
18 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
19 *
20 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
21 */
22 @Deprecated
23 public interface PreProcessInterceptor
24 {
25 /**
26 * Preprocess resource method invocation
27 *
28 * @param request
29 * @return null unless the interceptor is returning its own response
30 */
31 ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException;
32 }
0 /**
1 * JAX-RS specification 1.1 ({@link <a href="https://jcp.org/en/jsr/detail?id=311">https://jcp.org/en/jsr/detail?id=311</a>})
2 * had no interceptor framework, so Resteasy release 2.x provided one.
3 *
4 * However, JAX-RS specification 2.0
5 * ({@link <a href="https://www.jcp.org/aboutJava/communityprocess/final/jsr339/index.html">https://www.jcp.org/aboutJava/communityprocess/final/jsr339/index.html</a>})
6 * introduced an official interceptor/filter framework, so the older Resteasy interceptor framework is now deprecated.
7 *
8 * The relevant interfaces are defined in the javax.ws.rs.ext package of the jaxrs-api module.
9 */
10 package org.jboss.resteasy.spi.interception;
00 package org.jboss.resteasy.spi.metadata;
11
2 import java.security.AccessController;
3 import java.security.PrivilegedActionException;
4 import java.security.PrivilegedExceptionAction;
52 import org.jboss.resteasy.annotations.Body;
63 import org.jboss.resteasy.annotations.Form;
74 import org.jboss.resteasy.annotations.Query;
3431 import javax.ws.rs.core.Context;
3532 import javax.ws.rs.core.GenericType;
3633 import javax.ws.rs.core.MediaType;
37
3834 import java.lang.annotation.Annotation;
3935 import java.lang.reflect.AccessibleObject;
4036 import java.lang.reflect.Constructor;
4238 import java.lang.reflect.Method;
4339 import java.lang.reflect.Modifier;
4440 import java.lang.reflect.Type;
41 import java.security.AccessController;
42 import java.security.PrivilegedActionException;
43 import java.security.PrivilegedExceptionAction;
4544 import java.util.ArrayList;
4645 import java.util.HashSet;
4746 import java.util.List;
589588 LogMessages.LOGGER.mediaTypeLacksCharset(mt, method.getMethod().getName());
590589 }
591590 }
592 }
591 }
593592 }
594593 return this;
595594 }
734733 return fromAnnotations(true, clazz);
735734 }
736735
737 private static final String WELD_PROXY_INTERFACE_NAME = "org.jboss.weld.bean.proxy.ProxyObject";
738
739 /**
740 * Whether the given class is a proxy created by Weld or not. This is
741 * the case if the given class implements the interface
742 * {@code org.jboss.weld.bean.proxy.ProxyObject}.
743 *
744 * @param clazz the class of interest
745 *
746 * @return {@code true} if the given class is a Weld proxy,
747 * {@code false} otherwise
748 */
749 private static boolean isWeldProxy(Class<?> clazz) {
750 for ( Class<?> implementedInterface : clazz.getInterfaces() ) {
751 if ( implementedInterface.getName().equals( WELD_PROXY_INTERFACE_NAME ) ) {
752 return true;
753 }
754 }
755
756 return false;
757 }
758
759736 private static ResourceClass fromAnnotations(boolean isLocator, Class<?> clazz)
760737 {
761738 // stupid hack for Weld as it loses generic type information, but retains annotations.
762 if (!clazz.isInterface() && clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class) && isWeldProxy(clazz))
739 if (!clazz.isInterface() && clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class) && clazz.isSynthetic())
763740 {
764741 clazz = clazz.getSuperclass();
765742 }
787764 return builder.buildClass();
788765 }
789766
790 private static Method findAnnotatedInterfaceMethod(Class<?> root, Class<?> iface, Method implementation)
791 {
792 for (Method method : iface.getMethods())
793 {
794 if (method.isSynthetic()) continue;
795
796 if (!method.getName().equals(implementation.getName())) continue;
797 if (method.getParameterTypes().length != implementation.getParameterTypes().length) continue;
798
799 Method actual = Types.getImplementingMethod(root, method);
800 if (!actual.equals(implementation)) continue;
801
802 if (method.isAnnotationPresent(Path.class) || IsHttpMethod.getHttpMethods(method) != null)
803 return method;
804
805 }
806 for (Class<?> extended : iface.getInterfaces())
807 {
808 Method m = findAnnotatedInterfaceMethod(root, extended, implementation);
809 if(m != null)
810 return m;
811 }
812 return null;
813 }
814
815 private static Method findAnnotatedMethod(Class<?> root, Method implementation)
816 {
817 // check the method itself
767 /**
768 * Find the annotated resource method or sub-resource method / sub-resource locator in the class hierarchy.
769 *
770 * @param root The root resource class.
771 * @param implementation The resource method or sub-resource method / sub-resource locator implementation
772 * @return The annotated resource method or sub-resource method / sub-resource locator.
773 */
774 public static Method findAnnotatedMethod(final Class<?> root, final Method implementation)
775 {
776 if (implementation.isSynthetic())
777 {
778 return null;
779 }
780
781 // Check the method itself for JAX-RS annotations
818782 if (implementation.isAnnotationPresent(Path.class) || IsHttpMethod.getHttpMethods(implementation) != null)
783 {
819784 return implementation;
820
821 if (implementation.isAnnotationPresent(Produces.class)
822 || implementation.isAnnotationPresent(Consumes.class))
823 {
824 // completely abort this method
825 return null;
826785 }
827786
828787 // Per http://download.oracle.com/auth/otn-pub/jcp/jaxrs-1.0-fr-oth-JSpec/jaxrs-1.0-final-spec.pdf
829788 // Section 3.2 Annotation Inheritance
830789
831 // Check possible superclass declarations
790 if (implementation.isAnnotationPresent(Produces.class) || implementation.isAnnotationPresent(Consumes.class))
791 {
792 // Abort the search for inherited annotations as specified by the JAX-RS specification.
793 // If a implementation method has any JAX-RS annotations then all the annotations
794 // on the superclass or interface method are ignored.
795 // Therefore a method can be omitted if it is neither a resource method nor a sub-resource method /
796 // sub-resource locator but is annotated with other JAX-RS annotations.
797 return null;
798 }
799
800 // Check super-classes for inherited annotations
832801 for (Class<?> clazz = implementation.getDeclaringClass().getSuperclass(); clazz != null; clazz = clazz.getSuperclass())
833802 {
834 try
835 {
836 Method method = clazz.getDeclaredMethod(implementation.getName(), implementation.getParameterTypes());
837 if (method.isAnnotationPresent(Path.class) || IsHttpMethod.getHttpMethods(method) != null)
838 return method;
839 if (method.isAnnotationPresent(Produces.class)
840 || method.isAnnotationPresent(Consumes.class))
803 final Method overriddenMethod = Types.findOverriddenMethod(implementation.getDeclaringClass(), clazz, implementation);
804 if (overriddenMethod == null)
805 {
806 continue;
807 }
808
809 if (overriddenMethod.isAnnotationPresent(Path.class) || IsHttpMethod.getHttpMethods(overriddenMethod) != null)
810 {
811 return overriddenMethod;
812 }
813 if (overriddenMethod.isAnnotationPresent(Produces.class) || overriddenMethod.isAnnotationPresent(Consumes.class))
814 {
815 // Abort the search for inherited annotations as specified by the JAX-RS specification.
816 // If a implementation method has any JAX-RS annotations then all the annotations
817 // on the superclass or interface method are ignored.
818 // Therefore a method can be omitted if it is neither a resource method nor a sub-resource method /
819 // sub-resource locator but is annotated with other JAX-RS annotations.
820 return null;
821 }
822 }
823
824 // Check implemented interfaces for inherited annotations
825 for (Class<?> clazz = root; clazz != null; clazz = clazz.getSuperclass())
826 {
827 Method overriddenMethod = null;
828
829 for (Class<?> classInterface : clazz.getInterfaces())
830 {
831 final Method overriddenInterfaceMethod = Types.getImplementedInterfaceMethod(root, classInterface, implementation);
832 if (overriddenInterfaceMethod == null)
841833 {
842 // completely abort this method
843 return null;
834 continue;
844835 }
845 }
846 catch (NoSuchMethodException e)
847 {
848 // ignore
849 }
850 }
851
852 // Not found yet, so next check ALL interfaces from the root,
853 // but ensure no redefinition by peer interfaces (ambiguous) to preserve logic found in
854 // original implementation
855 for (Class<?> clazz = root; clazz != null; clazz = clazz.getSuperclass())
856 {
857 Method method = null;
858 for (Class<?> iface : clazz.getInterfaces())
859 {
860 Method m = findAnnotatedInterfaceMethod(root, iface, implementation);
861 if (m != null)
836 if (!overriddenInterfaceMethod.isAnnotationPresent(Path.class) && IsHttpMethod.getHttpMethods(overriddenInterfaceMethod) == null)
862837 {
863 if(method != null && !m.equals(method))
864 throw new RuntimeException(Messages.MESSAGES.ambiguousInheritedAnnotations(implementation));
865 method = m;
838 if (overriddenInterfaceMethod.isAnnotationPresent(Produces.class) || overriddenInterfaceMethod.isAnnotationPresent(Consumes.class))
839 {
840 // Abort the search for inherited annotations as specified by the JAX-RS specification.
841 // If a implementation method has any JAX-RS annotations then all the annotations
842 // on the superclass or interface method are ignored.
843 // Therefore a method can be omitted if it is neither a resource method nor a sub-resource method /
844 // sub-resource locator but is annotated with other JAX-RS annotations.
845 return null;
846 } else {
847 continue;
848 }
866849 }
867 }
868 if (method != null)
869 return method;
870 }
850 // Ensure no redefinition by peer interfaces (ambiguous) to preserve logic found in
851 // original implementation
852 if (overriddenMethod != null && !overriddenInterfaceMethod.equals(overriddenMethod))
853 {
854 throw new RuntimeException(Messages.MESSAGES.ambiguousInheritedAnnotations(implementation));
855 }
856
857 overriddenMethod = overriddenInterfaceMethod;
858 }
859
860 if (overriddenMethod != null)
861 {
862 return overriddenMethod;
863 }
864 }
865
871866 return null;
872867 }
873868
4242 {
4343 return asynchronous;
4444 }
45
46 public void markAsynchronous()
47 {
48 asynchronous = true;
49 }
4550 }
0 package org.jboss.resteasy.test;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientRequestFactory;
4 import org.jboss.resteasy.client.ProxyFactory;
5 import org.jboss.resteasy.util.PortProvider;
6
7 import java.net.MalformedURLException;
8 import java.net.URI;
9 import java.net.URL;
10
11 /**
12 * Test utility class
13 *
14 * @author <a href="justin@justinedelson.com">Justin Edelson</a>
15 * @version $Revision$
16 */
17 public class TestPortProvider
18 {
19 /**
20 * Create a Resteasy ClientRequest object using the configured port.
21 *
22 * @param path the request path
23 * @return the ClientRequest object
24 */
25 public static ClientRequest createClientRequest(String path)
26 {
27 return new ClientRequest(generateURL(path));
28 }
29
30 public static ClientRequest createClientRequest(ClientRequestFactory factory, String path)
31 {
32 return factory.createRequest(generateURL(path));
33 }
34
35 /**
36 * Create a Resteasy client proxy with an empty base request path.
37 *
38 * @param clazz the client interface class
39 * @return the proxy object
40 */
41 public static <T> T createProxy(Class<T> clazz)
42 {
43 return createProxy(clazz, "");
44 }
45
46 /**
47 * Create a Resteasy client proxy.
48 *
49 * @param clazz the client interface class
50 * @return the proxy object
51 * @path the base request path
52 */
53 public static <T> T createProxy(Class<T> clazz, String path)
54 {
55 return ProxyFactory.create(clazz, generateURL(path));
56 }
57
58 /**
59 * Create a URI for the provided path, using the configured port
60 *
61 * @param path the request path
62 * @return a full URI
63 */
64 public static URI createURI(String path)
65 {
66 return URI.create(generateURL(path));
67 }
68
69 /**
70 * Create a URL for the provided path, using the configured port
71 *
72 * @param path the request path
73 * @return a full URL
74 */
75 public static URL createURL(String path) throws MalformedURLException
76 {
77 return new URL(generateURL(path));
78 }
79
80 /**
81 * Generate a base URL incorporating the configured port.
82 *
83 * @return a full URL
84 */
85 public static String generateBaseUrl()
86 {
87 return generateURL("");
88 }
89
90 /**
91 * Generate a URL incorporating the configured port.
92 *
93 * @param path the path
94 * @return a full URL
95 */
96 public static String generateURL(String path)
97 {
98 return String.format("http://%s:%d%s", getHost(), getPort(), path);
99 }
100
101 /**
102 * Look up the configured port number, first checking an environment variable (RESTEASY_PORT),
103 * then a system property (org.jboss.resteasy.port), and finally the default port (8081).
104 *
105 * @return the port number specified in either the environment or system properties
106 */
107 public static int getPort()
108 {
109 return PortProvider.getPort();
110 }
111
112 /**
113 * Look up the configured hostname, first checking an environment variable (RESTEASY_HOST),
114 * then a system property (org.jboss.resteasy.host), and finally the default hostname (localhost).
115 *
116 * @return the host specified in either the environment or system properties
117 */
118 public static String getHost()
119 {
120 return PortProvider.getHost();
121 }
122 }
0 package org.jboss.resteasy.util;
1
2 /**
3 * A CharSequence backed by a char[] (no copy on creation)
4 *
5 */
6 public class ArrayCharSequence implements CharSequence
7 {
8 private final char[] buf;
9 private final int offset;
10 private final int count;
11
12 public ArrayCharSequence(char[] buff)
13 {
14 this(buff, 0, buff.length);
15 }
16
17 public ArrayCharSequence(char[] buff, int count)
18 {
19 this(buff, 0, count);
20 }
21
22 public ArrayCharSequence(char[] buff, int offset, int count)
23 {
24 this.buf = buff;
25 this.offset = offset;
26 this.count = count;
27 }
28
29 public char charAt(int index)
30 {
31 if (index < 0 || index >= count)
32 {
33 throw new StringIndexOutOfBoundsException(index);
34 }
35 return buf[offset + index];
36 }
37
38 public int length()
39 {
40 return count;
41 }
42
43 public CharSequence subSequence(int beginIndex, int endIndex)
44 {
45 if (beginIndex < 0)
46 {
47 throw new StringIndexOutOfBoundsException(beginIndex);
48 }
49 if (endIndex > count)
50 {
51 throw new StringIndexOutOfBoundsException(endIndex);
52 }
53 if (beginIndex > endIndex)
54 {
55 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
56 }
57 return ((beginIndex == 0) && (endIndex == count))
58 ? this
59 : new ArrayCharSequence(buf, offset + beginIndex, endIndex - beginIndex);
60 }
61
62 public String toString()
63 {
64 return new String(this.buf, this.offset, this.count);
65 }
66 }
266266 return builder.toString();
267267 }
268268
269 public static boolean savePathParams(String segment, StringBuilder newSegment, List<String> params)
269 public static boolean savePathParams(String segmentString, StringBuilder newSegment, List<String> params)
270270 {
271271 boolean foundParam = false;
272272 // Regular expressions can have '{' and '}' characters. Replace them to do match
273 segment = PathHelper.replaceEnclosedCurlyBraces(segment);
273 CharSequence segment = PathHelper.replaceEnclosedCurlyBracesCS(segmentString);
274274 Matcher matcher = PathHelper.URI_TEMPLATE_PATTERN.matcher(segment);
275275 int start = 0;
276276 while (matcher.find())
00 package org.jboss.resteasy.util;
11
2 import javax.json.bind.annotation.JsonbAnnotation;
3 import javax.json.bind.annotation.JsonbCreator;
4 import javax.json.bind.annotation.JsonbDateFormat;
5 import javax.json.bind.annotation.JsonbNillable;
6 import javax.json.bind.annotation.JsonbNumberFormat;
7 import javax.json.bind.annotation.JsonbProperty;
8 import javax.json.bind.annotation.JsonbPropertyOrder;
9 import javax.json.bind.annotation.JsonbTransient;
10 import javax.json.bind.annotation.JsonbTypeAdapter;
11 import javax.json.bind.annotation.JsonbTypeDeserializer;
12 import javax.json.bind.annotation.JsonbTypeSerializer;
13 import javax.json.bind.annotation.JsonbVisibility;
214 import javax.ws.rs.CookieParam;
315 import javax.ws.rs.HeaderParam;
416 import javax.ws.rs.MatrixParam;
517 import javax.ws.rs.PathParam;
618 import javax.ws.rs.QueryParam;
719 import javax.ws.rs.core.Context;
20
21 import org.jboss.resteasy.spi.ResteasyProviderFactory;
22
823 import java.lang.annotation.Annotation;
924 import java.lang.reflect.Method;
1025 import java.util.HashMap;
3550 private static final Class[] findJaxRSAnnotations_TYPE = new Class[]{};
3651
3752
53 private static final Class<? extends Annotation>[] JSON_BINDING_ANNOTATIONS =
54 ResteasyProviderFactory.EE8_PREVIEW_MODE ?
55 (Class<? extends Annotation>[]) new Class[]{
56 JsonbCreator.class,
57 JsonbNillable.class,
58 JsonbNumberFormat.class,
59 JsonbVisibility.class,
60 JsonbPropertyOrder.class,
61 JsonbTypeAdapter.class,
62 JsonbTypeSerializer.class,
63 JsonbProperty.class,
64 JsonbDateFormat.class,
65 JsonbTransient.class,
66 JsonbTypeDeserializer.class,
67 JsonbAnnotation.class
68 } : (Class<? extends Annotation>[]) new Class[]{};
69
3870 private FindAnnotation()
3971 {
4072 }
6193 }
6294
6395
64 /**
65 * FIXME Comment this
66 *
67 * @param <T>
68 * @param searchList
69 * @param annotation
70 * @return
71 */
72 public static <T> T findAnnotation(Annotation[] searchList, String... annotations)
73 {
74 if (searchList == null || annotations == null || annotations.length == 0) return null;
75 for (Annotation ann : searchList)
76 {
77 for (String a : annotations)
78 {
79 if (ann.annotationType().getName().equals(a))
80 {
81 return (T) ann;
82 }
83 }
84 }
85 return null;
86 }
87
88
8996 public static Class<? extends Annotation>[] findJaxRSAnnotations(Annotation[] searchList)
9097 {
9198
9299 LinkedList<Class<? extends Annotation>> result = new LinkedList<Class<? extends Annotation>>();
93100
94101 for (Class<? extends Annotation> clazz : JAXRS_ANNOTATIONS)
102 {
103
104 if (findAnnotation(searchList, clazz) != null)
105 result.add(clazz);
106
107 }
108
109 return result.toArray(findJaxRSAnnotations_TYPE);
110
111 }
112
113 public static Class<? extends Annotation>[] findJsonBindingAnnotations(Annotation[] searchList)
114 {
115
116 LinkedList<Class<? extends Annotation>> result = new LinkedList<Class<? extends Annotation>>();
117
118 for (Class<? extends Annotation> clazz : JSON_BINDING_ANNOTATIONS)
95119 {
96120
97121 if (findAnnotation(searchList, clazz) != null)
00 package org.jboss.resteasy.util;
11
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3 import org.jboss.resteasy.spi.StringConverter;
4
25 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.RuntimeDelegate;
37 import java.util.Set;
48
59 /**
140140 public static final int SC_TEMPORARY_REDIRECT = 307;
141141
142142 /**
143 * Status code (308) indicating that the requested resource
144 * resides permanently under a different URI. The permanent URI
145 * <em>SHOULD</em> be given by the <code><em>Location</em></code>
146 * field in the response.
147 */
148
149 public static final int SC_PERMANENT_REDIRECT = 308;
150
151 /**
143152 * Status code (400) indicating the request sent by the client was
144153 * syntactically incorrect.
145154 */
2121 */
2222 public class MediaTypeHelper
2323 {
24 private static final MediaTypeComparator COMPARATOR = new MediaTypeComparator();
25
2426 @SuppressWarnings(value = "unchecked")
2527 public static MediaType getConsumes(Class declaring, AccessibleObject method)
2628 {
3335 return MediaType.valueOf(consume.value()[0]);
3436 }
3537
36 public static MediaType[] getProduces(Class declaring, Method method)
38 public static MediaType getProduces(Class declaring, Method method)
3739 {
3840 return getProduces(declaring, method, null);
3941 }
4042
4143 @SuppressWarnings(value = "unchecked")
42 public static MediaType[] getProduces(Class declaring, Method method, MediaType defaultProduces)
44 public static MediaType getProduces(Class declaring, Method method, MediaType defaultProduces)
4345 {
4446 Produces consume = method.getAnnotation(Produces.class);
4547 if (consume == null)
4648 {
4749 consume = (Produces) declaring.getAnnotation(Produces.class);
4850 }
49 if (consume == null)
50 {
51 if (defaultProduces != null)
52 {
53 return new MediaType[]{defaultProduces};
54 } else {
55 return null;
56 }
57 }
58 MediaType[] mediaTypes = new MediaType[consume.value().length];
59 for(int i = 0; i< consume.value().length;i++){
60 mediaTypes[i] = MediaType.valueOf(consume.value()[i]);
61 }
62 return mediaTypes.length != 0 ? mediaTypes : null;
51 if (consume == null) return defaultProduces;
52 return MediaType.valueOf(consume.value()[0]);
6353 }
6454
6555 public static float getQ(MediaType type)
179169
180170 public static int compareWeight(MediaType one, MediaType two)
181171 {
182 return new MediaTypeComparator().compare(one, two);
172 return COMPARATOR.compare(one, two);
183173 }
184174
185175 public static boolean sameWeight(MediaType one, MediaType two)
186176 {
187 return new MediaTypeComparator().compare(one, two) == 0;
177 return COMPARATOR.compare(one, two) == 0;
188178 }
189179
190180 public static void sortByWeight(List<MediaType> types)
191181 {
192182 if (types == null || types.size() <= 1) return;
193 Collections.sort(types, new MediaTypeComparator());
183 Collections.sort(types, COMPARATOR);
194184 }
195185
196186 public static MediaType getBestMatch(List<MediaType> desired, List<MediaType> provided)
7070 return new String(chars);
7171 }
7272
73 /**
74 * A cheaper (memory-wise) version of replaceEnclosedCurlyBraces(String str)
75 */
76 public static CharSequence replaceEnclosedCurlyBracesCS(String str)
77 {
78 int open = 0;
79 CharSequence cs = str;
80 char[] chars = null;
81 for (int i = 0; i < str.length(); i++)
82 {
83 if (cs.charAt(i) == '{')
84 {
85 if (open != 0) {
86 if (cs == str) {
87 chars = str.toCharArray();
88 cs = new ArrayCharSequence(chars);
89 }
90 chars[i] = openCurlyReplacement;
91 }
92 open++;
93 }
94 else if (cs.charAt(i) == '}')
95 {
96 open--;
97 if (open != 0)
98 {
99 if (cs == str) {
100 chars = str.toCharArray();
101 cs = new ArrayCharSequence(chars);
102 }
103 chars[i] = closeCurlyReplacement;
104 }
105 }
106 }
107 return cs;
108 }
109
110
73111 public static String recoverEnclosedCurlyBraces(String str)
74112 {
75113 return str.replace(openCurlyReplacement, '{').replace(closeCurlyReplacement, '}');
00 package org.jboss.resteasy.util;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
13
24 import java.lang.reflect.Array;
35 import java.lang.reflect.GenericArrayType;
68 import java.lang.reflect.Type;
79 import java.lang.reflect.TypeVariable;
810 import java.lang.reflect.WildcardType;
11 import java.util.Arrays;
912 import java.util.HashMap;
1013 import java.util.Map;
11
12 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
1314
1415 /**
1516 * Type conversions and generic type manipulations
194195 return intfMethod;
195196 }
196197
198 /**
199 * Find the by a method implementation implemented interface method.
200 *
201 * @param root The root class of the class hierarchy.
202 * @param iface The containing interface of the implemented method in the class hierarchy.
203 * @param implementation The method implementation.
204 * @return The implemented method.
205 */
206 public static Method getImplementedInterfaceMethod(final Class<?> root, final Class<?> iface, final Method implementation)
207 {
208 Method overriddenInterfaceMethod = findOverriddenMethod(root, iface, implementation);
209 if (overriddenInterfaceMethod != null) {
210 return overriddenInterfaceMethod;
211 }
212
213 for (Class<?> extended : iface.getInterfaces()) {
214 overriddenInterfaceMethod = getImplementedInterfaceMethod(root, extended, implementation);
215
216 if (overriddenInterfaceMethod != null) {
217 return overriddenInterfaceMethod;
218 }
219 }
220
221 return null;
222 }
223
224 /**
225 * Find the by a method implementation overridden superclass method.
226 *
227 * @param root The root class of the class hierarchy.
228 * @param superClass The containing class of the overridden method in the class hierarchy.
229 * @param implementation The method implementation.
230 * @return The overridden method.
231 */
232 public static Method findOverriddenMethod(final Class<?> root, final Class<?> superClass, final Method implementation)
233 {
234 // Check if the overridden method exists without generics
235 try
236 {
237 final Method method = superClass.getDeclaredMethod(implementation.getName(), implementation.getParameterTypes());
238 return method;
239 }
240 catch (NoSuchMethodException e)
241 {
242 // ignore
243 }
244
245 // Check if the overridden method exists with generics
246 final Map<TypeVariable<?>, Type> genericTypeMap = populateParameterizedMap(root, superClass);
247
248 for (Method superClassMethod : superClass.getDeclaredMethods())
249 {
250 if (superClassMethod.isSynthetic())
251 {
252 continue;
253 }
254 if (!implementation.getName().equals(superClassMethod.getName()) || implementation.getParameterCount() != superClassMethod.getParameterCount())
255 {
256 continue;
257 }
258
259 final Type[] actualMethodParameters = extractTypeVariables(genericTypeMap, superClassMethod.getGenericParameterTypes());
260 if (Arrays.equals(implementation.getGenericParameterTypes(), actualMethodParameters))
261 {
262 return superClassMethod;
263 }
264 }
265
266 return null;
267 }
197268
198269 public static Class<?> getRawType(Type type)
199270 {
440511 {
441512 if (Object.class.equals(root)) return null;
442513
443 Map<String, Type> typeVarMap = populateParameterizedMap(root, rootType);
514 Map<TypeVariable<?>, Type> typeVarMap = populateParameterizedMap(root, rootType);
444515
445516 Class<?> superclass = root.getSuperclass();
446517 Type genericSuper = root.getGenericSuperclass();
471542 return null;
472543 }
473544
474 private static Map<String, Type> populateParameterizedMap(Class<?> root, ParameterizedType rootType)
475 {
476 Map<String, Type> typeVarMap = new HashMap<String, Type>();
545 private static Map<TypeVariable<?>, Type> populateParameterizedMap(Class<?> root, ParameterizedType rootType)
546 {
547 Map<TypeVariable<?>, Type> typeVarMap = new HashMap<>();
477548 if (rootType != null)
478549 {
479550 TypeVariable<? extends Class<?>>[] vars = root.getTypeParameters();
480551 for (int i = 0; i < vars.length; i++)
481552 {
482 typeVarMap.put(vars[i].getName(), rootType.getActualTypeArguments()[i]);
553 typeVarMap.put(vars[i], rootType.getActualTypeArguments()[i]);
483554 }
484555 }
485556 return typeVarMap;
486557 }
487558
559 /**
560 * Create a mapping for generic types to actual types between two classes / interfaces of a type hierarchy.
561 *
562 * @param root The root class / interface of the type hierarchy.
563 * @param superClass A superclass / interface of the type hierarchy.
564 * @return The Mapping for generic types to actual types.
565 */
566 public static Map<TypeVariable<?>, Type> populateParameterizedMap(final Class<?> root, final Class<?> superClass)
567 {
568 final Type[] types = Types.findParameterizedTypes(root, superClass);
569 final TypeVariable<? extends Class<?>>[] typeParameters = superClass.getTypeParameters();
570
571 final Map<TypeVariable<?>, Type> genericTypeMap = new HashMap<>();
572 if (typeParameters != null && types != null)
573 {
574 int i = 0;
575 while (i < types.length)
576 {
577 genericTypeMap.put(typeParameters[i], types[i]);
578 i++;
579 }
580 while (i < typeParameters.length)
581 {
582 genericTypeMap.put(typeParameters[i], typeParameters[i].getGenericDeclaration());
583 i++;
584 }
585 }
586
587 return genericTypeMap;
588 }
488589
489590 public static Type[] findInterfaceParameterizedTypes(Class<?> root, ParameterizedType rootType, Class<?> searchedForInterface)
490591 {
491 Map<String, Type> typeVarMap = populateParameterizedMap(root, rootType);
592 Map<TypeVariable<?>, Type> typeVarMap = populateParameterizedMap(root, rootType);
492593
493594 for (int i = 0; i < root.getInterfaces().length; i++)
494595 {
517618 return recurseSuperclassForInterface(searchedForInterface, typeVarMap, genericSuper, superclass);
518619 }
519620
520 private static Type[] recurseSuperclassForInterface(Class<?> searchedForInterface, Map<String, Type> typeVarMap, Type genericSub, Class<?> sub)
621 private static Type[] recurseSuperclassForInterface(Class<?> searchedForInterface, Map<TypeVariable<?>, Type> typeVarMap, Type genericSub, Class<?> sub)
521622 {
522623 if (genericSub instanceof ParameterizedType)
523624 {
539640 return null;
540641 }
541642
542 private static Type[] extractTypeVariables(Map<String, Type> typeVarMap, Type[] types)
543 {
544 for (int j = 0; j < types.length; j++)
545 {
546 if (types[j] instanceof TypeVariable)
547 {
548 TypeVariable tv = (TypeVariable) types[j];
549 types[j] = typeVarMap.get(tv.getName());
643 /**
644 * Resolve generic types to actual types.
645 *
646 * @param typeVarMap The mapping for generic types to actual types.
647 * @param types The types to resolve.
648 * @return An array of resolved method parameter types in declaration order.
649 */
650 private static Type[] extractTypeVariables(final Map<TypeVariable<?>, Type> typeVarMap, final Type[] types)
651 {
652 final Type[] resolvedMethodParameterTypes = new Type[types.length];
653
654 for (int i = 0; i < types.length; i++)
655 {
656 final Type methodParameterType = types[i];
657
658 if (methodParameterType instanceof TypeVariable<?>)
659 {
660 resolvedMethodParameterTypes[i] = typeVarMap.get(methodParameterType);
550661 }
551662 else
552663 {
553 types[j] = types[j];
554 }
555 }
556 return types;
557 }
558
559 private static Type[] extractTypes(Map<String, Type> typeVarMap, Type genericSub)
664 resolvedMethodParameterTypes[i] = methodParameterType;
665 }
666 }
667
668 return resolvedMethodParameterTypes;
669 }
670
671 private static Type[] extractTypes(Map<TypeVariable<?>, Type> typeVarMap, Type genericSub)
560672 {
561673 if (genericSub instanceof ParameterizedType)
562674 {
563675 ParameterizedType param = (ParameterizedType) genericSub;
564676 Type[] types = param.getActualTypeArguments();
565 Type[] returnTypes = new Type[types.length];
566 System.arraycopy(types, 0, returnTypes, 0, types.length);
567 extractTypeVariables(typeVarMap, returnTypes);
677
678 Type[] returnTypes = extractTypeVariables(typeVarMap, types);
568679 return returnTypes;
569680 }
570681 else
+0
-21
resteasy-jaxrs/src/main/resources/META-INF/services/javax.ws.rs.ext.Providers less more
0 org.jboss.resteasy.plugins.providers.DataSourceProvider
1 org.jboss.resteasy.plugins.providers.DocumentProvider
2 org.jboss.resteasy.plugins.providers.DefaultTextPlain
3 org.jboss.resteasy.plugins.providers.DefaultNumberWriter
4 org.jboss.resteasy.plugins.providers.StringTextStar
5 org.jboss.resteasy.plugins.providers.SourceProvider
6 org.jboss.resteasy.plugins.providers.InputStreamProvider
7 org.jboss.resteasy.plugins.providers.ReaderProvider
8 org.jboss.resteasy.plugins.providers.ByteArrayProvider
9 org.jboss.resteasy.plugins.providers.FormUrlEncodedProvider
10 org.jboss.resteasy.plugins.providers.JaxrsFormProvider
11 org.jboss.resteasy.plugins.providers.FileProvider
12 org.jboss.resteasy.plugins.providers.FileRangeWriter
13 org.jboss.resteasy.plugins.providers.StreamingOutputProvider
14 org.jboss.resteasy.plugins.providers.IIOImageProvider
15 org.jboss.resteasy.plugins.interceptors.CacheControlFeature
16 org.jboss.resteasy.plugins.interceptors.ClientContentEncodingAnnotationFeature
17 org.jboss.resteasy.plugins.interceptors.ServerContentEncodingAnnotationFeature
18 org.jboss.resteasy.plugins.interceptors.MessageSanitizerContainerResponseFilter
19
20
0 org.jboss.resteasy.plugins.providers.DataSourceProvider
1 org.jboss.resteasy.plugins.providers.DocumentProvider
2 org.jboss.resteasy.plugins.providers.DefaultTextPlain
3 org.jboss.resteasy.plugins.providers.DefaultNumberWriter
4 org.jboss.resteasy.plugins.providers.DefaultBooleanWriter
5 org.jboss.resteasy.plugins.providers.StringTextStar
6 org.jboss.resteasy.plugins.providers.SourceProvider
7 org.jboss.resteasy.plugins.providers.InputStreamProvider
8 org.jboss.resteasy.plugins.providers.ReaderProvider
9 org.jboss.resteasy.plugins.providers.ByteArrayProvider
10 org.jboss.resteasy.plugins.providers.FormUrlEncodedProvider
11 org.jboss.resteasy.plugins.providers.JaxrsFormProvider
12 org.jboss.resteasy.plugins.providers.CompletionStageProvider
13 org.jboss.resteasy.plugins.providers.ReactiveStreamProvider
14 org.jboss.resteasy.plugins.providers.FileProvider
15 org.jboss.resteasy.plugins.providers.FileRangeWriter
16 org.jboss.resteasy.plugins.providers.StreamingOutputProvider
17 org.jboss.resteasy.plugins.providers.IIOImageProvider
18 org.jboss.resteasy.plugins.interceptors.CacheControlFeature
19 org.jboss.resteasy.plugins.interceptors.encoding.ClientContentEncodingAnnotationFeature
20 org.jboss.resteasy.plugins.interceptors.encoding.ServerContentEncodingAnnotationFeature
21 org.jboss.resteasy.plugins.interceptors.encoding.MessageSanitizerContainerResponseFilter
22
0 org.jboss.resteasy.plugins.providers.DataSourceProvider
1 org.jboss.resteasy.plugins.providers.DocumentProvider
2 org.jboss.resteasy.plugins.providers.DefaultTextPlain
3 org.jboss.resteasy.plugins.providers.DefaultNumberWriter
4 org.jboss.resteasy.plugins.providers.DefaultBooleanWriter
5 org.jboss.resteasy.plugins.providers.StringTextStar
6 org.jboss.resteasy.plugins.providers.SourceProvider
7 org.jboss.resteasy.plugins.providers.InputStreamProvider
8 org.jboss.resteasy.plugins.providers.ReaderProvider
9 org.jboss.resteasy.plugins.providers.ByteArrayProvider
10 org.jboss.resteasy.plugins.providers.FormUrlEncodedProvider
11 org.jboss.resteasy.plugins.providers.JaxrsFormProvider
12 org.jboss.resteasy.plugins.providers.CompletionStageProvider
13 org.jboss.resteasy.plugins.providers.ReactiveStreamProvider
14 org.jboss.resteasy.plugins.providers.FileProvider
15 org.jboss.resteasy.plugins.providers.FileRangeWriter
16 org.jboss.resteasy.plugins.providers.StreamingOutputProvider
17 org.jboss.resteasy.plugins.providers.IIOImageProvider
18 org.jboss.resteasy.plugins.interceptors.CacheControlFeature
19 org.jboss.resteasy.plugins.interceptors.encoding.ClientContentEncodingAnnotationFeature
20 org.jboss.resteasy.plugins.interceptors.encoding.ServerContentEncodingAnnotationFeature
21 org.jboss.resteasy.plugins.interceptors.encoding.MessageSanitizerContainerResponseFilter
22 org.jboss.resteasy.plugins.providers.sse.SseEventProvider
23 org.jboss.resteasy.plugins.providers.sse.SseEventOutputProvider
24 org.jboss.resteasy.plugins.providers.sse.SseEventSinkInterceptor
25
+0
-18
resteasy-jaxrs-services/pom.xml less more
0 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
2 <modelVersion>4.0.0</modelVersion>
3 <parent>
4 <groupId>org.jboss.resteasy</groupId>
5 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
7 <relativePath>../pom.xml</relativePath>
8 </parent>
9 <artifactId>resteasy-jaxrs-services</artifactId>
10 <name>RESTEasy JAX-RS services</name>
11 <description/>
12 <packaging>jar</packaging>
13
14 <dependencies>
15 </dependencies>
16
17 </project>
+0
-1
resteasy-jaxrs-services/src/main/resources/META-INF/services/javax.ws.rs.ext.RuntimeDelegate less more
0 org.jboss.resteasy.spi.ResteasyProviderFactory
0 <?xml version="1.0"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3 <modelVersion>4.0.0</modelVersion>
4 <parent>
5 <artifactId>resteasy-jaxrs-all</artifactId>
6 <groupId>org.jboss.resteasy</groupId>
7 <version>3.5.0.Final</version>
8 <relativePath>../pom.xml</relativePath>
9 </parent>
10
11 <artifactId>resteasy-jaxrs-testsuite</artifactId>
12 <name>RESTEasy JAX-RS Client/Server Testsuite</name>
13 <build>
14 <plugins>
15 <plugin>
16 <groupId>org.apache.maven.plugins</groupId>
17 <artifactId>maven-deploy-plugin</artifactId>
18 <configuration>
19 <skip>true</skip>
20 </configuration>
21 </plugin>
22 <plugin>
23 <groupId>org.apache.maven.plugins</groupId>
24 <artifactId>maven-install-plugin</artifactId>
25 <configuration>
26 <skip>true</skip>
27 </configuration>
28 </plugin>
29 </plugins>
30 </build>
31
32 <dependencies>
33 <dependency>
34 <groupId>org.jboss.resteasy</groupId>
35 <artifactId>resteasy-jaxrs</artifactId>
36 <version>${project.version}</version>
37 </dependency>
38 <dependency>
39 <groupId>org.jboss.resteasy</groupId>
40 <artifactId>resteasy-client</artifactId>
41 <version>${project.version}</version>
42 </dependency>
43 <dependency>
44 <groupId>org.jboss.resteasy</groupId>
45 <artifactId>resteasy-jaxb-provider</artifactId>
46 <version>${project.version}</version>
47 </dependency>
48 <dependency>
49 <groupId>junit</groupId>
50 <artifactId>junit</artifactId>
51 <scope>compile</scope>
52 </dependency>
53 <dependency>
54 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>tjws</artifactId>
56 <version>${project.version}</version>
57 <exclusions>
58 <exclusion>
59 <groupId>javax.servlet</groupId>
60 <artifactId>servlet-api</artifactId>
61 </exclusion>
62 </exclusions>
63 <scope>test</scope>
64 </dependency>
65 <dependency>
66 <groupId>org.jboss.spec.javax.servlet</groupId>
67 <artifactId>jboss-servlet-api_3.1_spec</artifactId>
68 </dependency>
69 <dependency>
70 <groupId>org.apache.httpcomponents</groupId>
71 <artifactId>httpclient</artifactId>
72 </dependency>
73 <dependency>
74 <groupId>org.jboss.resteasy</groupId>
75 <artifactId>resteasy-undertow</artifactId>
76 <version>${project.version}</version>
77 <scope>test</scope>
78 </dependency>
79 <dependency>
80 <groupId>io.undertow</groupId>
81 <artifactId>undertow-servlet</artifactId>
82 <scope>test</scope>
83 </dependency>
84 <dependency>
85 <groupId>org.jboss.resteasy</groupId>
86 <artifactId>resteasy-jdk-http</artifactId>
87 <version>${project.version}</version>
88 </dependency>
89 <dependency>
90 <groupId>org.jboss.resteasy</groupId>
91 <artifactId>resteasy-wadl</artifactId>
92 <version>${project.version}</version>
93 </dependency>
94 <dependency>
95 <groupId>org.jboss.resteasy</groupId>
96 <artifactId>resteasy-netty4</artifactId>
97 <version>${project.version}</version>
98 </dependency>
99 <dependency>
100 <groupId>io.netty</groupId>
101 <artifactId>netty-all</artifactId>
102 <scope>test</scope>
103 </dependency>
104 <dependency>
105 <groupId>org.javassist</groupId>
106 <artifactId>javassist</artifactId>
107 <scope>test</scope>
108 </dependency>
109 </dependencies>
110
111 <profiles>
112 <profile>
113 <id>default</id>
114 <activation>
115 <activeByDefault>true</activeByDefault>
116 </activation>
117 <build>
118 <plugins>
119 <plugin>
120 <groupId>org.apache.maven.plugins</groupId>
121 <artifactId>maven-surefire-plugin</artifactId>
122 <version>2.17</version>
123 <configuration>
124 <excludes>
125 <exclude>org/jboss/resteasy/test/nextgen/producers/MissingProducerTest.java</exclude>
126 </excludes>
127 </configuration>
128 </plugin>
129 </plugins>
130 </build>
131 </profile>
132 <profile>
133 <id>fork</id>
134 <activation>
135 <property>
136 <name>fork</name>
137 </property>
138 </activation>
139 <build>
140 <plugins>
141 <plugin>
142 <groupId>org.apache.maven.plugins</groupId>
143 <artifactId>maven-surefire-plugin</artifactId>
144 <version>2.17</version>
145 <configuration>
146 <reuseForks>false</reuseForks>
147 </configuration>
148 </plugin>
149 </plugins>
150 </build>
151 </profile>
152 </profiles>
153 </project>
0 package org.jboss.resteasy.test.resteasy_jaxrs.i18n;
1
2 import java.io.InputStream;
3 import java.util.Locale;
4 import java.util.Properties;
5
6 import org.junit.AfterClass;
7 import org.junit.BeforeClass;
8
9 /**
10 *
11 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
12 * @version $Revision: 1.1 $
13 *
14 * Copyright Oct 8, 2014
15 */
16 abstract public class TestMessagesParent
17 {
18 static protected Locale savedLocale;
19 protected Properties properties = new Properties();
20
21 @BeforeClass
22 static public void beforeClass()
23 {
24 savedLocale = Locale.getDefault();
25 }
26
27 @AfterClass
28 static public void afterClass()
29 {
30 Locale.setDefault(savedLocale);
31 System.out.println("Reset default locale to: " + savedLocale);
32 }
33
34 public boolean before(Locale locale, String filename) throws Exception
35 {
36 System.out.println("default locale: " + Locale.getDefault());
37 Locale.setDefault(locale);
38 System.out.println("Set default locale to: " + locale);
39 System.out.println("Messages file: " + filename);
40 InputStream is = getClass().getClassLoader().getResourceAsStream(filename);
41 if (is == null)
42 {
43 return false;
44 }
45 properties.load(is);
46 return getExpectedNumberOfMethods() == properties.size();
47 }
48
49 protected String getExpected(String id, String message, Object... args)
50 {
51 String expected = "RESTEASY" + id + ": " + String.format(replacePositionalSpecifiers(String.class.cast(properties.get(message))), args);
52 System.out.println("expected: " + expected);
53 return expected;
54 }
55
56 protected String replacePositionalSpecifiers(String s)
57 {
58 // System.out.println("before: " + s);
59 int pos0 = s.indexOf("{0}");
60 if (pos0 > -1)
61 {
62 s = s.substring(0, pos0) + "%1$s" + (pos0 + 3 >= s.length() ? "" : s.substring(pos0 + 3));
63 }
64 int pos1 = s.indexOf("{1}");
65 if (pos1 > -1)
66 {
67 s = s.substring(0, pos1) + "%2$s" + (pos1 + 3 >= s.length() ? "" : s.substring(pos1 + 3));
68 }
69 int pos2 = s.indexOf("{2}");
70 if (pos2 > -1)
71 {
72 s = s.substring(0, pos2) + "%3$s" + (pos2 + 3 >= s.length() ? "" : s.substring(pos2 + 3));
73 }
74 // System.out.println("after: " + s);
75 return s;
76 }
77
78 abstract protected int getExpectedNumberOfMethods();
79 abstract protected Locale getLocale();
80 }
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.resteasy.annotations.Body;
3 import org.jboss.resteasy.annotations.LinkHeaderParam;
4 import org.jboss.resteasy.annotations.ResponseObject;
5 import org.jboss.resteasy.annotations.Status;
6 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.client.jaxrs.internal.ClientResponse;
10 import org.jboss.resteasy.core.Dispatcher;
11 import org.jboss.resteasy.test.EmbeddedContainer;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.junit.AfterClass;
14 import org.junit.BeforeClass;
15 import org.junit.Test;
16
17 import javax.ws.rs.GET;
18 import javax.ws.rs.HeaderParam;
19 import javax.ws.rs.Path;
20 import javax.ws.rs.Produces;
21 import javax.ws.rs.core.Context;
22 import javax.ws.rs.core.Response;
23 import javax.ws.rs.core.UriInfo;
24 import java.net.URI;
25
26 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
27
28 /**
29 * @author <a href="mailto:mstefank@redhat.com">Martin Štefanko</a>
30 */
31 public class ResponseObjectTest
32 {
33
34 private static ResteasyClient client;
35 private static ResponseObjectClient responseObjectClient;
36
37 @Path("test")
38 interface ResponseObjectClient
39 {
40 @GET
41 BasicObject get();
42
43 @GET
44 @Path("link-header")
45 HateoasObject performGetBasedOnHeader();
46 }
47
48 @ResponseObject
49 public interface BasicObject
50 {
51 @Status
52 int status();
53
54 @Body
55 String body();
56
57 ClientResponse response();
58
59 @HeaderParam("Content-Type")
60 String contentType();
61 }
62
63 @ResponseObject
64 public interface HateoasObject
65 {
66 @Status
67 int status();
68
69 @LinkHeaderParam(rel = "nextLink")
70 URI nextLink();
71
72 @GET
73 @LinkHeaderParam(rel = "nextLink")
74 String followNextLink();
75 }
76
77 @Path("test")
78 public static class ResponseObjectResource
79 {
80
81 @GET
82 @Produces("text/plain")
83 public String get()
84 {
85 return "ABC";
86 }
87
88 @GET
89 @Path("/link-header")
90 public Response getWithHeader(@Context UriInfo uri)
91 {
92 URI subUri = uri.getAbsolutePathBuilder().path("next-link").build();
93 org.jboss.resteasy.spi.Link link = new org.jboss.resteasy.spi.Link();
94 link.setHref(subUri.toASCIIString());
95 link.setRelationship("nextLink");
96 return Response.noContent().header("Link", link.toString()).build();
97 }
98
99 @GET
100 @Produces("text/plain")
101 @Path("/link-header/next-link")
102 public String getHeaderForward()
103 {
104 return "forwarded";
105 }
106 }
107
108 @BeforeClass
109 public static void before() throws Exception
110 {
111 final Dispatcher dispatcher = EmbeddedContainer.start().getDispatcher();
112 client = new ResteasyClientBuilder().build();
113 dispatcher.getRegistry().addPerRequestResource(ResponseObjectResource.class);
114 responseObjectClient = ProxyBuilder.builder(ResponseObjectClient.class, client.target(generateBaseUrl())).build();
115 }
116
117 @AfterClass
118 public static void after() throws Exception
119 {
120 client.close();
121 EmbeddedContainer.stop();
122 }
123
124 @Test
125 public void testSimple()
126 {
127 BasicObject obj = responseObjectClient.get();
128 org.junit.Assert.assertEquals(HttpResponseCodes.SC_OK, obj.status());
129 org.junit.Assert.assertEquals("The response object doesn't contain the expected string", "ABC", obj.body());
130 org.junit.Assert.assertEquals("The response object doesn't contain the expected header",
131 "text/plain;charset=UTF-8", obj.response().getHeaders().getFirst("Content-Type"));
132 org.junit.Assert.assertEquals("The response object doesn't contain the expected header", "text/plain;charset=UTF-8", obj.contentType());
133 }
134
135 @Test
136 public void testLinkFollow()
137 {
138 HateoasObject obj = responseObjectClient.performGetBasedOnHeader();
139 org.junit.Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, obj.status());
140 org.junit.Assert.assertTrue("The resource was not forwarded", obj.nextLink().getPath().endsWith("next-link"));
141 org.junit.Assert.assertEquals("The resource was not forwarded", "forwarded", obj.followNextLink());
142
143 }
144 }
0 package org.jboss.resteasy.test.client.cache;
1
2 import org.jboss.resteasy.annotations.cache.Cache;
3 import org.jboss.resteasy.client.ProxyFactory;
4 import org.jboss.resteasy.client.cache.CacheFactory;
5 import org.jboss.resteasy.client.cache.LightweightBrowserCache;
6 import org.jboss.resteasy.test.BaseResourceTest;
7 import org.junit.Assert;
8 import org.junit.Before;
9 import org.junit.BeforeClass;
10 import org.junit.Test;
11
12 import javax.ws.rs.GET;
13 import javax.ws.rs.Path;
14 import javax.ws.rs.PathParam;
15 import javax.ws.rs.Produces;
16 import javax.ws.rs.core.CacheControl;
17 import javax.ws.rs.core.Context;
18 import javax.ws.rs.core.EntityTag;
19 import javax.ws.rs.core.Request;
20 import javax.ws.rs.core.Response;
21
22 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
23
24 /**
25 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
26 * @version $Revision: 1 $
27 */
28 public class ClientCacheTest extends BaseResourceTest
29 {
30 private static int count = 0;
31
32 @Path("/cache")
33 public static class MyService
34 {
35 @GET
36 @Produces("text/plain")
37 @Cache(maxAge = 2)
38 public String get()
39 {
40 count++;
41 return "hello world" + count;
42 }
43
44 @Path("/etag/always/good")
45 @GET
46 @Produces("text/plain")
47 public Response getEtagged(@Context Request request)
48 {
49 count++;
50 Response.ResponseBuilder builder = request.evaluatePreconditions(new EntityTag("42"));
51 CacheControl cc = new CacheControl();
52 cc.setMaxAge(2);
53 if (builder != null)
54 {
55 return builder.cacheControl(cc).build();
56 }
57 return Response.ok("hello" + count).cacheControl(cc).tag("42").build();
58 }
59
60 @Path("/etag/never/good")
61 @GET
62 @Produces("text/plain")
63 public Response getEtaggedNeverGood(@Context Request request)
64 {
65 count++;
66 Response.ResponseBuilder builder = request.evaluatePreconditions(new EntityTag("42"));
67 if (builder != null)
68 {
69 return Response.serverError().build();
70 }
71 CacheControl cc = new CacheControl();
72 cc.setMaxAge(2);
73 return Response.ok("hello" + count).cacheControl(cc).tag("32").build();
74 }
75
76 @Path("/etag/always/validate")
77 @GET
78 @Produces("text/plain")
79 public Response getValidateEtagged(@Context Request request)
80 {
81 count++;
82 Response.ResponseBuilder builder = request.evaluatePreconditions(new EntityTag("42"));
83 if (builder != null)
84 {
85 return builder.build();
86 }
87 return Response.ok("hello" + count).tag("42").build();
88 }
89
90 @Path("/cacheit/{id}")
91 @GET
92 @Produces("text/plain")
93 @Cache(maxAge = 3000)
94 public String getCacheit(@PathParam("id") String id)
95 {
96 count++;
97 return "cachecache" + count;
98 }
99
100 }
101
102 @Path("/cache")
103 public static interface MyProxy
104 {
105 @GET
106 @Produces("text/plain")
107 @Cache(maxAge = 2)
108 public String get();
109
110 @Path("/etag/always/good")
111 @GET
112 @Produces("text/plain")
113 public String getAlwaysGoodEtag();
114
115 @Path("/etag/never/good")
116 @GET
117 @Produces("text/plain")
118 public String getNeverGoodEtag();
119
120 @Path("/etag/always/validate")
121 @GET
122 @Produces("text/plain")
123 public String getValidateEtagged();
124
125 @Path("/cacheit/{id}")
126 @GET
127 @Produces("text/plain")
128 @Cache(maxAge = 3000)
129 public String getCacheit(@PathParam("id") String id);
130 }
131
132
133 @BeforeClass
134 public static void setUp() throws Exception
135 {
136 addPerRequestResource(MyService.class);
137 }
138
139 @Before
140 public void reset()
141 {
142 count = 0;
143 }
144
145
146 @Test
147 public void testProxy() throws Exception
148 {
149 MyProxy proxy = ProxyFactory.create(MyProxy.class, generateBaseUrl());
150 CacheFactory.makeCacheable(proxy);
151
152 count = 0;
153 String rtn = null;
154 rtn = proxy.get();
155 Assert.assertEquals("hello world" + 1, rtn);
156 Assert.assertEquals(1, count);
157 rtn = proxy.get();
158 Assert.assertEquals("hello world" + 1, rtn);
159 Assert.assertEquals(1, count);
160 Thread.sleep(2000);
161 rtn = proxy.get();
162 Assert.assertEquals("hello world" + 2, rtn);
163 Assert.assertEquals(2, count);
164 rtn = proxy.get();
165 Assert.assertEquals("hello world" + 2, rtn);
166 Assert.assertEquals(2, count);
167
168 // Test always good etag
169 count = 0;
170 rtn = proxy.getAlwaysGoodEtag();
171 Assert.assertEquals("hello1", rtn);
172 Assert.assertEquals(1, count);
173 rtn = proxy.getAlwaysGoodEtag();
174 Assert.assertEquals("hello1", rtn);
175 Assert.assertEquals(1, count);
176 Thread.sleep(2000);
177 rtn = proxy.getAlwaysGoodEtag();
178 Assert.assertEquals("hello1", rtn);
179 Assert.assertEquals(2, count);
180 rtn = proxy.getAlwaysGoodEtag();
181 Assert.assertEquals("hello1", rtn);
182 Assert.assertEquals(2, count);
183
184 // Test never good etag
185 count = 0;
186 rtn = proxy.getNeverGoodEtag();
187 Assert.assertEquals("hello1", rtn);
188 Assert.assertEquals(1, count);
189 rtn = proxy.getNeverGoodEtag();
190 Assert.assertEquals("hello1", rtn);
191 Assert.assertEquals(1, count);
192 Thread.sleep(2000);
193 rtn = proxy.getNeverGoodEtag();
194 Assert.assertEquals("hello2", rtn);
195 Assert.assertEquals(2, count);
196 rtn = proxy.getNeverGoodEtag();
197 Assert.assertEquals("hello2", rtn);
198 Assert.assertEquals(2, count);
199
200
201 // Test always validate etag
202 count = 0;
203 rtn = proxy.getValidateEtagged();
204 Assert.assertEquals("hello1", rtn);
205 Assert.assertEquals(1, count);
206 rtn = proxy.getValidateEtagged();
207 Assert.assertEquals("hello1", rtn);
208 Assert.assertEquals(2, count);
209 rtn = proxy.getValidateEtagged();
210 Assert.assertEquals("hello1", rtn);
211 Assert.assertEquals(3, count);
212 rtn = proxy.getValidateEtagged();
213 Assert.assertEquals("hello1", rtn);
214 Assert.assertEquals(4, count);
215 }
216
217 @Test
218 public void testMaxSize() throws Exception
219 {
220 MyProxy proxy = ProxyFactory.create(MyProxy.class, generateBaseUrl());
221 LightweightBrowserCache cache = CacheFactory.makeCacheable(proxy);
222 cache.setMaxBytes(20);
223
224 count = 0;
225
226 String rtn = proxy.getCacheit("1");
227 Assert.assertEquals("cachecache" + 1, rtn);
228 Assert.assertEquals(1, count);
229
230 rtn = proxy.getCacheit("1");
231 Assert.assertEquals("cachecache" + 1, rtn);
232 Assert.assertEquals(1, count);
233
234 rtn = proxy.getCacheit("2");
235 Assert.assertEquals("cachecache" + 2, rtn);
236 Assert.assertEquals(2, count);
237
238 rtn = proxy.getCacheit("2");
239 Assert.assertEquals("cachecache" + 2, rtn);
240 Assert.assertEquals(2, count);
241
242 rtn = proxy.getCacheit("1");
243 Assert.assertEquals("cachecache" + 3, rtn);
244 Assert.assertEquals(3, count);
245
246
247 }
248
249 }
0 package org.jboss.resteasy.test.client.core;
1
2 import org.apache.http.client.HttpClient;
3 import org.apache.http.impl.client.DefaultHttpClient;
4 import org.jboss.resteasy.client.ClientExecutor;
5 import org.jboss.resteasy.client.ClientResponse;
6 import org.jboss.resteasy.client.ProxyFactory;
7 import org.jboss.resteasy.client.core.ClientErrorInterceptor;
8 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
9 import org.jboss.resteasy.spi.NoLogWebApplicationException;
10 import org.jboss.resteasy.spi.ResteasyProviderFactory;
11 import org.jboss.resteasy.test.BaseResourceTest;
12 import org.junit.Assert;
13 import org.junit.BeforeClass;
14 import org.junit.Test;
15
16 import javax.ws.rs.Consumes;
17 import javax.ws.rs.GET;
18 import javax.ws.rs.PUT;
19 import javax.ws.rs.Path;
20 import javax.ws.rs.PathParam;
21 import javax.ws.rs.Produces;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.core.Response;
24 import java.net.URI;
25
26 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
27
28 public class ClientErrorInterceptorTest extends BaseResourceTest
29 {
30
31 public static class MyResourceImpl implements MyResource
32 {
33 public String get()
34 {
35 return "hello world";
36 }
37
38 public String error()
39 {
40 Response r = Response.status(404).type("text/plain").entity("there was an error").build();
41 throw new NoLogWebApplicationException(r);
42 }
43
44 @Override
45 public void update(String id, String obj)
46 {
47 Response r = Response.status(404).type("text/plain").entity("there was an error").build();
48 throw new NoLogWebApplicationException(r);
49 }
50 }
51
52 @Path("/test")
53 public static interface MyResource
54 {
55 @GET
56 @Produces("text/plain")
57 public String get();
58
59 @GET
60 @Path("error")
61 @Produces("text/plain")
62 String error();
63
64 @PUT
65 @Path("{id}")
66 @Consumes(MediaType.APPLICATION_XML)
67 void update(@PathParam("id") String id, String obj);
68 }
69
70 @BeforeClass
71 public static void setUp() throws Exception
72 {
73 addPerRequestResource(MyResourceImpl.class);
74 }
75
76 public static class MyClienteErrorInterceptor implements ClientErrorInterceptor
77 {
78 @Override
79 public void handle(ClientResponse<?> response) throws RuntimeException
80 {
81 String errorMessage = response.getEntity(String.class);
82 throw new MyException(errorMessage);
83 }
84 }
85
86 public static class MyException extends RuntimeException
87 {
88 private static final long serialVersionUID = 1L;
89
90 public MyException(String message)
91 {
92 super(message);
93 }
94 }
95
96 @Test
97 public void testStreamClosedWhenGetEntity() throws Exception
98 {
99 HttpClient httpClient = new DefaultHttpClient();
100 ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);
101
102 ResteasyProviderFactory pf = ResteasyProviderFactory.getInstance();
103 pf.addClientErrorInterceptor(new MyClienteErrorInterceptor());
104
105 MyResource proxy = ProxyFactory.create(MyResource.class, URI.create(generateBaseUrl()), clientExecutor, pf);
106
107 try
108 {
109 proxy.error();
110 Assert.fail();
111 }
112 catch (MyException e)
113 {
114 Assert.assertEquals("there was an error", e.getMessage());
115 }
116 }
117
118 @Test
119 public void testStreamClosedWhenGetEntityForVoid() throws Exception
120 {
121 HttpClient httpClient = new DefaultHttpClient();
122 ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);
123
124 ResteasyProviderFactory pf = ResteasyProviderFactory.getInstance();
125 pf.addClientErrorInterceptor(new MyClienteErrorInterceptor());
126
127 MyResource proxy = ProxyFactory.create(MyResource.class, URI.create(generateBaseUrl()), clientExecutor, pf);
128
129 try
130 {
131 proxy.update("1", "hello");
132 Assert.fail();
133 }
134 catch (MyException e)
135 {
136 Assert.assertEquals("there was an error", e.getMessage());
137 }
138 }
139 }
0 package org.jboss.resteasy.test.client.exception;
1
2 import org.apache.http.ConnectionClosedException;
3 import org.apache.http.HttpException;
4 import org.apache.http.MalformedChunkCodingException;
5 import org.apache.http.MethodNotSupportedException;
6 import org.apache.http.NoHttpResponseException;
7 import org.apache.http.ProtocolException;
8 import org.apache.http.UnsupportedHttpVersionException;
9 import org.apache.http.auth.AuthenticationException;
10 import org.apache.http.auth.InvalidCredentialsException;
11 import org.apache.http.auth.MalformedChallengeException;
12 import org.apache.http.client.CircularRedirectException;
13 import org.apache.http.client.ClientProtocolException;
14 import org.apache.http.client.NonRepeatableRequestException;
15 import org.apache.http.client.RedirectException;
16 import org.apache.http.conn.ConnectTimeoutException;
17 import org.apache.http.conn.ConnectionPoolTimeoutException;
18 import org.apache.http.conn.HttpHostConnectException;
19 import org.apache.http.cookie.CookieRestrictionViolationException;
20 import org.apache.http.cookie.MalformedCookieException;
21 import org.apache.http.impl.auth.NTLMEngineException;
22 import org.apache.http.impl.client.TunnelRefusedException;
23 import org.jboss.resteasy.client.ClientExecutor;
24 import org.jboss.resteasy.client.ClientRequest;
25 import org.jboss.resteasy.client.ClientResponse;
26 import org.jboss.resteasy.client.ClientResponseFailure;
27 import org.jboss.resteasy.client.ProxyBuilder;
28 import org.jboss.resteasy.client.exception.ResteasyAuthenticationException;
29 import org.jboss.resteasy.client.exception.ResteasyCircularRedirectException;
30 import org.jboss.resteasy.client.exception.ResteasyClientProtocolException;
31 import org.jboss.resteasy.client.exception.ResteasyConnectTimeoutException;
32 import org.jboss.resteasy.client.exception.ResteasyConnectionClosedException;
33 import org.jboss.resteasy.client.exception.ResteasyConnectionPoolTimeoutException;
34 import org.jboss.resteasy.client.exception.ResteasyCookieRestrictionViolationException;
35 import org.jboss.resteasy.client.exception.ResteasyHttpException;
36 import org.jboss.resteasy.client.exception.ResteasyHttpHostConnectException;
37 import org.jboss.resteasy.client.exception.ResteasyIOException;
38 import org.jboss.resteasy.client.exception.ResteasyInvalidCredentialsException;
39 import org.jboss.resteasy.client.exception.ResteasyMalformedChallengeException;
40 import org.jboss.resteasy.client.exception.ResteasyMalformedChunkCodingException;
41 import org.jboss.resteasy.client.exception.ResteasyMalformedCookieException;
42 import org.jboss.resteasy.client.exception.ResteasyMethodNotSupportedException;
43 import org.jboss.resteasy.client.exception.ResteasyNTLMEngineException;
44 import org.jboss.resteasy.client.exception.ResteasyNoHttpResponseException;
45 import org.jboss.resteasy.client.exception.ResteasyNonRepeatableRequestException;
46 import org.jboss.resteasy.client.exception.ResteasyProtocolException;
47 import org.jboss.resteasy.client.exception.ResteasyRedirectException;
48 import org.jboss.resteasy.client.exception.ResteasyTunnelRefusedException;
49 import org.jboss.resteasy.client.exception.ResteasyUnsupportedHttpVersionException;
50 import org.jboss.resteasy.client.exception.mapper.ApacheHttpClient4ExceptionMapper;
51 import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper;
52 import org.jboss.resteasy.core.Dispatcher;
53 import org.jboss.resteasy.spi.HttpRequest;
54 import org.jboss.resteasy.spi.ResteasyDeployment;
55 import org.jboss.resteasy.spi.ResteasyProviderFactory;
56 import org.jboss.resteasy.test.EmbeddedContainer;
57 import org.jboss.resteasy.util.Types;
58 import org.junit.Test;
59
60 import javax.ws.rs.GET;
61 import javax.ws.rs.POST;
62 import javax.ws.rs.PUT;
63 import javax.ws.rs.Path;
64 import javax.ws.rs.WebApplicationException;
65 import javax.ws.rs.core.Application;
66 import javax.ws.rs.core.Context;
67 import javax.ws.rs.core.MediaType;
68 import javax.ws.rs.core.UriBuilder;
69 import javax.ws.rs.ext.Provider;
70 import java.io.IOException;
71 import java.lang.reflect.Type;
72 import java.net.ConnectException;
73 import java.util.ArrayList;
74 import java.util.HashSet;
75 import java.util.Hashtable;
76 import java.util.Set;
77
78 import static org.junit.Assert.assertTrue;
79 import static org.junit.Assert.fail;
80
81 /**
82 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
83 * @version $Revision: 1.1 $
84 *
85 * Copyright Jul 28, 2012
86 */
87 public class HttpClient4ClientExceptionMapperTest
88 {
89 protected static ResteasyDeployment deployment;
90 protected static Dispatcher dispatcher;
91
92 public static interface Foo
93 {
94 @GET
95 @Path("foo")
96 String getFoo();
97
98 @PUT
99 @Path("foo")
100 String setFoo(String value);
101
102 @POST
103 @Path("error")
104 String error();
105 }
106
107 @Path("foo")
108 public static class TestResource implements Foo
109 {
110 @Context
111 HttpRequest request;
112
113 @Override
114 public String getFoo()
115 {
116 return request.getHttpHeaders().getAcceptableMediaTypes().toString();
117 }
118
119 @Override
120 public String setFoo(String value)
121 {
122 return request.getHttpHeaders().getMediaType().toString();
123 }
124
125 @Override
126 public String error()
127 {
128 throw new WebApplicationException(500);
129 }
130 }
131
132 public void before() throws Exception
133 {
134 deployment = EmbeddedContainer.start();
135 dispatcher = deployment.getDispatcher();
136 deployment.getRegistry().addPerRequestResource(TestResource.class);
137 }
138
139 public void beforeProviderInstance(ClientExceptionMapper<?> mapper) throws Exception
140 {
141 deployment = new ResteasyDeployment();
142 ArrayList<Object> providers = new ArrayList<Object>();
143 providers.add(mapper);
144 deployment.setProviders(providers);
145 deployment.start();
146 deployment.getRegistry().addPerRequestResource(TestResource.class);
147 }
148
149 public void beforeApplicationClasses(final Class<?> mapper) throws Exception
150 {
151 deployment = new ResteasyDeployment();
152 Application application = new Application()
153 {
154 public Set<Class<?>> getClasses()
155 {
156 HashSet<Class<?>> classes = new HashSet<Class<?>>();
157 classes.add(mapper);
158 return classes;
159 }
160 };
161 deployment.setApplication(application);
162 deployment.start();
163 deployment.getRegistry().addPerRequestResource(TestResource.class);
164 }
165
166 public void beforeApplicationSingleton(final ClientExceptionMapper<?> mapper) throws Exception
167 {
168 deployment = new ResteasyDeployment();
169 Application application = new Application()
170 {
171 public Set<Object> getSingletons()
172 {
173 HashSet<Object> singletons = new HashSet<Object>();
174 singletons.add(mapper);
175 return singletons;
176 }
177 };
178 deployment.setApplication(application);
179 deployment.start();
180 deployment.getRegistry().addPerRequestResource(TestResource.class);
181 }
182
183 public void beforeClassNames(final Class<?> mapper) throws Exception
184 {
185 deployment = new ResteasyDeployment();
186 ArrayList<String> providerClasses = new ArrayList<String>();
187 providerClasses.add(mapper.getName());
188 deployment.setProviderClasses(providerClasses);
189 deployment.start();
190 deployment.getRegistry().addPerRequestResource(TestResource.class);
191 }
192
193 public void beforeContextParams(final Class<?> mapper) throws Exception
194 {
195 Hashtable<String,String> initParams = new Hashtable<String,String>();
196 Hashtable<String,String> contextParams = new Hashtable<String,String>();
197 contextParams.put("javax.ws.rs.Application", TestApplication.class.getName());
198 deployment = EmbeddedContainer.start(initParams, contextParams);
199 }
200
201 public void beforeInitParams(final Class<?> mapper) throws Exception
202 {
203 Hashtable<String,String> initParams = new Hashtable<String,String>();
204 Hashtable<String,String> contextParams = new Hashtable<String,String>();
205 initParams.put("javax.ws.rs.Application", TestApplication.class.getName());
206 deployment = EmbeddedContainer.start(initParams, contextParams);
207 }
208
209 public void after() throws Exception
210 {
211 EmbeddedContainer.stop();
212 deployment = null;
213 }
214
215 /**
216 * Verify that ClientResponseFailure is thrown if the request successfully invokes a
217 * resource method, and the resource method returns a status code >= 400. That is,
218 * verify that the default error handling mechanism still works.
219 */
220 @Test
221 public void testClientResponseFailure() throws Exception
222 {
223 before();
224 boolean ok = false;
225 try
226 {
227 Foo foo = ProxyBuilder.build(Foo.class, "http://localhost:8081/foo/").serverMediaType(MediaType.TEXT_PLAIN_TYPE).now();
228 String answer = foo.error();
229 System.out.println("answer: " + answer);
230 }
231 catch (ClientResponseFailure e)
232 {
233 ok = true;
234 }
235 catch (Throwable t)
236 {
237 traverseException(t);
238 fail("Expected ClientResponseFailure, got " + t);
239 }
240 finally
241 {
242 after();
243 }
244 assertTrue("Expected ClientResponseFailure, got no Exception", ok);
245 }
246
247 @Test
248 public void testApacheHttpClient4Executor() throws Exception
249 {
250 doTestApacheHttpClient4Executor();
251 }
252
253 /**
254 * Verify that ApacheHttpClient4ExceptionMapper always gets set.
255 */
256 @Test
257 public void testApacheHttpClient4ExecutorAgain() throws Exception
258 {
259 doTestApacheHttpClient4Executor();
260 }
261
262 private void doTestApacheHttpClient4Executor() throws Exception
263 {
264 before();
265 try
266 {
267 Foo foo = ProxyBuilder.build(Foo.class, "http://localhost:9999").serverMediaType(MediaType.TEXT_PLAIN_TYPE).now();
268 foo.getFoo();
269 }
270 catch (ResteasyIOException e)
271 {
272 traverseException(e);
273 assertTrue(ConnectException.class.equals(e.getCause().getClass()));
274 }
275 catch (Throwable t)
276 {
277 traverseException(t);
278 fail("Expected HttpHostConnectException, got " + t);
279 }
280 finally
281 {
282 after();
283 }
284 }
285
286 @Test
287 public void testAuthenticationException() throws Exception
288 {
289 doTest(new ResteasyAuthenticationException(), new AuthenticationException());
290 }
291
292 @Test
293 public void testCircularRedirectException() throws Exception
294 {
295 doTest(new ResteasyCircularRedirectException(), new CircularRedirectException());
296 }
297
298
299 @Test
300 public void testClientProtocolException() throws Exception
301 {
302 doTest(new ResteasyClientProtocolException(), new ClientProtocolException());
303 }
304
305 @Test
306 public void testConnectionClosedException() throws Exception
307 {
308 doTest(new ResteasyConnectionClosedException(), new ConnectionClosedException(""));
309 }
310
311 @Test
312 public void testConnectionPoolTimeoutException() throws Exception
313 {
314 doTest(new ResteasyConnectionPoolTimeoutException(), new ConnectionPoolTimeoutException(""));
315 }
316
317 @Test
318 public void testConnectTimeoutException() throws Exception
319 {
320 doTest(new ResteasyConnectTimeoutException(), new ConnectTimeoutException(""));
321 }
322
323 @Test
324 public void testCookieRestrictionViolationException() throws Exception
325 {
326 doTest(new ResteasyCookieRestrictionViolationException(), new CookieRestrictionViolationException());
327 }
328
329 @Test
330 public void testHttpException() throws Exception
331 {
332 doTest(new ResteasyHttpException(), new HttpException());
333 }
334
335 @Test
336 public void testHttpHostConnectException() throws Exception
337 {
338 doTest(new ResteasyHttpHostConnectException(), new HttpHostConnectException(null, null));
339 }
340
341 @Test
342 public void testInvalidCredentialsException() throws Exception
343 {
344 doTest(new ResteasyInvalidCredentialsException(), new InvalidCredentialsException());
345 }
346
347 @Test
348 public void testIOException() throws Exception
349 {
350 doTest(new ResteasyIOException(), new IOException());
351 }
352
353 @Test
354 public void testMalformedChallengeException() throws Exception
355 {
356 doTest(new ResteasyMalformedChallengeException(), new MalformedChallengeException());
357 }
358
359 @Test
360 public void testMalformedChunkCodingException() throws Exception
361 {
362 doTest(new ResteasyMalformedChunkCodingException(), new MalformedChunkCodingException());
363 }
364
365 @Test
366 public void testMalformedCookieException() throws Exception
367 {
368 doTest(new ResteasyMalformedCookieException(), new MalformedCookieException());
369 }
370
371 @Test
372 public void testMethodNotSupportedException() throws Exception
373 {
374 doTest(new ResteasyMethodNotSupportedException(), new MethodNotSupportedException(""));
375 }
376
377 @Test
378 public void testNoHttpResponseException() throws Exception
379 {
380 doTest(new ResteasyNoHttpResponseException(), new NoHttpResponseException(""));
381 }
382
383 @Test
384 public void testNonRepeatableRequestException() throws Exception
385 {
386 doTest(new ResteasyNonRepeatableRequestException(), new NonRepeatableRequestException());
387 }
388
389 @Test
390 public void testNTLMEngineException() throws Exception
391 {
392 doTest(new ResteasyNTLMEngineException(), new NTLMEngineException());
393 }
394
395 @Test
396 public void testProtocolException() throws Exception
397 {
398 doTest(new ResteasyProtocolException(), new ProtocolException());
399 }
400
401 @Test
402 public void testRedirectException() throws Exception
403 {
404 doTest(new ResteasyRedirectException(), new RedirectException());
405 }
406
407 @Test
408 public void testTunnelRefusedException() throws Exception
409 {
410 doTest(new ResteasyTunnelRefusedException(), new TunnelRefusedException("", null));
411 }
412
413 @Test
414 public void testUnsupportedHttpVersionException() throws Exception
415 {
416 doTest(new ResteasyUnsupportedHttpVersionException(), new UnsupportedHttpVersionException());
417 }
418
419 private void doTest(Exception resteasyException, Exception embeddedException) throws Exception
420 {
421 before();
422 try
423 {
424 ProxyBuilder<Foo> builder = ProxyBuilder.build(Foo.class, "http://localhost:9999").serverMediaType(MediaType.TEXT_PLAIN_TYPE);
425 builder.executor(new TestClientExecutor(embeddedException));
426 Foo foo = builder.now();
427 foo.getFoo();
428 }
429 catch (Throwable t)
430 {
431 traverseException(t);
432 assertTrue("Expected instance of " + resteasyException.getClass() + ", got " + t, resteasyException.getClass().equals(t.getClass()));
433 assertTrue("Expected instance of " + embeddedException.getClass() + ", got " + t, embeddedException.getClass().equals(t.getCause().getClass()));
434 }
435 finally
436 {
437 after();
438 }
439 }
440
441 @Test
442 public void testAlternativeMapperProviderInstance() throws Exception
443 {
444 beforeProviderInstance(new TestClientExceptionMapper());
445 doTestWithAlternativeMapper(new TestException(null), new UnsupportedHttpVersionException());
446 }
447
448 @Test
449 public void testAlternativeMapperClassName() throws Exception
450 {
451 beforeClassNames(TestClientExceptionMapper.class);
452 doTestWithAlternativeMapper(new TestException(null), new UnsupportedHttpVersionException());
453 }
454
455 @Test
456 public void testAlternativeMapperApplicationClasses() throws Exception
457 {
458 beforeApplicationClasses(TestClientExceptionMapper.class);
459 doTestWithAlternativeMapper(new TestException(null), new UnsupportedHttpVersionException());
460 }
461
462 @Test
463 public void testAlternativeMapperApplicationSingleton() throws Exception
464 {
465 beforeApplicationSingleton(new TestClientExceptionMapper());
466 doTestWithAlternativeMapper(new TestException(null), new UnsupportedHttpVersionException());
467 }
468
469 @Test
470 public void testAlternativeMapperContextParams() throws Exception
471 {
472 beforeContextParams(TestClientExceptionMapper.class);
473 doTestWithAlternativeMapper(new TestException(null), new UnsupportedHttpVersionException());
474 }
475
476 @Test
477 public void testAlternativeMapperInitParams() throws Exception
478 {
479 beforeInitParams(TestClientExceptionMapper.class);
480 doTestWithAlternativeMapper(new TestException(null), new UnsupportedHttpVersionException());
481 }
482
483 private void doTestWithAlternativeMapper(Exception wrappingException, Exception embeddedException) throws Exception
484 {
485 try
486 {
487 ProxyBuilder<Foo> builder = ProxyBuilder.build(Foo.class, "http://localhost:9999").serverMediaType(MediaType.TEXT_PLAIN_TYPE);
488 builder.executor(new TestClientExecutor(embeddedException));
489 Foo foo = builder.now();
490 foo.getFoo();
491 }
492 catch (Throwable t)
493 {
494 traverseException(t);
495 assertTrue("Expected instance of " + wrappingException.getClass() + ", got " + t, wrappingException.getClass().equals(t.getClass()));
496 assertTrue("Expected instance of " + embeddedException.getClass() + ", got " + t, embeddedException.getClass().equals(t.getCause().getClass()));
497 }
498 finally
499 {
500 after();
501 }
502 }
503
504 static private void traverseException(Throwable t)
505 {
506 String indent = "";
507 while (t instanceof Throwable)
508 {
509 System.out.println(indent + t);
510 t = t.getCause();
511 indent += " ";
512 }
513 }
514
515 static public class TestApplication extends Application
516 {
517 public Set<Class<?>> getClasses()
518 {
519 HashSet<Class<?>> classes = new HashSet<Class<?>>();
520 classes.add(TestClientExceptionMapper.class);
521 return classes;
522 }
523 }
524
525
526 @Provider
527 static class TestClientExecutor implements ClientExecutor
528 {
529 private Exception e;
530
531 public TestClientExecutor(Exception e)
532 {
533 this.e = e;
534 if (ResteasyProviderFactory.getInstance().getClientExceptionMapper(Exception.class) == null)
535 {
536 Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class, ClientExceptionMapper.class)[0];
537 ResteasyProviderFactory.getInstance().addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);
538 }
539 }
540 @Override
541 public ClientRequest createRequest(String uriTemplate)
542 {
543 return null;
544 }
545 @Override
546 public ClientRequest createRequest(UriBuilder uriBuilder)
547 {
548 return null;
549 }
550 @Override
551 public ClientResponse<?> execute(ClientRequest request) throws Exception
552 {
553 throw e;
554 }
555 @Override
556 public void close() throws Exception
557 {
558 }
559 }
560
561 static class TestException extends RuntimeException
562 {
563 private static final long serialVersionUID = -7825447948319726641L;
564
565 public TestException(Exception e)
566 {
567 super(e);
568 }
569 }
570
571 @Provider
572 static public class TestClientExceptionMapper implements ClientExceptionMapper<Exception>
573 {
574 @Override
575 public RuntimeException toException(Exception exception)
576 {
577 return new TestException(exception);
578 }
579
580 }
581 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.apache.http.client.HttpClient;
3 import org.apache.http.conn.ClientConnectionManager;
4 import org.apache.http.conn.params.ConnManagerParams;
5 import org.apache.http.conn.scheme.PlainSocketFactory;
6 import org.apache.http.conn.scheme.Scheme;
7 import org.apache.http.conn.scheme.SchemeRegistry;
8 import org.apache.http.impl.client.DefaultHttpClient;
9 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
10 import org.apache.http.params.BasicHttpParams;
11 import org.apache.http.params.HttpParams;
12 import org.jboss.resteasy.client.ClientRequest;
13 import org.jboss.resteasy.client.ClientResponse;
14 import org.jboss.resteasy.client.ClientResponseFailure;
15 import org.jboss.resteasy.client.ProxyFactory;
16 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
17 import org.jboss.resteasy.spi.NoLogWebApplicationException;
18 import org.jboss.resteasy.test.BaseResourceTest;
19 import org.junit.Assert;
20 import org.junit.BeforeClass;
21 import org.junit.Test;
22
23 import javax.ws.rs.GET;
24 import javax.ws.rs.Path;
25 import javax.ws.rs.Produces;
26 import java.util.concurrent.atomic.AtomicLong;
27
28 /**
29 * Test connection cleanup
30 *
31 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
32 * @version $Revision: 1 $
33 */
34 public class ApacheHttpClient4Test extends BaseResourceTest
35 {
36
37 public static class MyResourceImpl implements MyResource
38 {
39 public String get()
40 {
41 return "hello world";
42 }
43
44 public String error()
45 {
46 throw new NoLogWebApplicationException(404);
47 }
48 }
49
50 @Path("/test")
51 public static interface MyResource
52 {
53 @GET
54 @Produces("text/plain")
55 public String get();
56
57 @GET
58 @Path("error")
59 @Produces("text/plain")
60 String error();
61 }
62
63 @BeforeClass
64 public static void setUp() throws Exception
65 {
66 addPerRequestResource(MyResourceImpl.class);
67 }
68
69 private AtomicLong counter = new AtomicLong();
70
71 @Test
72 public void testConnectionCleanupGC() throws Exception
73 {
74 final ApacheHttpClient4Executor executor = createClient();
75 counter.set(0);
76
77
78 Thread[] threads = new Thread[3];
79
80 for (int i = 0; i < 3; i++)
81 {
82 threads[i] = new Thread()
83 {
84 @Override
85 public void run()
86 {
87 for (int j = 0; j < 10; j++)
88 {
89 runit(executor, false);
90 System.gc();
91 }
92 }
93 };
94 }
95
96 for (int i = 0; i < 3; i++) threads[i].start();
97 for (int i = 0; i < 3; i++) threads[i].join();
98
99 Assert.assertEquals(30l, counter.get());
100 }
101
102 @Test
103 public void testConnectionCleanupManual() throws Exception
104 {
105 final ApacheHttpClient4Executor executor = createClient();
106 counter.set(0);
107
108
109 Thread[] threads = new Thread[3];
110
111 for (int i = 0; i < 3; i++)
112 {
113 threads[i] = new Thread()
114 {
115 @Override
116 public void run()
117 {
118 for (int j = 0; j < 10; j++)
119 {
120 runit(executor, true);
121 }
122 }
123 };
124 }
125
126 for (int i = 0; i < 3; i++) threads[i].start();
127 for (int i = 0; i < 3; i++) threads[i].join();
128
129 Assert.assertEquals(30l, counter.get());
130 }
131
132 @Test
133 public void testConnectionCleanupProxy() throws Exception
134 {
135 final ApacheHttpClient4Executor executor = createClient();
136 final MyResource proxy = ProxyFactory.create(MyResource.class, "http://localhost:8081", executor);
137 counter.set(0);
138
139
140 Thread[] threads = new Thread[3];
141
142
143 for (int i = 0; i < 3; i++)
144 {
145 threads[i] = new Thread()
146 {
147 @Override
148 public void run()
149 {
150 for (int j = 0; j < 10; j++)
151 {
152 System.out.println("calling proxy");
153 String str = proxy.get();
154 System.out.println("returned: " + str);
155 Assert.assertEquals("hello world", str);
156 counter.incrementAndGet();
157 }
158 }
159 };
160 }
161
162 for (int i = 0; i < 3; i++) threads[i].start();
163 for (int i = 0; i < 3; i++) threads[i].join();
164
165 Assert.assertEquals(30l, counter.get());
166 }
167
168 @Test
169 public void testConnectionCleanupErrorGC() throws Exception
170 {
171 final ApacheHttpClient4Executor executor = createClient();
172 final MyResource proxy = ProxyFactory.create(MyResource.class, "http://localhost:8081", executor);
173 counter.set(0);
174
175
176 Thread[] threads = new Thread[3];
177
178
179 for (int i = 0; i < 3; i++)
180 {
181 threads[i] = new Thread()
182 {
183 @Override
184 public void run()
185 {
186 for (int j = 0; j < 10; j++)
187 {
188 System.out.println("calling proxy");
189 callProxy(proxy);
190 System.gc();
191 System.out.println("returned");
192 }
193 }
194 };
195 }
196
197 for (int i = 0; i < 3; i++) threads[i].start();
198 for (int i = 0; i < 3; i++) threads[i].join();
199
200 Assert.assertEquals(30l, counter.get());
201 }
202
203 @Test
204 public void testConnectionCleanupErrorNoGC() throws Exception
205 {
206 final ApacheHttpClient4Executor executor = createClient();
207 final MyResource proxy = ProxyFactory.create(MyResource.class, "http://localhost:8081", executor);
208 counter.set(0);
209
210
211 Thread[] threads = new Thread[3];
212
213
214 for (int i = 0; i < 3; i++)
215 {
216 threads[i] = new Thread()
217 {
218 @Override
219 public void run()
220 {
221 for (int j = 0; j < 10; j++)
222 {
223 System.out.println("calling proxy");
224 String str = null;
225 try
226 {
227 str = proxy.error();
228 }
229 catch (ClientResponseFailure e)
230 {
231 Assert.assertEquals(e.getResponse().getStatus(), 404);
232 e.getResponse().releaseConnection();
233 counter.incrementAndGet();
234 }
235 System.out.println("returned");
236 }
237 }
238 };
239 }
240
241 for (int i = 0; i < 3; i++) threads[i].start();
242 for (int i = 0; i < 3; i++) threads[i].join();
243
244 Assert.assertEquals(30l, counter.get());
245 }
246
247 private void callProxy(MyResource proxy)
248 {
249 String str = null;
250 try
251 {
252 str = proxy.error();
253 }
254 catch (ClientResponseFailure e)
255 {
256 Assert.assertEquals(e.getResponse().getStatus(), 404);
257 counter.incrementAndGet();
258 }
259 }
260
261
262 private ApacheHttpClient4Executor createClient()
263 {
264 HttpParams params = new BasicHttpParams();
265 ConnManagerParams.setMaxTotalConnections(params, 3);
266 ConnManagerParams.setTimeout(params, 5000);
267
268 // Create and initialize scheme registry
269 SchemeRegistry schemeRegistry = new SchemeRegistry();
270 schemeRegistry.register(
271 new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
272
273 // Create an HttpClient with the ThreadSafeClientConnManager.
274 // This connection manager must be used if more than one thread will
275 // be using the HttpClient.
276 ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
277 HttpClient httpClient = new DefaultHttpClient(cm, params);
278
279 final ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
280 return executor;
281 }
282
283 private void runit(ApacheHttpClient4Executor executor, boolean release)
284 {
285 ClientRequest request = executor.createRequest("http://localhost:8081/test");
286 ClientResponse response = null;
287 try
288 {
289 System.out.println("get");
290 response = request.get();
291 Assert.assertEquals(200, response.getStatus());
292 //Assert.assertEquals("hello world", response.getEntity(String.class));
293 System.out.println("ok");
294 if (release) response.releaseConnection();
295 }
296 catch (Exception e)
297 {
298 throw new RuntimeException(e);
299 }
300 counter.incrementAndGet();
301 }
302 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.jboss.resteasy.client.ClientResponse;
3 import org.jboss.resteasy.client.ClientResponseFailure;
4 import org.jboss.resteasy.client.ProxyFactory;
5 import org.jboss.resteasy.client.core.ClientErrorInterceptor;
6 import org.jboss.resteasy.test.BaseResourceTest;
7 import org.junit.Before;
8 import org.junit.Test;
9
10 import javax.ws.rs.GET;
11 import javax.ws.rs.Path;
12 import javax.ws.rs.Produces;
13
14 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
15 import static org.junit.Assert.*;
16
17 /**
18 * @author <a href="mailto:lincoln@ocpsoft.com">Lincoln Baxter, III</a>
19 */
20 public class ClientExceptionInterceptorTest extends BaseResourceTest
21 {
22 private static final String RESPONSE_OK = "RESPONSE OK";
23
24 @Before
25 public void setUp() throws Exception
26 {
27 addPerRequestResource(TestResource.class);
28 getProviderFactory().getClientErrorInterceptors().clear();
29 }
30
31 @Test
32 public void testNoExceptionEncountered() throws Exception
33 {
34 getProviderFactory().addClientErrorInterceptor(new TestNoExceptionInterceptor());
35 getProviderFactory().addClientErrorInterceptor(new TestThrowExceptionInterceptor());
36 TestService service = ProxyFactory.create(TestService.class, generateURL("/"));
37 String result = service.get();
38 assertEquals(RESPONSE_OK, result);
39 }
40
41 @Test(expected = ClientResponseFailure.class)
42 public void testExceptionEncounteredAndIgnoredIsRethrown() throws Exception
43 {
44 getProviderFactory().addClientErrorInterceptor(new TestNoExceptionInterceptor());
45 TestService service = ProxyFactory.create(TestService.class, generateURL("/"));
46 service.getBadUrl();
47 }
48
49 @Test(expected = TestException.class)
50 public void testExceptionEncounteredAndNewExceptionThrown() throws Exception
51 {
52 getProviderFactory().addClientErrorInterceptor(new TestThrowExceptionInterceptor());
53 TestService service = ProxyFactory.create(TestService.class, generateURL("/"));
54 service.getBadUrl();
55 }
56
57 @Test
58 public void testExceptionInterceptorsChain() throws Exception
59 {
60 TestNoExceptionInterceptor handler = new TestNoExceptionInterceptor();
61 getProviderFactory().addClientErrorInterceptor(handler);
62 getProviderFactory().addClientErrorInterceptor(new TestThrowExceptionInterceptor());
63 TestService service = ProxyFactory.create(TestService.class, generateURL("/"));
64
65 try
66 {
67 service.getBadUrl();
68 fail();
69 }
70 catch (TestException e)
71 {
72 assertTrue(handler.isHandled());
73 }
74 }
75
76 /*
77 * Test utility classes
78 */
79 @Path("/test")
80 public static class TestResource
81 {
82 @GET
83 @Path("/get")
84 @Produces("text/plain")
85 public String get()
86 {
87 return RESPONSE_OK;
88 }
89 }
90
91 @Path("/test")
92 public interface TestService
93 {
94 @GET
95 @Path("/get")
96 @Produces("text/plain")
97 public String get();
98
99 @GET
100 @Path("/foo")
101 @Produces("text/plain")
102 public String getBadUrl();
103 }
104
105 public static class TestThrowExceptionInterceptor implements ClientErrorInterceptor
106 {
107 public void handle(ClientResponse<?> response) throws RuntimeException
108 {
109 throw new TestException();
110 }
111 }
112
113 public static class TestNoExceptionInterceptor implements ClientErrorInterceptor
114 {
115 private boolean handled = false;
116
117 public void handle(ClientResponse<?> response) throws RuntimeException
118 {
119 handled = true;
120 }
121
122 public boolean isHandled()
123 {
124 return handled;
125 }
126 }
127
128 @SuppressWarnings("serial")
129 public static class TestException extends RuntimeException
130 {
131 }
132 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.apache.http.HttpResponse;
3 import org.apache.http.client.HttpClient;
4 import org.apache.http.client.methods.HttpPost;
5 import org.apache.http.impl.client.DefaultHttpClient;
6 import org.jboss.logging.Logger;
7 import org.jboss.resteasy.client.ClientExecutor;
8 import org.jboss.resteasy.client.ClientRequest;
9 import org.jboss.resteasy.client.ClientResponse;
10 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
11 import org.jboss.resteasy.test.BaseResourceTest;
12 import org.junit.Assert;
13 import org.junit.Before;
14 import org.junit.Test;
15
16 import javax.ws.rs.POST;
17 import javax.ws.rs.Path;
18
19 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
20 import static org.junit.Assert.fail;
21
22 /**
23 * Unit tests for https://issues.jboss.org/browse/RESTEASY-621.
24 *
25 * @author <a href="mailto:ron.sigal@jboss.com">Ron Sigal</a>
26 * @version $Revision: 1 $
27 */
28 public class ClientExecutorShutdownTest extends BaseResourceTest
29 {
30 private static Logger log = Logger.getLogger(ClientExecutorShutdownTest.class);
31
32 @Path("/test")
33 public interface TestService
34 {
35 @POST
36 ClientResponse<String> post();
37 }
38
39 @Path("/test")
40 public static class TestServiceImpl
41 {
42 @POST
43 public void post()
44 {
45 System.out.println("In POST");
46 }
47 }
48
49 @Before
50 public void setUp() throws Exception
51 {
52 addPerRequestResource(TestServiceImpl.class);
53 }
54
55 /**
56 * Verify that each ClientRequest gets its own ClientExecutor
57 * if one is not supplied through the constructor.
58 */
59 @Test
60 public void testClientRequestNonSharedExecutor() throws Exception
61 {
62 ClientRequest request1 = new ClientRequest(generateURL("/test"));
63 ClientResponse<?> response1 = request1.post();
64 Assert.assertEquals(204, response1.getStatus());
65 ClientRequest request2 = new ClientRequest(generateURL("/test"));
66 ClientResponse<?> response2 = request2.post();
67 Assert.assertEquals(204, response2.getStatus());
68 ClientExecutor executor1 = request1.getExecutor();
69 ClientExecutor executor2 = request2.getExecutor();
70 Assert.assertNotSame(executor1, executor2);
71 executor2.close();
72 response1 = request1.post();
73 Assert.assertEquals(204, response1.getStatus());
74 executor1.close();
75
76 }
77
78 /**
79 * Verify that ClientRequest uses the ClientExecutor
80 * supplied through a constructor.
81 */
82 @Test
83 public void testClientRequestSharedExecutor() throws Exception
84 {
85 ClientExecutor executor = new ApacheHttpClient4Executor();
86 ClientRequest request1 = new ClientRequest(generateURL("/test"), executor);
87 ClientResponse<?> response1 = request1.post();
88 Assert.assertEquals(204, response1.getStatus());
89 ClientRequest request2 = new ClientRequest(generateURL("/test"), executor);
90 ClientResponse<?> response2 = request2.post();
91 Assert.assertEquals(204, response2.getStatus());
92 ClientExecutor executor1 = request1.getExecutor();
93 ClientExecutor executor2 = request2.getExecutor();
94 Assert.assertSame(executor, executor1);
95 Assert.assertSame(executor, executor2);
96 executor.close();
97 }
98
99 /**
100 * Verify that if ApacheHttpClient4Executor creates its own HttpClient,
101 * then ApacheHttpClient4Executor.finalize() will close the HttpClient's
102 * org.apache.http.conn.ClientConnectionManager.
103 */
104 @Test
105 public void testApacheHttpClient4ExecutorNonSharedHttpClientFinalize() throws Throwable
106 {
107 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor();
108 ClientRequest request = new ClientRequest(generateURL("/test"), executor);
109 ClientResponse<?> response = request.post();
110 Assert.assertEquals(204, response.getStatus());
111 executor.finalize();
112 HttpClient httpClient = executor.getHttpClient();
113 HttpPost post = new HttpPost(generateURL("/test"));
114 try
115 {
116 httpClient.execute(post);
117 fail("Expected IllegalStateException");
118 }
119 catch (IllegalStateException e)
120 {
121 log.info("Got expected IllegalStateException");
122 }
123 }
124
125 /**
126 * Verify that if ApacheHttpClient4Executor creates its own HttpClient,
127 * then ApacheHttpClient4Executor.close() will close the HttpClient's
128 * org.apache.http.conn.ClientConnectionManager.
129 */
130 @Test
131 public void testApacheHttpClient4ExecutorNonSharedHttpClientClose() throws Throwable
132 {
133 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor();
134 ClientRequest request = new ClientRequest(generateURL("/test"), executor);
135 ClientResponse<?> response = request.post();
136 Assert.assertEquals(204, response.getStatus());
137 executor.close();
138 HttpClient httpClient = executor.getHttpClient();
139 HttpPost post = new HttpPost(generateURL("/test"));
140 try
141 {
142 httpClient.execute(post);
143 fail("Expected IllegalStateException");
144 }
145 catch (IllegalStateException e)
146 {
147 log.info("Got expected IllegalStateException");
148 }
149 }
150
151 /**
152 * Verify that if ApacheHttpClient4Executor receives an HttpClient through
153 * a constructor, then ApacheHttpClient4Executor.finalize() will not close the
154 * HttpClient's org.apache.http.conn.ClientConnectionManager.
155 */
156 @Test
157 public void testApacheHttpClient4ExecutorSharedHttpClientFinalize() throws Throwable
158 {
159 HttpClient httpClient = new DefaultHttpClient();
160 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
161 ClientRequest request = new ClientRequest(generateURL("/test"), executor);
162 ClientResponse<?> response = request.post();
163 Assert.assertEquals(204, response.getStatus());
164 executor.finalize();
165 Assert.assertEquals(httpClient, executor.getHttpClient());
166 HttpPost post = new HttpPost(generateURL("/test"));
167 HttpResponse httpResponse = httpClient.execute(post);
168 Assert.assertEquals(204, httpResponse.getStatusLine().getStatusCode());
169 httpClient.getConnectionManager().shutdown();
170 }
171
172 /**
173 * Verify that if ApacheHttpClient4Executor receives an HttpClient through
174 * a constructor, then ApacheHttpClient4Executor.close() will not close the
175 * HttpClient's org.apache.http.conn.ClientConnectionManager.
176 */
177 @Test
178 public void testApacheHttpClient4ExecutorSharedHttpClientClose() throws Throwable
179 {
180 HttpClient httpClient = new DefaultHttpClient();
181 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
182 ClientRequest request = new ClientRequest(generateURL("/test"), executor);
183 ClientResponse<?> response = request.post();
184 Assert.assertEquals(204, response.getStatus());
185 executor.close();
186 Assert.assertEquals(httpClient, executor.getHttpClient());
187 HttpPost post = new HttpPost(generateURL("/test"));
188 HttpResponse httpResponse = httpClient.execute(post);
189 Assert.assertEquals(204, httpResponse.getStatusLine().getStatusCode());
190 httpClient.getConnectionManager().shutdown();
191 }
192 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
5 import org.jboss.resteasy.test.BaseResourceTest;
6 import org.junit.Assert;
7 import org.junit.Before;
8 import org.junit.Test;
9
10 import javax.ws.rs.POST;
11 import javax.ws.rs.Path;
12
13 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
14
15 /**
16 * Unit test for https://issues.jboss.org/browse/RESTEASY-623.
17 *
18 * @author <a href="mailto:ron.sigal@jboss.com">Ron Sigal</a>
19 * @version $Revision: 1 $
20 */
21 public class ClientRequestDefaultClientExecutorTest extends BaseResourceTest
22 {
23 @Path("/test")
24 public interface TestService
25 {
26 @POST
27 ClientResponse<String> post();
28 }
29
30 @Path("/test")
31 public static class TestServiceImpl
32 {
33 @POST
34 public void post()
35 {
36 System.out.println("In POST");
37 }
38 }
39
40 @Before
41 public void setUp() throws Exception
42 {
43 addPerRequestResource(TestServiceImpl.class);
44 }
45
46 /**
47 * Verify that each ClientRequest.setDefaultExecutorClass()
48 * still works.
49 */
50 @Test
51 public void testClientRequestNonSharedExecutor() throws Exception
52 {
53 ClientRequest.setDefaultExecutorClass(TestClientExecutor.class.getName());
54 ClientRequest request = new ClientRequest(generateURL("/test"));
55 ClientResponse<?> response = request.post();
56 Assert.assertEquals(204, response.getStatus());
57 Assert.assertTrue(request.getExecutor() instanceof TestClientExecutor);
58 response.releaseConnection();
59 }
60
61 public static class TestClientExecutor extends ApacheHttpClient4Executor
62 {
63 }
64 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.test.BaseResourceTest;
4 import org.junit.Assert;
5 import org.junit.Before;
6 import org.junit.Test;
7
8 import javax.ws.rs.Consumes;
9 import javax.ws.rs.POST;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.PathParam;
12 import javax.ws.rs.Produces;
13
14 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
15
16 /**
17 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
18 * @version $Revision: 1 $
19 */
20 public class ClientRequestReuseTest extends BaseResourceTest
21 {
22 @Path("/test")
23 public static class TestService
24 {
25 @POST
26 @Path("{name}")
27 @Produces("text/plain")
28 @Consumes("text/plain")
29 public String post(@PathParam("name") String id, String message)
30 {
31 System.out.println("Server!!!");
32 return message + id;
33 }
34 }
35
36 @Before
37 public void setUp() throws Exception
38 {
39 addPerRequestResource(TestService.class);
40 }
41
42 @Test
43 public void testStylesheet() throws Exception
44 {
45 ClientRequest request = new ClientRequest(generateURL("/test/{name}"));
46 request.body("text/plain", "Hello ").pathParameter("name", "Bill");
47 String response = request.postTarget(String.class);
48 System.out.println(response);
49 Assert.assertEquals(response, "Hello Bill");
50 response = request.postTarget(String.class);
51 System.out.println(response);
52 Assert.assertEquals(response, "Hello Bill");
53 request.clear();
54 request.body("text/plain", "Goodbye ").pathParameter("name", "Everyone");
55 response = request.postTarget(String.class);
56 System.out.println(response);
57 Assert.assertEquals(response, "Goodbye Everyone");
58
59
60 }
61 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.jboss.resteasy.client.ProxyFactory;
3 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.jboss.resteasy.test.BaseResourceTest;
6 import org.junit.Assert;
7 import org.junit.Before;
8 import org.junit.Test;
9
10 import javax.ws.rs.GET;
11 import javax.ws.rs.Path;
12 import javax.ws.rs.Produces;
13 import javax.ws.rs.core.Context;
14 import javax.ws.rs.core.UriInfo;
15
16 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
17
18 /**
19 */
20 public class ContextTest extends BaseResourceTest
21 {
22 public static class Resource implements ResourceInterface
23 {
24
25 public String echo(UriInfo info)
26 {
27 Assert.assertNotNull(info);
28 return "content";
29 }
30 }
31
32 @Path(value = "/test")
33 public interface ResourceInterface
34 {
35
36 @GET
37 @Produces("text/plain")
38 public String echo(@Context UriInfo info);
39 }
40
41 @Before
42 public void setUp() throws Exception
43 {
44 addPerRequestResource(Resource.class);
45 }
46
47
48 @Test
49 public void testEcho()
50 {
51 RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
52 ResourceInterface client = ProxyFactory.create(ResourceInterface.class, generateBaseUrl());
53 Assert.assertEquals("content", client.echo(null));
54 }
55
56
57 }
0 package org.jboss.resteasy.test.client.old;
1
2 import java.io.IOException;
3
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7
8 import org.apache.http.HttpEntity;
9 import org.apache.http.entity.ByteArrayEntity;
10 import org.apache.http.entity.FileEntity;
11 import org.jboss.resteasy.client.ClientRequest;
12 import org.jboss.resteasy.client.ClientResponse;
13 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
14 import org.jboss.resteasy.logging.Logger;
15 import org.jboss.resteasy.spi.ResteasyDeployment;
16 import org.jboss.resteasy.test.EmbeddedContainer;
17 import org.junit.After;
18 import org.junit.Assert;
19 import org.junit.Before;
20 import org.junit.Test;
21
22 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
23
24 /**
25 *
26 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
27 * @version $Revision: 1.1 $
28 *
29 * Copyright Sep 29, 2012
30 */
31 public class EntityBufferingInFileTest
32 {
33 private static final Logger log = Logger.getLogger(EntityBufferingInFileTest.class);
34
35 protected ResteasyDeployment deployment;
36
37 @Path("/")
38 static public class TestResource
39 {
40 @POST
41 @Produces("text/plain")
42 @Path("hello")
43 public String resourceMethod(String body)
44 {
45 System.out.println("entered resourceMethod()");
46 return body;
47 }
48 }
49
50 @Before
51 public void before() throws Exception
52 {
53 deployment = EmbeddedContainer.start();
54 deployment.getRegistry().addPerRequestResource(TestResource.class);
55 }
56
57 @After
58 public void after() throws Exception
59 {
60 EmbeddedContainer.stop();
61 deployment = null;
62 }
63
64 @Test
65 public void testInMemoryBytes() throws Exception
66 {
67 doTest(ApacheHttpClient4Executor.BYTE_MEMORY_UNIT, 16, 10, true);
68 }
69
70 @Test
71 public void testOnDiskBytes() throws Exception
72 {
73 doTest(ApacheHttpClient4Executor.BYTE_MEMORY_UNIT, 16, 20, false);
74 }
75
76 @Test
77 public void testInMemoryKilobytes() throws Exception
78 {
79 doTest(ApacheHttpClient4Executor.KILOBYTE_MEMORY_UNIT, 1, 500, true);
80 }
81
82 @Test
83 public void testOnDiskKilobytes() throws Exception
84 {
85 doTest(ApacheHttpClient4Executor.KILOBYTE_MEMORY_UNIT, 1, 2000, false);
86 }
87
88 @Test
89 public void testInMemoryMegabytes() throws Exception
90 {
91 doTest(ApacheHttpClient4Executor.MEGABYTE_MEMORY_UNIT, 1, 500000, true);
92 }
93
94 @Test
95 public void testOnDiskMegabytes() throws Exception
96 {
97 doTest(ApacheHttpClient4Executor.MEGABYTE_MEMORY_UNIT, 1, 2000000, false);
98 }
99
100 @Test
101 public void testInMemoryGigabytes() throws Exception
102 {
103 doTest(ApacheHttpClient4Executor.GIGABYTE_MEMORY_UNIT, 1, 500000000, true);
104 }
105
106 @Test
107 public void testOnDiskGigabytes() throws Exception
108 {
109 doTest(ApacheHttpClient4Executor.GIGABYTE_MEMORY_UNIT, 1, 2000000000, false);
110 }
111
112 protected void doTest(String memoryUnit, int threshold, int length, boolean inMemory) throws Exception
113 {
114 try
115 {
116 TestClientExecutor executor = new TestClientExecutor();
117 executor.setFileUploadMemoryUnit(memoryUnit);
118 executor.setFileUploadInMemoryThresholdLimit(threshold);
119 StringBuffer sb = new StringBuffer();
120 for (int i = 0; i < length; i++)
121 {
122 sb.append("0");
123 }
124 String body = sb.toString();
125 ClientRequest request = new ClientRequest(generateURL("/hello"), executor);
126 request.body("text/plain", body);
127 System.out.println("Sending request");
128 ClientResponse<String> response = request.post(String.class);
129 System.out.println("Received response");
130 Assert.assertEquals(200, response.getStatus());
131 Assert.assertEquals(body, response.getEntity());
132 if (inMemory)
133 {
134 Assert.assertTrue(executor.getBuildEntity() instanceof ByteArrayEntity);
135 }
136 else
137 {
138 Assert.assertTrue(executor.getBuildEntity() instanceof FileEntity);
139 }
140 }
141 catch (OutOfMemoryError e)
142 {
143 // Ok, skip it.
144 log.info("OutOfMemoryError on " + memoryUnit + " test.");
145
146 }
147 }
148
149 static class TestClientExecutor extends ApacheHttpClient4Executor
150 {
151 private HttpEntity entityToBuild;
152
153 protected HttpEntity buildEntity(final ClientRequest request) throws IOException
154 {
155 entityToBuild = super.buildEntity(request);
156 return entityToBuild;
157 }
158
159 public HttpEntity getBuildEntity()
160 {
161 return entityToBuild;
162 }
163 }
164 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.junit.Assert;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.core.executors.InMemoryClientExecutor;
5 import org.junit.Test;
6
7 import javax.ws.rs.Consumes;
8 import javax.ws.rs.GET;
9 import javax.ws.rs.HeaderParam;
10 import javax.ws.rs.POST;
11 import javax.ws.rs.Path;
12 import javax.ws.rs.Produces;
13 import javax.ws.rs.QueryParam;
14
15 /**
16 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
17 * @version $Revision: 1 $
18 */
19 public class InMemoryTest
20 {
21 @Path("/foo")
22 public static class SimpleTest
23 {
24
25 @POST
26 @Produces("text/plain")
27 @Consumes("text/plain")
28 public String create(String cust)
29 {
30 return cust;
31 }
32
33 @GET
34 @Produces("text/plain")
35 public String get(@HeaderParam("a") String a, @QueryParam("b") String b)
36 {
37 return a + " " + b;
38 }
39
40 }
41
42 @Test
43 public void testSimple() throws Exception
44 {
45 InMemoryClientExecutor executor = new InMemoryClientExecutor();
46 executor.getDispatcher().getRegistry().addPerRequestResource(SimpleTest.class);
47 ClientRequest request = new ClientRequest("/foo", executor);
48 request.body("text/plain", "hello world");
49 Assert.assertEquals("hello world", request.postTarget(String.class));
50
51 request = new ClientRequest("/foo", executor);
52 request.header("a", "hello");
53 request.queryParameter("b", "world");
54 Assert.assertEquals("hello world", request.getTarget(String.class));
55
56 }
57 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.jboss.resteasy.client.ClientResponseFailure;
3 import org.jboss.resteasy.client.ProxyFactory;
4 import org.jboss.resteasy.test.BaseResourceTest;
5 import org.jboss.resteasy.test.TestPortProvider;
6 import org.junit.Assert;
7 import org.junit.BeforeClass;
8 import org.junit.Test;
9
10 import javax.ws.rs.Consumes;
11 import javax.ws.rs.POST;
12 import javax.ws.rs.Path;
13 import javax.ws.rs.WebApplicationException;
14
15 /**
16 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
17 * @version $Revision: 1 $
18 */
19 public class Regression435Test extends BaseResourceTest
20 {
21 @Path("/test")
22 public interface MyTest
23 {
24 @POST
25 @Consumes("text/plain")
26 public void postIt(String msg);
27 }
28
29 public static class MyTestResource implements MyTest
30 {
31 public void postIt(String msg)
32 {
33 System.out.println("HERE: " + msg);
34 throw new WebApplicationException(401);
35 }
36 }
37
38 @BeforeClass
39 public static void setup() throws Exception
40 {
41 addPerRequestResource(MyTestResource.class);
42 }
43
44 @Test
45 public void testMe() throws Exception
46 {
47 MyTest proxy = ProxyFactory.create(MyTest.class, TestPortProvider.generateURL(""));
48 try
49 {
50 proxy.postIt("hello");
51 }
52 catch (ClientResponseFailure e)
53 {
54 Assert.assertEquals(401, e.getResponse().getStatus());
55 }
56 }
57
58 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.jboss.resteasy.client.ProxyBuilder;
3 import org.jboss.resteasy.client.ProxyFactory;
4 import org.jboss.resteasy.spi.HttpRequest;
5 import org.jboss.resteasy.test.BaseResourceTest;
6 import org.jboss.resteasy.test.TestPortProvider;
7 import org.junit.Before;
8 import org.junit.Test;
9
10 import javax.ws.rs.GET;
11 import javax.ws.rs.PUT;
12 import javax.ws.rs.Path;
13 import javax.ws.rs.core.Context;
14 import javax.ws.rs.core.MediaType;
15
16 import static org.junit.Assert.assertEquals;
17
18 public class TestDefaultMediaTypes extends BaseResourceTest
19 {
20 public static interface Foo
21 {
22 @GET
23 @Path("foo")
24 String getFoo();
25
26 @PUT
27 @Path("foo")
28 String setFoo(String value);
29 }
30
31 @Path("foo")
32 public static class FooImpl implements Foo
33 {
34 @Context
35 HttpRequest request;
36
37 @Override
38 public String getFoo()
39 {
40 return request.getHttpHeaders().getAcceptableMediaTypes().toString();
41 }
42
43 @Override
44 public String setFoo(String value)
45 {
46 return request.getHttpHeaders().getMediaType().toString();
47 }
48 }
49
50 @Before
51 public void setUp() throws Exception
52 {
53 addPerRequestResource(FooImpl.class);
54 }
55
56 @Test(expected = RuntimeException.class)
57 public void testOldBehaviorContinues() throws Exception
58 {
59 String url = TestPortProvider.generateURL("/foo");
60 ProxyFactory.create(Foo.class, url);
61 }
62
63 @Test
64 public void testDefaultValues() throws Exception
65 {
66 String url = TestPortProvider.generateURL("/foo");
67 Foo foo = ProxyBuilder.build(Foo.class, url).serverMediaType(MediaType.TEXT_PLAIN_TYPE).now();
68
69 assertEquals("[text/plain]", foo.getFoo());
70 assertEquals("text/plain", foo.setFoo("SOMETHING"));
71 }
72
73 @Test
74 public void testMismatch() throws Exception
75 {
76 // NOTE: this doesn't fail on the server because the default */* provider matches the
77 // requested media type.
78 String url = TestPortProvider.generateURL("/foo");
79 Foo foo = ProxyBuilder.build(Foo.class, url).serverMediaType(MediaType.APPLICATION_JSON_TYPE).now();
80
81 assertEquals("[application/json]", foo.getFoo());
82 assertEquals("application/json", foo.setFoo("SOMETHING"));
83 }
84 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.jboss.resteasy.client.ProxyFactory;
3 import org.jboss.resteasy.client.core.marshallers.ResteasyClientProxy;
4 import org.jboss.resteasy.test.BaseResourceTest;
5 import org.jboss.resteasy.test.TestPortProvider;
6 import org.junit.Before;
7 import org.junit.Test;
8
9 import javax.ws.rs.GET;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.PathParam;
12 import javax.ws.rs.Produces;
13
14 import static org.junit.Assert.assertEquals;
15
16 public class TestProxyCastingSimple extends BaseResourceTest
17 {
18 public static interface InterfaceAorB
19 {
20 public <T> T as(Class<T> iface);
21 }
22
23 public static interface InterfaceA extends InterfaceAorB
24 {
25 @GET
26 @Path("foo")
27 @Produces("text/plain")
28 String getFoo();
29 }
30
31 public static interface InterfaceB extends InterfaceAorB
32 {
33 @GET
34 @Path("bar")
35 @Produces("text/plain")
36 String getBar();
37 }
38
39 public static interface FooBar
40 {
41 @Path("{thing}")
42 InterfaceAorB getThing(@PathParam("thing") String thing);
43 }
44
45 @Path("/foobar")
46 public static class FooBarImpl implements FooBar
47 {
48 @Override
49 public InterfaceAorB getThing(String thing)
50 {
51 if ("a".equalsIgnoreCase(thing))
52 {
53 return new InterfaceA()
54 {
55 @Override
56 public String getFoo()
57 {
58 return "FOO";
59 }
60
61 @Override
62 public <T> T as(Class<T> iface)
63 {
64 return iface.cast(this);
65 }
66 };
67 }
68 else if ("b".equalsIgnoreCase(thing))
69 {
70 return new InterfaceB()
71 {
72 @Override
73 public String getBar()
74 {
75 return "BAR";
76 }
77
78 @Override
79 public <T> T as(Class<T> iface)
80 {
81 return iface.cast(this);
82 }
83 };
84 }
85 else
86 {
87 throw new IllegalArgumentException("Bad arg: " + thing);
88 }
89 }
90 }
91
92 @Before
93 public void setUp() throws Exception
94 {
95 addPerRequestResource(FooBarImpl.class);
96 }
97
98 @Test
99 public void testSubresourceProxy() throws Exception
100 {
101 String url = TestPortProvider.generateURL("/foobar");
102 FooBar foobar = ProxyFactory.create(FooBar.class, url);
103 {
104 InterfaceA a = ((ResteasyClientProxy) foobar.getThing("a")).as(InterfaceA.class);
105 assertEquals("FOO", a.getFoo());
106 InterfaceB b = ((ResteasyClientProxy) foobar.getThing("b")).as(InterfaceB.class);
107 assertEquals("BAR", b.getBar());
108 }
109 {
110 InterfaceA a = foobar.getThing("a").as(InterfaceA.class);
111 assertEquals("FOO", a.getFoo());
112 InterfaceB b = foobar.getThing("b").as(InterfaceB.class);
113 assertEquals("BAR", b.getBar());
114 }
115 }
116 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.core.executors.URLConnectionClientExecutor;
4 import org.jboss.resteasy.test.BaseResourceTest;
5 import org.junit.Assert;
6 import org.junit.Before;
7 import org.junit.Test;
8
9 import javax.ws.rs.Consumes;
10 import javax.ws.rs.POST;
11 import javax.ws.rs.Path;
12 import javax.ws.rs.PathParam;
13 import javax.ws.rs.Produces;
14
15 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
16
17 /**
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 */
21 public class UrlExecutorTest extends BaseResourceTest
22 {
23 @Path("/test")
24 public static class TestService
25 {
26 @POST
27 @Path("{name}")
28 @Produces("text/plain")
29 @Consumes("text/plain")
30 public String post(@PathParam("name") String id, String message)
31 {
32 System.out.println("Server!!!");
33 return message + id;
34 }
35 }
36
37 @Before
38 public void setUp() throws Exception
39 {
40 addPerRequestResource(TestService.class);
41 }
42
43 @Test
44 public void testStylesheet() throws Exception
45 {
46 URLConnectionClientExecutor executor = new URLConnectionClientExecutor();
47 ClientRequest request = executor.createRequest(generateURL("/test/{name}"));
48 request.body("text/plain", "Hello ").pathParameter("name", "Bill");
49 String response = request.postTarget(String.class);
50 System.out.println(response);
51 Assert.assertEquals(response, "Hello Bill");
52 response = request.postTarget(String.class);
53 System.out.println(response);
54 Assert.assertEquals(response, "Hello Bill");
55 request.clear();
56 request.body("text/plain", "Goodbye ").pathParameter("name", "Everyone");
57 response = request.postTarget(String.class);
58 System.out.println(response);
59 Assert.assertEquals(response, "Goodbye Everyone");
60
61
62 }
63 }
0 package org.jboss.resteasy.test.client.old;
1
2 import org.jboss.resteasy.client.ProxyFactory;
3 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.jboss.resteasy.test.BaseResourceTest;
6 import org.junit.Assert;
7 import org.junit.Before;
8 import org.junit.Test;
9
10 import javax.annotation.Resource;
11 import javax.ws.rs.GET;
12 import javax.ws.rs.Path;
13 import javax.ws.rs.PathParam;
14 import javax.ws.rs.Produces;
15 import javax.ws.rs.core.Context;
16 import javax.ws.rs.core.UriInfo;
17 import java.util.List;
18
19 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
20
21 /**
22 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
23 * @version $Revision: 1 $
24 */
25 public class WhitespaceTest extends BaseResourceTest
26 {
27 @Resource
28 @Path(value = "/sayhello")
29 public static class Hello
30 {
31
32 @Context
33 UriInfo info;
34
35 @GET
36 @Path("/en/{in}")
37 @Produces("text/plain")
38 public String echo(@PathParam(value = "in") String in)
39 {
40 Assert.assertEquals(SPACES_REQUEST, in);
41 List<String> params = info.getPathParameters(true).get("in");
42 System.out.println("DECODE" + params.get(0));
43
44 params = info.getPathParameters(false).get("in");
45 System.out.println("ENCODE" + params.get(0));
46
47
48 return in;
49 }
50
51
52 }
53
54
55 @Path(value = "/sayhello")
56 public interface HelloClient
57 {
58
59 @GET
60 @Path("/en/{in}")
61 @Produces("text/plain")
62 public String sayHi(@PathParam(value = "in") String in);
63
64
65 }
66
67 @Before
68 public void setUp() throws Exception
69 {
70 addPerRequestResource(Hello.class);
71 }
72
73
74 private static final String SPACES_REQUEST = "something something";
75
76 @Test
77 public void testEcho()
78 {
79 RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
80 HelloClient client = ProxyFactory.create(HelloClient.class, generateBaseUrl());
81 Assert.assertEquals(SPACES_REQUEST, client.sayHi(SPACES_REQUEST));
82 }
83
84
85 }
0 package org.jboss.resteasy.test.encoding;
1
2 import javax.ws.rs.Encoded;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.MatrixParam;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.UriBuilder;
8
9 import org.jboss.resteasy.client.ClientRequest;
10 import org.jboss.resteasy.client.ClientResponse;
11 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
12 import org.jboss.resteasy.spi.ResteasyDeployment;
13 import org.jboss.resteasy.test.EmbeddedContainer;
14 import org.junit.AfterClass;
15 import org.junit.Assert;
16 import org.junit.BeforeClass;
17 import org.junit.Test;
18
19 /**
20 * RESTEASY-729
21 *
22 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
23 * @version $Revision: 1.1 $
24 *
25 * Copyright Aug 16, 2012
26 */
27 public class MatrixParamEncodingTest
28 {
29 protected static ResteasyDeployment deployment;
30
31 @Path("/")
32 static public class TestResource
33 {
34 @GET
35 @Path("decoded")
36 @Produces("text/plain")
37 public String matrixParamDecoded(@MatrixParam("param") String param)
38 {
39 System.out.println("matrixParamDecoded() received: " + param);
40 return param;
41 }
42
43 @GET
44 @Path("encoded")
45 @Produces("text/plain")
46 public String returnMatrixParamEncoded(@Encoded @MatrixParam("param") String param)
47 {
48 System.out.println("matrixParamEncoded() received: " + param);
49 return param;
50 }
51 }
52
53 @BeforeClass
54 public static void setup() throws Exception
55 {
56 deployment = EmbeddedContainer.start();
57 deployment.getRegistry().addPerRequestResource(TestResource.class);
58 }
59
60
61 @AfterClass
62 public static void shutdown() throws Exception
63 {
64 EmbeddedContainer.stop();
65 deployment = null;
66 }
67
68 @Test
69 public void testMatrixParamRequestDecoded() throws Exception
70 {
71 ClientRequest request = new ClientRequest("http://localhost:8081/decoded");
72 request.matrixParameter("param", "ac/dc");
73 System.out.println("Sending request: " + request.getUri());
74 ClientResponse<String> response = request.get(String.class);
75 System.out.println("Received response: " + response.getEntity());
76 Assert.assertEquals(200, response.getStatus());
77 Assert.assertEquals("ac/dc", response.getEntity());
78 response.releaseConnection();
79 }
80
81 @Test
82 public void testMatrixParamRequestEncoded() throws Exception
83 {
84 ClientRequest request = new ClientRequest("http://localhost:8081/encoded");
85 request.matrixParameter("param", "ac/dc");
86 System.out.println("Sending request: " + request.getUri());
87 ClientResponse<String> response = request.get(String.class);
88 System.out.println("Received response: " + response.getEntity());
89 Assert.assertEquals(200, response.getStatus());
90 Assert.assertEquals("ac%2Fdc", response.getEntity());
91 response.releaseConnection();
92 }
93
94 @Test
95 public void testMatrixParamUriBuilderDecoded() throws Exception
96 {
97 UriBuilder uriBuilder = ResteasyUriBuilder.fromUri("http://localhost:8081/decoded");
98 uriBuilder.matrixParam("param", "ac/dc");
99 ClientRequest request = new ClientRequest(uriBuilder.build().toString());
100 System.out.println("Sending request to " + uriBuilder.build().toString());
101 ClientResponse<String> response = request.get(String.class);
102 System.out.println("Received response: " + response.getEntity());
103 Assert.assertEquals(200, response.getStatus());
104 Assert.assertEquals("ac/dc", response.getEntity());
105 response.releaseConnection();
106 }
107
108 @Test
109 public void testMatrixParamUriBuilderEncoded() throws Exception
110 {
111 UriBuilder uriBuilder = ResteasyUriBuilder.fromUri("http://localhost:8081/encoded");
112 uriBuilder.matrixParam("param", "ac/dc");
113 ClientRequest request = new ClientRequest(uriBuilder.build().toString());
114 System.out.println("Sending request to " + uriBuilder.build().toString());
115 ClientResponse<String> response = request.get(String.class);
116 System.out.println("Received response: " + response.getEntity());
117 Assert.assertEquals(200, response.getStatus());
118 Assert.assertEquals("ac%2Fdc", response.getEntity());
119 response.releaseConnection();
120 }
121 }
0 package org.jboss.resteasy.test.encoding;
1
2 import java.util.Iterator;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.Encoded;
6 import javax.ws.rs.FormParam;
7 import javax.ws.rs.GET;
8 import javax.ws.rs.MatrixParam;
9 import javax.ws.rs.POST;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.PathParam;
12 import javax.ws.rs.Produces;
13 import javax.ws.rs.QueryParam;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.core.MultivaluedMap;
16 import javax.ws.rs.core.PathSegment;
17
18 import org.junit.Assert;
19
20 import org.jboss.resteasy.client.ClientRequest;
21 import org.jboss.resteasy.client.ClientResponse;
22 import org.jboss.resteasy.spi.ResteasyDeployment;
23 import org.jboss.resteasy.test.EmbeddedContainer;
24 import org.junit.After;
25 import org.junit.AfterClass;
26 import org.junit.Before;
27 import org.junit.BeforeClass;
28 import org.junit.Test;
29
30 /**
31 * RESTEASY-737
32 *
33 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
34 * @version $Revision: 1.1 $
35 *
36 * Copyright Aug 8, 2012
37 */
38 public class ParameterEncodingTest
39 {
40 protected static ResteasyDeployment deployment;
41
42 @Path("/")
43 static public class TestResource
44 {
45 @GET
46 @Produces("text/plain")
47 @Path("encoded/pathparam/{pathParam}")
48 public String getEncodedPathParam(@Encoded @PathParam("pathParam") String pathParam)
49 {
50 System.out.println("getEncodedPathParam(): encoded: " + pathParam);
51 return pathParam;
52 }
53
54 @GET
55 @Produces("text/plain")
56 @Path("decoded/pathparam/{pathParam}")
57 public String getDecodedPathParam(@PathParam("pathParam") String pathParam)
58 {
59 System.out.println("getDecodedPathParam(): decoded: " + pathParam);
60 return pathParam;
61 }
62
63 @GET
64 @Produces("text/plain")
65 @Path("encoded/matrix")
66 public String getEncodedMatrixParam(@Encoded @MatrixParam("m") String matrixParam)
67 {
68 System.out.println("getEncodedMatrixParam(): encoded: " + matrixParam);
69 return matrixParam;
70 }
71
72 @GET
73 @Produces("text/plain")
74 @Path("decoded/matrix")
75 public String getDecodedMatrixParam(@MatrixParam("m") String matrixParam)
76 {
77 System.out.println("getDecodedMatrixParam(): decoded: " + matrixParam);
78 return matrixParam;
79 }
80
81 @GET
82 @Produces("text/plain")
83 @Path("encoded/query")
84 public String getEncodedQueryParam(@Encoded @QueryParam("m") String queryParam)
85 {
86 System.out.println("getEncodedQueryParam(): encoded: " + queryParam);
87 return queryParam;
88 }
89
90 @GET
91 @Produces("text/plain")
92 @Path("decoded/query")
93 public String getDecodedQueryParam(@QueryParam("m") String queryParam)
94 {
95 System.out.println("getDecodedQueryParam(): decoded: " + queryParam);
96 return queryParam;
97 }
98
99 @POST
100 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
101 @Produces("text/plain")
102 @Path("encoded/form")
103 public String getEncodedFormParam(@Encoded @FormParam("f") String formParam)
104 {
105 System.out.println("getEncodedFormParamPost(): encoded: " + formParam);
106 return formParam;
107 }
108
109 @POST
110 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
111 @Produces("text/plain")
112 @Path("decoded/form")
113 public String getDecodedFormParam(@FormParam("f") String formParam)
114 {
115 System.out.println("getDecodedFormParamPost(): decoded: " + formParam);
116 return formParam;
117 }
118
119 @GET
120 @Produces("text/plain")
121 @Path("encoded/segment/{pathParam}")
122 public String getEncodedSegmentPathParam(@Encoded @PathParam("pathParam") PathSegment segment)
123 {
124 System.out.println("getEncodedSegmentPathParam(): encoded segment: " + segment.getPath());
125 return segment.getPath();
126 }
127
128 @GET
129 @Produces("text/plain")
130 @Path("decoded/segment/{pathParam}")
131 public String getDecodedSegmentPathParam(@PathParam("pathParam") PathSegment segment)
132 {
133 System.out.println("getDecodedSegmentPathParam(): decoded segment: " + segment.getPath());
134 return segment.getPath();
135 }
136
137 @GET
138 @Produces("text/plain")
139 @Path("encoded/segment/matrix/{params}")
140 public String getEncodedSegmentMatrixParam(@Encoded @PathParam("params") PathSegment segment)
141 {
142 MultivaluedMap<String, String> map = segment.getMatrixParameters();
143 Iterator<String> it = map.keySet().iterator();
144 System.out.println("getEncodedSegmentMatrixParam(): encoded matrix params: ");
145 StringBuilder builder = new StringBuilder();
146 while(it.hasNext())
147 {
148 String key = it.next();
149 System.out.println(" " + key + "->" + map.getFirst(key));
150 builder.append(map.getFirst(key));
151 }
152 return builder.toString();
153 }
154
155 @GET
156 @Produces("text/plain")
157 @Path("decoded/segment/matrix/{params}")
158 public String getDecodedSegmentMatrixParam(@PathParam("params") PathSegment segment)
159 {
160 MultivaluedMap<String, String> map = segment.getMatrixParameters();
161 Iterator<String> it = map.keySet().iterator();
162 System.out.println("getDecodedSegmentMatrixParam(): decoded matrix params: ");
163 StringBuilder builder = new StringBuilder();
164 while(it.hasNext())
165 {
166 String key = it.next();
167 System.out.println(" " + key + "->" + map.getFirst(key));
168 builder.append(map.getFirst(key));
169 }
170 return builder.toString();
171 }
172 }
173
174 @BeforeClass
175 public static void setup() throws Exception
176 {
177 deployment = EmbeddedContainer.start();
178 deployment.getRegistry().addPerRequestResource(TestResource.class);
179 }
180
181 @AfterClass
182 public static void shutdown() throws Exception
183 {
184 EmbeddedContainer.stop();
185 deployment = null;
186 }
187
188 @Test
189 public void testResteasy734() throws Exception
190 {
191 ClientRequest request = null;
192 ClientResponse<String> response = null;
193
194 request = new ClientRequest("http://localhost:8081/encoded/pathparam/bee bop");
195 response = request.get(String.class);
196 System.out.println("Received encoded path param: " + response.getEntity());
197 Assert.assertEquals(200, response.getStatus());
198 Assert.assertEquals("bee%20bop", response.getEntity());
199 response.releaseConnection();
200
201 request = new ClientRequest("http://localhost:8081/decoded/pathparam/bee bop");
202 response = request.get(String.class);
203 System.out.println("Received decoded path param: " + response.getEntity());
204 Assert.assertEquals(200, response.getStatus());
205 Assert.assertEquals("bee bop", response.getEntity());
206 response.releaseConnection();
207
208 request = new ClientRequest("http://localhost:8081/encoded/matrix;m=bee bop");
209 response = request.get(String.class);
210 System.out.println("Received encoded matrix param: " + response.getEntity());
211 Assert.assertEquals(200, response.getStatus());
212 Assert.assertEquals("bee%20bop", response.getEntity());
213 response.releaseConnection();
214
215 request = new ClientRequest("http://localhost:8081/decoded/matrix;m=bee bop");
216 response = request.get(String.class);
217 System.out.println("Received decoded matrix param: " + response.getEntity());
218 Assert.assertEquals(200, response.getStatus());
219 Assert.assertEquals("bee bop", response.getEntity());
220 response.releaseConnection();
221
222 request = new ClientRequest("http://localhost:8081/encoded/query?m=bee bop");
223 response = request.get(String.class);
224 System.out.println("Received encoded query param: " + response.getEntity());
225 Assert.assertEquals(200, response.getStatus());
226 Assert.assertEquals("bee%20bop", response.getEntity());
227 response.releaseConnection();
228
229 request = new ClientRequest("http://localhost:8081/decoded/query?m=bee bop");
230 response = request.get(String.class);
231 System.out.println("Received decoded query param: " + response.getEntity());
232 Assert.assertEquals(200, response.getStatus());
233 Assert.assertEquals("bee bop", response.getEntity());
234 response.releaseConnection();
235
236 request = new ClientRequest("http://localhost:8081/encoded/form");
237 request.formParameter("f", "bee bop");
238 response = request.post(String.class);
239 System.out.println("Received encoded form param: " + response.getEntity());
240 Assert.assertEquals(200, response.getStatus());
241 Assert.assertEquals("bee+bop", response.getEntity());
242 response.releaseConnection();
243
244 request = new ClientRequest("http://localhost:8081/decoded/form");
245 request.formParameter("f", "bee bop");
246 response = request.post(String.class);
247 System.out.println("Received decoded form param: " + response.getEntity());
248 Assert.assertEquals(200, response.getStatus());
249 Assert.assertEquals("bee bop", response.getEntity());
250 response.releaseConnection();
251
252 request = new ClientRequest("http://localhost:8081/encoded/segment/bee bop");
253 response = request.get(String.class);
254 System.out.println("Received encoded path param from segment: " + response.getEntity());
255 Assert.assertEquals(200, response.getStatus());
256 Assert.assertEquals("bee%20bop", response.getEntity());
257 response.releaseConnection();
258
259 request = new ClientRequest("http://localhost:8081/decoded/segment/bee bop");
260 response = request.get(String.class);
261 System.out.println("Received decoded path param from segment: " + response.getEntity());
262 Assert.assertEquals(200, response.getStatus());
263 Assert.assertEquals("bee bop", response.getEntity());
264 response.releaseConnection();
265
266 request = new ClientRequest("http://localhost:8081/encoded/segment/matrix/params;m=bee bop");
267 response = request.get(String.class);
268 System.out.println("Received encoded matrix param from segment: " + response.getEntity());
269 Assert.assertEquals(200, response.getStatus());
270 Assert.assertEquals("bee%20bop", response.getEntity());
271 response.releaseConnection();
272
273 request = new ClientRequest("http://localhost:8081/decoded/segment/matrix/params;m=bee bop");
274 response = request.get(String.class);
275 System.out.println("Received decoded matrix param from segment: " + response.getEntity());
276 Assert.assertEquals(200, response.getStatus());
277 Assert.assertEquals("bee bop", response.getEntity());
278 response.releaseConnection();
279 }
280 }
0 package org.jboss.resteasy.test.finegrain;
1
2 import org.junit.Assert;
3 import org.jboss.resteasy.annotations.ClientResponseType;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.ProxyFactory;
6 import org.jboss.resteasy.core.Dispatcher;
7 import org.jboss.resteasy.core.MessageBodyParameterInjector;
8 import org.jboss.resteasy.spi.BadRequestException;
9 import org.jboss.resteasy.spi.InternalDispatcher;
10 import org.jboss.resteasy.spi.ResteasyProviderFactory;
11 import org.jboss.resteasy.test.EmbeddedContainer;
12 import org.junit.AfterClass;
13 import org.junit.Before;
14 import org.junit.BeforeClass;
15 import org.junit.Test;
16
17 import javax.ws.rs.Consumes;
18 import javax.ws.rs.DELETE;
19 import javax.ws.rs.DefaultValue;
20 import javax.ws.rs.GET;
21 import javax.ws.rs.POST;
22 import javax.ws.rs.PUT;
23 import javax.ws.rs.Path;
24 import javax.ws.rs.PathParam;
25 import javax.ws.rs.Produces;
26 import javax.ws.rs.QueryParam;
27 import javax.ws.rs.core.Context;
28 import javax.ws.rs.core.Response;
29 import javax.ws.rs.core.UriInfo;
30 import java.util.Stack;
31
32 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
33
34 /**
35 * Test for InternalDispatcher
36 *
37 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
38 * @version $Revision: 1 $
39 */
40
41 public class InternalDispatcherTest
42 {
43
44 private static Dispatcher dispatcher;
45 private static ForwardingResource forwardingResource;
46
47 private static final String PATH = "/foo/bar";
48
49 @Path("/")
50 public interface Client
51 {
52 @GET
53 @Path("basic")
54 @Produces("text/plain")
55 String getBasic();
56
57 @PUT
58 @Path("basic")
59 @Consumes("text/plain")
60 void putBasic(String body);
61
62 @GET
63 @Path("forward/basic")
64 @Produces("text/plain")
65 String getForwardBasic();
66
67 @PUT
68 @Path("forward/basic")
69 @Consumes("text/plain")
70 void putForwardBasic(String body);
71
72 @POST
73 @Path("forward/basic")
74 @Consumes("text/plain")
75 void postForwardBasic(String body);
76
77 @DELETE
78 @Path("/forward/basic")
79 void deleteForwardBasic();
80
81 @GET
82 @Produces("text/plain")
83 @Path("/forward/object/{id}")
84 @ClientResponseType(entityType = String.class)
85 Response getForwardedObject(@PathParam("id") Integer id);
86
87 @GET
88 @Produces("text/plain")
89 @Path("/object/{id}")
90 @ClientResponseType(entityType = String.class)
91 Response getObject(@PathParam("id") Integer id);
92
93 @GET
94 @Produces("text/plain")
95 @Path("/infinite-forward")
96 int infiniteForward();
97
98 @GET
99 @Path(PATH + "/basic")
100 @Produces("text/plain")
101 String getComplexBasic();
102
103 @GET
104 @Path(PATH + "/forward/basic")
105 @Produces("text/plain")
106 String getComplexForwardBasic();
107 }
108
109 @Path("/")
110 public static class ForwardingResource
111 {
112 public Stack<String> uriStack = new Stack<String>();
113 String basic = "basic";
114 @Context
115 UriInfo uriInfo;
116
117 @GET
118 @Produces("text/plain")
119 @Path("/basic")
120 public String getBasic()
121 {
122 String item = uriInfo.getAbsolutePath().toString();
123 uriStack.push(item);
124 return basic;
125 }
126
127 @GET
128 @Produces("text/plain")
129 @Path("/forward/basic")
130 public String forwardBasic(@Context InternalDispatcher dispatcher)
131 {
132 uriStack.push(uriInfo.getAbsolutePath().toString());
133 return (String) dispatcher.getEntity("/basic");
134 }
135
136 @PUT
137 @POST
138 @Consumes("text/plain")
139 @Path("/basic")
140 public void putBasic(String basic)
141 {
142 uriStack.push(uriInfo.getAbsolutePath().toString());
143 this.basic = basic;
144 }
145
146 @DELETE
147 @Path("/basic")
148 public void deleteBasic()
149 {
150 uriStack.push(uriInfo.getAbsolutePath().toString());
151 this.basic = "basic";
152 }
153
154 @PUT
155 @Consumes("text/plain")
156 @Path("/forward/basic")
157 public void putForwardBasic(String basic,
158 @Context InternalDispatcher dispatcher)
159 {
160 uriStack.push(uriInfo.getAbsolutePath().toString());
161 dispatcher.putEntity("/basic", basic);
162 }
163
164 @POST
165 @Consumes("text/plain")
166 @Path("/forward/basic")
167 public void postForwardBasic(String basic,
168 @Context InternalDispatcher dispatcher)
169 {
170 uriStack.push(uriInfo.getAbsolutePath().toString());
171 dispatcher.postEntity("/basic", basic);
172 }
173
174 @DELETE
175 @Path("/forward/basic")
176 public void deleteForwardBasic(@Context InternalDispatcher dispatcher)
177 {
178 uriStack.push(uriInfo.getAbsolutePath().toString());
179 dispatcher.delete("/basic");
180 }
181
182 @GET
183 @Produces("text/plain")
184 @Path("/object/{id}")
185 public Response getObject(@PathParam("id") Integer id)
186 {
187 uriStack.push(uriInfo.getAbsolutePath().toString());
188 if (id == 0)
189 return Response.noContent().build();
190 else
191 return Response.ok("object" + id).build();
192 }
193
194 @GET
195 @Path("/forward/object/{id}")
196 public Response forwardObject(@PathParam("id") Integer id,
197 @Context InternalDispatcher dispatcher)
198 {
199 uriStack.push(uriInfo.getAbsolutePath().toString());
200 return dispatcher.getResponse("/object/" + id);
201 }
202
203 @GET
204 @Path(PATH + "/basic")
205 @Produces("text/plain")
206 public String getComplexBasic() {
207 uriStack.push(uriInfo.getAbsolutePath().toString());
208 return PATH + basic;
209 }
210
211 @GET
212 @Produces("text/plain")
213 @Path(PATH + "/forward/basic")
214 public String complexForwardBasic(@Context InternalDispatcher dispatcher)
215 {
216 uriStack.push(uriInfo.getAbsolutePath().toString());
217 return (String) dispatcher.getEntity(PATH + "/basic");
218 }
219
220 @GET
221 @Path("/infinite-forward")
222 @Produces("text/plain")
223 public int infinitFoward(@Context InternalDispatcher dispatcher,
224 @QueryParam("count") @DefaultValue("0") int count)
225 {
226 uriStack.push(uriInfo.getAbsolutePath().toString());
227 try
228 {
229 dispatcher.getEntity("/infinite-forward?count=" + (count + 1));
230 // we'll never reach 20, since the max count of times through the
231 // system is 20, and first time through is 0
232 Assert.assertNotSame(20, count);
233 }
234 catch (BadRequestException e)
235 {
236
237 }
238 finally
239 {
240 Assert
241 .assertEquals(count, MessageBodyParameterInjector.bodyCount());
242 Assert.assertEquals(count + 1, ResteasyProviderFactory
243 .getContextDataLevelCount());
244 }
245 return ResteasyProviderFactory.getContextDataLevelCount();
246 }
247 }
248
249 @BeforeClass
250 public static void before() throws Exception
251 {
252 dispatcher = EmbeddedContainer.start().getDispatcher();
253 forwardingResource = new ForwardingResource();
254 dispatcher.getRegistry().addSingletonResource(forwardingResource);
255 }
256
257 @Before
258 public void setup() {
259 forwardingResource.uriStack.clear();
260 }
261
262 @AfterClass
263 public static void after() throws Exception
264 {
265 EmbeddedContainer.stop();
266 }
267
268 @Test
269 public void testClientResponse() throws Exception
270 {
271 Client client = ProxyFactory.create(Client.class, generateBaseUrl());
272
273 Assert.assertEquals("basic", client.getBasic());
274 Assert.assertEquals("basic", client.getForwardBasic());
275 Assert.assertEquals("object1", client.getObject(1).getEntity());
276 Assert.assertEquals("object1", client.getForwardedObject(1).getEntity());
277 ClientResponse<?> cr = (ClientResponse<?>) client.getObject(0);
278 Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus());
279 cr.releaseConnection();
280 cr = (ClientResponse<?>) client.getForwardedObject(0);
281 Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus());
282 cr.releaseConnection();
283
284 client.putForwardBasic("testBasic");
285 Assert.assertEquals("testBasic", client.getBasic());
286 client.postForwardBasic("testBasic1");
287 Assert.assertEquals("testBasic1", client.getBasic());
288 client.deleteForwardBasic();
289 Assert.assertEquals("basic", client.getBasic());
290
291 }
292
293 @Test
294 public void testInfinitForward()
295 {
296 Client client = ProxyFactory.create(Client.class, generateBaseUrl());
297 // assert that even though there were infinite forwards, there still was
298 // only 1 level of "context" data and that clean up occurred correctly.
299 // This should not spin forever, since RESTEasy stops the recursive loop
300 // after 20 internal dispatches
301 Assert.assertEquals(1, client.infiniteForward());
302 }
303
304 @Test
305 public void testUriInfoBasic() {
306 String baseUrl = generateBaseUrl();
307 Client client = ProxyFactory.create(Client.class, baseUrl);
308
309 client.getBasic();
310 Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop());
311 Assert.assertTrue(forwardingResource.uriStack.isEmpty());
312
313 }
314
315 @Test
316 public void testUriInfoForwardBasic() {
317 String baseUrl = generateBaseUrl();
318 Client client = ProxyFactory.create(Client.class, baseUrl);
319
320 client.getForwardBasic();
321 Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop());
322 Assert.assertEquals(baseUrl + "/forward/basic", forwardingResource.uriStack.pop());
323 Assert.assertTrue(forwardingResource.uriStack.isEmpty());
324 }
325
326 @Test
327 public void testUriInfoForwardBasicComplexUri() {
328 String baseUrl = generateBaseUrl();
329 Client client = ProxyFactory.create(Client.class, baseUrl);
330
331 client.getComplexForwardBasic();
332 Assert.assertEquals(baseUrl + PATH + "/basic", forwardingResource.uriStack.pop());
333 Assert.assertEquals(baseUrl + PATH + "/forward/basic", forwardingResource.uriStack.pop());
334 Assert.assertTrue(forwardingResource.uriStack.isEmpty());
335 }
336
337 }
0 package org.jboss.resteasy.test.finegrain;
1
2 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
3
4 import java.util.logging.Handler;
5 import java.util.logging.LogManager;
6 import java.util.logging.LogRecord;
7
8 import javax.annotation.Resource;
9 import javax.ws.rs.GET;
10 import javax.ws.rs.POST;
11 import javax.ws.rs.PUT;
12 import javax.ws.rs.Path;
13 import javax.ws.rs.Produces;
14 import javax.ws.rs.client.Client;
15 import javax.ws.rs.client.ClientBuilder;
16 import javax.ws.rs.core.MediaType;
17 import javax.ws.rs.core.Response;
18
19 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
20 import org.jboss.resteasy.test.BaseResourceTest;
21 import org.junit.After;
22 import org.junit.Assert;
23 import org.junit.Before;
24 import org.junit.FixMethodOrder;
25 import org.junit.Test;
26 import org.junit.runners.MethodSorters;
27
28 /**
29 * RESTEASY-1398 - false "multiple endpoints" warning
30 *
31 * @author <a href="mailto:thofman@redhat.com">Tomas Hofman</a>
32 */
33 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
34 public class MultipleEndpointsWarningTest extends BaseResourceTest
35 {
36 @Resource
37 @Path("")
38 public static class Hello
39 {
40 @Path("unique")
41 @GET
42 public String unique() throws Exception {
43 return "Hello";
44 }
45
46 @Path("verbs")
47 @GET
48 @Produces("text/plain")
49 public String getVerb() throws Exception {
50 return "Hello";
51 }
52
53 @Path("verbs")
54 @POST
55 @Produces("text/plain")
56 public String postVerb() throws Exception {
57 return "Hello";
58 }
59
60 @Path("verbs")
61 @PUT
62 @Produces("text/plain")
63 public String putVerb() throws Exception {
64 return "Hello";
65 }
66
67 @Path("duplicate")
68 @GET
69 public String duplicate1() throws Exception {
70 return "Hello";
71 }
72
73 @Path("duplicate")
74 @GET
75 public String duplicate2() throws Exception {
76 return "Hello";
77 }
78 }
79
80 private class LogHandler extends Handler {
81
82 private volatile int messagesLogged = 0;
83
84 @Override
85 public void publish(LogRecord record) {
86 if (record.getMessage().contains(MESSAGE_CODE)) {
87 messagesLogged++;
88 }
89 }
90
91 @Override
92 public void flush() {
93 }
94
95 @Override
96 public void close() throws SecurityException {
97 }
98 }
99
100 private static String MESSAGE_CODE = "RESTEASY002142";
101
102 private LogHandler logHandler = new LogHandler();
103
104 @Before
105 public void setUp() throws Exception
106 {
107 LogManager.getLogManager().getLogger(LogMessages.LOGGER.getClass().getPackage().getName()).addHandler(logHandler);
108
109 addPerRequestResource(Hello.class);
110 }
111
112 @After
113 public void tearDown() {
114 logHandler.messagesLogged = 0;
115 LogManager.getLogManager().getLogger(LogMessages.LOGGER.getClass().getPackage().getName()).removeHandler(logHandler);
116 }
117
118 @Test
119 public void test1_Unique() throws Exception {
120 Client client = ClientBuilder.newClient();
121 Response response = client.target(generateURL("/unique")).request().accept(MediaType.TEXT_PLAIN, MediaType.WILDCARD).get();
122 response.close();
123 Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
124
125 response = client.target(generateURL("/unique")).request().get();
126 response.close();
127 Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
128
129 response = client.target(generateURL("/unique")).request().accept(MediaType.TEXT_PLAIN).get();
130 response.close();
131 Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
132 }
133
134 @Test
135 public void test2_DifferentVerbs() throws Exception {
136 Client client = ClientBuilder.newClient();
137 Response response = client.target(generateURL("/verbs")).request().accept(MediaType.TEXT_PLAIN).get();
138 response.close();
139 Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
140
141 response = client.target(generateURL("/verbs")).request().accept(MediaType.TEXT_PLAIN, MediaType.WILDCARD).get();
142 response.close();
143 Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
144
145 response = client.target(generateURL("/verbs")).request().get();
146 response.close();
147 Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
148 }
149
150 @Test
151 public void test3_Duplicate() throws Exception {
152 Client client = ClientBuilder.newClient();
153 Response response = client.target(generateURL("/duplicate")).request().get();
154 response.close();
155 Assert.assertEquals(MESSAGE_CODE + " should've been logged once", 1, logHandler.messagesLogged);
156 }
157 }
0 package org.jboss.resteasy.test.finegrain.application;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.spi.ResteasyDeployment;
6 import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
7 import org.jboss.resteasy.test.EmbeddedContainer;
8 import org.junit.AfterClass;
9 import org.junit.Assert;
10 import org.junit.BeforeClass;
11 import org.junit.Test;
12
13 import javax.ws.rs.DELETE;
14 import javax.ws.rs.GET;
15 import javax.ws.rs.Path;
16 import javax.ws.rs.PathParam;
17 import javax.ws.rs.Produces;
18 import javax.ws.rs.WebApplicationException;
19 import javax.ws.rs.core.Application;
20 import javax.ws.rs.core.Response;
21 import javax.ws.rs.core.Response.Status;
22 import javax.ws.rs.ext.Provider;
23 import java.util.HashSet;
24 import java.util.Set;
25
26 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
27
28 /**
29 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
30 * @version $Revision: 1 $
31 */
32 public class ApplicationConfigWithInterceptorTest
33 {
34 @Path("/my")
35 public static class MyResource
36 {
37 @GET
38 @Produces("text/plain")
39 @Path("/good")
40 public String get()
41 {
42 return "hello";
43 }
44
45 @GET
46 @Produces("text/plain")
47 @Path("/bad")
48 public String response()
49 {
50 throw new WebApplicationException(Response.status(Status.CONFLICT).entity("conflicted").build());
51 }
52
53 @DELETE
54 @Path("{id}")
55 public void remove(@PathParam("id") String id)
56 {
57 return;
58 }
59 }
60
61 @Provider
62 public static class AddHeader implements PostProcessInterceptor
63 {
64 public void postProcess(ServerResponse response)
65 {
66 System.out.println("HERE!!!!!");
67 response.getMetadata().add("custom-header", "hello");
68 }
69 }
70
71 public static class MyApplicationConfig extends Application
72 {
73 private Set<Class<?>> classes = new HashSet<Class<?>>();
74
75 public MyApplicationConfig()
76 {
77 classes.add(MyResource.class);
78 classes.add(AddHeader.class);
79 }
80
81 @Override
82 public Set<Class<?>> getClasses()
83 {
84 return classes;
85 }
86
87 }
88
89 @BeforeClass
90 public static void before() throws Exception
91 {
92 ResteasyDeployment deployment = new ResteasyDeployment();
93 deployment.setApplication(new MyApplicationConfig());
94 EmbeddedContainer.start(deployment);
95 }
96
97 @AfterClass
98 public static void after() throws Exception
99 {
100 EmbeddedContainer.stop();
101 }
102
103 @Test
104 public void testNormalReturn() throws Exception
105 {
106 doTest("/my/good", 200);
107 }
108
109 @Test
110 public void testWebApplicationExceptionWithResponse() throws Exception
111 {
112 doTest("/my/bad", 409);
113 }
114
115 @Test
116 public void testNoContentResponse() throws Exception
117 {
118 doTest("/my/123", 204, false);
119 }
120
121 @SuppressWarnings("unchecked")
122 private void doTest(String path, int expectedStatus) throws Exception
123 {
124 doTest(path, expectedStatus, true);
125 }
126
127 @SuppressWarnings("unchecked")
128 private void doTest(String path, int expectedStatus, boolean get) throws Exception
129 {
130 ClientRequest request = new ClientRequest(generateURL(path));
131 ClientResponse response = get ? request.get() : request.delete();
132 Assert.assertEquals(expectedStatus, response.getStatus());
133 Assert.assertNotNull(response.getResponseHeaders().getFirst("custom-header"));
134
135 }
136 }
0 package org.jboss.resteasy.test.finegrain.client;
1
2 import org.jboss.resteasy.client.ProxyFactory;
3 import org.jboss.resteasy.core.Dispatcher;
4 import org.jboss.resteasy.test.EmbeddedContainer;
5 import org.junit.Assert;
6 import org.junit.Test;
7
8 import javax.ws.rs.FormParam;
9 import javax.ws.rs.POST;
10 import javax.ws.rs.Path;
11
12 import static org.jboss.resteasy.test.TestPortProvider.createClientRequest;
13 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
14
15 public class ClientFormParamTest
16 {
17
18 public static class FormResourceImpl implements FormResource
19 {
20 public String put(String value)
21 {
22 return value;
23 }
24 }
25
26 @Path("/form")
27 public static interface FormResource
28 {
29 @POST
30 public String put(@FormParam("value") String value);
31 }
32
33 @Test
34 public void test() throws Exception
35 {
36 final Dispatcher dispatcher = EmbeddedContainer.start().getDispatcher();
37 try
38 {
39 dispatcher.getRegistry().addPerRequestResource(FormResourceImpl.class);
40 final FormResource client = ProxyFactory.create(FormResource.class, generateBaseUrl());
41 final String result = client.put("value");
42 Assert.assertEquals(result, "value");
43 final String result1 = createClientRequest("/form").formParameter("value", "value").post(
44 String.class).getEntity();
45 Assert.assertEquals(result1, "value");
46 }
47 finally
48 {
49 EmbeddedContainer.stop();
50 }
51 }
52
53 }
0 package org.jboss.resteasy.test.finegrain.methodparams;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.core.Dispatcher;
5 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.test.EmbeddedContainer;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.junit.AfterClass;
9 import org.junit.Assert;
10 import org.junit.BeforeClass;
11 import org.junit.Test;
12
13 import javax.ws.rs.GET;
14 import javax.ws.rs.NotFoundException;
15 import javax.ws.rs.Path;
16 import javax.ws.rs.core.Context;
17 import javax.ws.rs.core.Response;
18 import javax.ws.rs.ext.ExceptionMapper;
19 import javax.ws.rs.ext.Provider;
20 import javax.ws.rs.ext.Providers;
21
22 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
23
24 /**
25 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
26 * @version $Revision: 1 $
27 */
28 public class ExceptionMapperTest
29 {
30 private static Dispatcher dispatcher;
31
32 public static class MyException extends Exception
33 {
34 public MyException()
35 {
36 }
37
38 public MyException(String s)
39 {
40 super(s);
41 }
42
43 public MyException(String s, Throwable throwable)
44 {
45 super(s, throwable);
46 }
47
48 public MyException(Throwable throwable)
49 {
50 super(throwable);
51 }
52 }
53
54 public static class SubclassException extends MyException
55 {
56 public SubclassException(String s)
57 {
58 super(s);
59 }
60 }
61
62 @Path("/")
63 public static class Throwme
64 {
65 @GET
66 public String get() throws MyException
67 {
68 throw new MyException("FAILURE!!!");
69 }
70
71 @Path("subclass")
72 @GET
73 public String getSubclass() throws MyException
74 {
75 throw new SubclassException("FAILURE!!!");
76 }
77
78 @Path("providers")
79 @GET
80 public String getProvidersTest(@Context Providers providers)
81 {
82 Assert.assertNotNull(providers);
83 Assert.assertEquals(providers.getExceptionMapper(MyException.class).getClass(), MyExceptionMapper.class);
84 return "stuff";
85 }
86 }
87
88 @BeforeClass
89 public static void before() throws Exception
90 {
91 dispatcher = EmbeddedContainer.start().getDispatcher();
92 dispatcher.getRegistry().addPerRequestResource(Throwme.class);
93 ResteasyProviderFactory.getInstance().registerProvider(MyExceptionMapper.class);
94 ResteasyProviderFactory.getInstance().registerProvider(NotFoundMapper.class);
95 }
96
97 @AfterClass
98 public static void after() throws Exception
99 {
100 EmbeddedContainer.stop();
101 }
102
103 @Provider
104 public static class MyExceptionMapper implements ExceptionMapper<MyException>
105 {
106 public Response toResponse(MyException exception)
107 {
108 return Response.notModified().build();
109 }
110 }
111
112 @Test
113 public void testRegisteredCorrectly()
114 {
115 Assert.assertNotNull(ResteasyProviderFactory.getInstance().getExceptionMapper(MyException.class));
116 Assert.assertNotNull(ResteasyProviderFactory.getInstance().getExceptionMapper(NotFoundException.class));
117 }
118
119 private static boolean notFoundMapper = false;
120
121 @Provider
122 public static class NotFoundMapper implements ExceptionMapper<NotFoundException>
123 {
124 public Response toResponse(NotFoundException exception)
125 {
126 notFoundMapper = true;
127 return Response.status(410).build();
128 }
129 }
130
131 @Test
132 public void testProvidersInjection()
133 {
134 ClientRequest request = new ClientRequest(generateURL("/providers"));
135 ClientResponse<?> response;
136 try
137 {
138 response = request.get();
139 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
140 response.releaseConnection();
141 } catch (Exception e)
142 {
143 throw new RuntimeException(e);
144 }
145 }
146
147 @Test
148 public void testMapping()
149 {
150 ClientRequest request = new ClientRequest(generateURL(""));
151 ClientResponse<?> response;
152 try
153 {
154 response = request.get();
155 Assert.assertEquals(HttpResponseCodes.SC_NOT_MODIFIED, response.getStatus());
156 response.releaseConnection();
157 } catch (Exception e)
158 {
159 throw new RuntimeException(e);
160 }
161 }
162
163 @Test
164 public void testSubclassMapping()
165 {
166 ClientRequest request = new ClientRequest(generateURL("/subclass"));
167 ClientResponse<?> response;
168 try
169 {
170 response = request.get();
171 Assert.assertEquals(HttpResponseCodes.SC_NOT_MODIFIED, response.getStatus());
172 response.releaseConnection();
173 } catch (Exception e)
174 {
175 throw new RuntimeException(e);
176 }
177 }
178
179 @Test
180 public void testResteasyExceptionMapping()
181 {
182 ClientRequest request = new ClientRequest(generateURL("/notexist"));
183 ClientResponse<?> response;
184 try
185 {
186 response = request.get();
187 Assert.assertEquals(410, response.getStatus());
188 response.releaseConnection();
189 } catch (Exception e)
190 {
191 throw new RuntimeException(e);
192 }
193 }
194 }
0 package org.jboss.resteasy.test.finegrain.methodparams;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.test.BaseResourceTest;
5 import org.jboss.resteasy.test.TestPortProvider;
6 import org.junit.Assert;
7 import org.junit.Before;
8 import org.junit.Test;
9
10 import javax.ws.rs.GET;
11 import javax.ws.rs.MatrixParam;
12 import javax.ws.rs.Path;
13 import javax.ws.rs.PathParam;
14 import javax.ws.rs.Produces;
15 import javax.ws.rs.core.Context;
16 import javax.ws.rs.core.MultivaluedMap;
17 import javax.ws.rs.core.PathSegment;
18 import javax.ws.rs.core.Response;
19 import javax.ws.rs.core.UriInfo;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23
24 /**
25 * Spec requires that HEAD and OPTIONS are handled in a default manner
26 *
27 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
28 * @version $Revision: 1 $
29 */
30 public class PathParamTest extends BaseResourceTest
31 {
32
33 @Path(value = "/PathParamTest")
34 public static class Resource
35 {
36 @GET
37 @Path("/{id}")
38 public Response single(@PathParam("id") String id)
39 {
40 return Response.ok("single=" + id).build();
41 }
42
43 @GET
44 @Path("/{id}/{id1}")
45 public Response two(@PathParam("id") String id,
46 @PathParam("id1") PathSegment id1)
47 {
48 return Response.ok("double=" + id + id1.getPath()).build();
49 }
50
51 @GET
52 @Path("/{id}/{id1}/{id2}")
53 public Response triple(@PathParam("id") int id,
54 @PathParam("id1") PathSegment id1,
55 @PathParam("id2") float id2)
56 {
57 return Response.ok("triple=" + id + id1.getPath() + id2).build();
58 }
59
60 @GET
61 @Path("/{id}/{id1}/{id2}/{id3}")
62 public Response quard(@PathParam("id") double id,
63 @PathParam("id1") boolean id1,
64 @PathParam("id2") byte id2,
65 @PathParam("id3") PathSegment id3)
66 {
67 return Response.ok("quard=" + id + id1 + id2 + id3.getPath()).build();
68 }
69
70 @GET
71 @Path("/{id}/{id1}/{id2}/{id3}/{id4}")
72 public Response penta(@PathParam("id") long id,
73 @PathParam("id1") String id1,
74 @PathParam("id2") short id2,
75 @PathParam("id3") boolean id3,
76 @PathParam("id4") PathSegment id4)
77 {
78 return Response.ok("penta=" + id + id1 + id2 + id3 + id4.getPath()).
79 build();
80 }
81
82 @Produces("text/plain")
83 @GET
84 @Path("/{id}/{id}/{id}/{id}/{id}/{id}")
85 public Response list(@PathParam("id") List<String> id)
86 {
87 StringBuffer sb = new StringBuffer();
88 sb.append("list=");
89 for (String tmp : id)
90 {
91 sb.append(tmp);
92 }
93 return Response.ok(sb.toString()).build();
94 }
95
96 @Produces("text/plain")
97 @GET
98 @Path("/matrix/{id}")
99 public Response matrixparamtest(@PathParam("id") PathSegment id)
100 {
101 StringBuffer sb = new StringBuffer();
102 sb.append("matrix=");
103
104 sb.append("/" + id.getPath());
105 MultivaluedMap<String, String> matrix = id.getMatrixParameters();
106 Set keys = matrix.keySet();
107 for (Object key : keys)
108 {
109 sb.append(";" + key.toString() + "=" +
110 matrix.getFirst(key.toString()));
111
112 }
113 return Response.ok(sb.toString()).build();
114 }
115 }
116
117 @Path("/digits")
118 public static class Digits
119 {
120 @Path("{id:\\d+}")
121 @GET
122 public String get(@PathParam("id") int id)
123 {
124 Assert.assertEquals(5150, id);
125 return Integer.toString(id);
126 }
127 }
128
129 @Path("/employeeinfo")
130 public static class Email
131 {
132 @GET
133 @Path("/employees/{firstname}.{lastname}@{domain}.com")
134 @Produces("text/plain")
135 public String getEmployeeLastName(@PathParam("lastname") String lastName)
136 {
137 return lastName;
138 }
139 }
140
141
142 @Before
143 public void setUp() throws Exception
144 {
145 deployment.getRegistry().addPerRequestResource(Digits.class);
146 deployment.getRegistry().addPerRequestResource(Resource.class);
147 deployment.getRegistry().addPerRequestResource(CarResource.class);
148 deployment.getRegistry().addPerRequestResource(Email.class);
149 }
150
151 @Test
152 public void testEmail() throws Exception
153 {
154
155 ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/employeeinfo/employees/bill.burke@burkecentral.com"));
156 String str = request.getTarget(String.class);
157 Assert.assertEquals("burke", str);
158 }
159
160
161 /*
162 * Client invokes GET on root resource at /PathParamTest;
163 * Verify that right Method is invoked using
164 * PathParam primitive type List<String>.
165 */
166 @Test
167 public void test6() throws Exception
168 {
169
170 String[] Headers = {"list=abcdef"};//, "list=fedcba"};
171
172 for (String header : Headers)
173 {
174 ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/PathParamTest/a/b/c/d/e/f"));
175 request.header("Accept", "text/plain");
176 ClientResponse<String> response = request.get(String.class);
177 Assert.assertEquals(200, response.getStatus());
178 Assert.assertEquals(header, response.getEntity());
179 }
180 }
181
182 @Test
183 public void test178() throws Exception
184 {
185 {
186 ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/digits/5150"));
187 ClientResponse<?> response = request.get();
188 Assert.assertEquals(200, response.getStatus());
189 response.releaseConnection();
190 }
191
192 {
193 ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/digits/5150A"));
194 ClientResponse<?> response = request.get();
195 Assert.assertEquals(404, response.getStatus());
196 response.releaseConnection();
197 }
198 }
199
200 @Path("/cars/{make}")
201 public static class CarResource
202 {
203 public static enum Color
204 {
205 red,
206 white,
207 blue,
208 black
209 }
210
211 @GET
212 @Path("/matrixparam/{model}/{year}")
213 @Produces("text/plain")
214 public String getFromMatrixParam(@PathParam("make") String make,
215 @PathParam("model") PathSegment car,
216 @MatrixParam("color") Color color,
217 @PathParam("year") String year)
218 {
219 return "A " + color + " " + year + " " + make + " " + car.getPath();
220 }
221
222
223 @GET
224 @Path("/pathsegment/{model}/{year}")
225 @Produces("text/plain")
226 public String getFromPathSegment(@PathParam("make") String make,
227 @PathParam("model") PathSegment car,
228 @PathParam("year") String year)
229 {
230 String carColor = car.getMatrixParameters().getFirst("color");
231 return "A " + carColor + " " + year + " " + make + " " + car.getPath();
232 }
233
234 @GET
235 @Path("/pathsegments/{model : .+}/year/{year}")
236 @Produces("text/plain")
237 public String getFromMultipleSegments(@PathParam("make") String make,
238 @PathParam("model") List<PathSegment> car,
239 @PathParam("year") String year)
240 {
241 String output = "A " + year + " " + make;
242 for (PathSegment segment : car)
243 {
244 output += " " + segment.getPath();
245 }
246 return output;
247 }
248
249 @GET
250 @Path("/uriinfo/{model}/{year}")
251 @Produces("text/plain")
252 public String getFromUriInfo(@Context UriInfo info)
253 {
254 String make = info.getPathParameters().getFirst("make");
255 String year = info.getPathParameters().getFirst("year");
256 PathSegment model = info.getPathSegments().get(3);
257 String color = model.getMatrixParameters().getFirst("color");
258
259 return "A " + color + " " + year + " " + make + " " + model.getPath();
260 }
261
262 @GET
263 @Path("/concat/{model: \\D+}{year: \\d+}")
264 @Produces("text/plain")
265 public String getConcatenatedSegment(@Context UriInfo info,
266 @PathParam("model") String model, @PathParam("year") String year) {
267 String make = info.getPathParameters().getFirst("make");
268 String color = info.getQueryParameters().get("color").get(0);
269 return "A " + color + " " + year + " " + make + " " + model;
270 }
271
272 @GET
273 @Path("/concat2/{model: \\$\\D+}{year: \\d+}")
274 @Produces("text/plain")
275 public String getConcatenated2Segment(@Context UriInfo info,
276 @PathParam("model") String model, @PathParam("year") String year) {
277 String make = info.getPathParameters().getFirst("make");
278 String color = info.getQueryParameters().get("color").get(0);
279 return "A " + color + " " + year + " " + make + " " + model;
280 }
281
282 @GET
283 @Path("/concat3/{model: [\\$]glk}")
284 @Produces("text/plain")
285 public String getConcatenated3Segment(@Context UriInfo info,
286 @PathParam("model") String model) {
287 String make = info.getPathParameters().getFirst("make");
288 String color = info.getQueryParameters().get("color").get(0);
289 return "A " + color + " " + make + " " + model;
290 }
291
292 @GET
293 @Path("/group/{model: [^/()]+?}{ignore: (?:\\(\\))?}")
294 @Produces("text/plain")
295 public String getGroupSegment(@Context UriInfo info,
296 @PathParam("model") String model) {
297 String make = info.getPathParameters().getFirst("make");
298 String color = info.getQueryParameters().get("color").get(0);
299 return "A " + color + " " + make + " " + model;
300 }
301 }
302
303 @Test
304 public void testCarResource() throws Exception
305 {
306
307 System.out.println("**** Via @MatrixParam ***");
308 ClientRequest get = new ClientRequest(TestPortProvider.generateURL("/cars/mercedes/matrixparam/e55;color=black/2006"));
309 ClientResponse<String> response = get.get(String.class);
310 Assert.assertEquals(200, response.getStatus());
311 Assert.assertEquals("A black 2006 mercedes e55", response.getEntity());
312 // This must be a typo. Should be "A midnight blue 2006 Porsche 911 Carrera S".
313
314 System.out.println("**** Via PathSegment ***");
315 get = new ClientRequest(TestPortProvider.generateURL("/cars/mercedes/pathsegment/e55;color=black/2006"));
316 response = get.get(String.class);
317 Assert.assertEquals(200, response.getStatus());
318 Assert.assertEquals("A black 2006 mercedes e55", response.getEntity());
319
320 System.out.println("**** Via PathSegments ***");
321 get = new ClientRequest(TestPortProvider.generateURL("/cars/mercedes/pathsegments/e55/amg/year/2006"));
322 response = get.get(String.class);
323 Assert.assertEquals(200, response.getStatus());
324 Assert.assertEquals("A 2006 mercedes e55 amg", response.getEntity());
325
326 System.out.println("**** Via PathSegment ***");
327 get = new ClientRequest(TestPortProvider.generateURL("/cars/mercedes/uriinfo/e55;color=black/2006"));
328 response = get.get(String.class);
329 Assert.assertEquals(200, response.getStatus());
330 Assert.assertEquals("A black 2006 mercedes e55", response.getEntity());
331
332 System.out.println("**** Via Concatenated plain***");
333 get = new ClientRequest(TestPortProvider.generateURL("/cars/mercedes/concat/mlk2006?color=black"));
334 response = get.get(String.class);
335 Assert.assertEquals(200, response.getStatus());
336 Assert.assertEquals("A black 2006 mercedes mlk", response.getEntity());
337
338 System.out.println("**** Via Concatenated with regex character***");
339 get = new ClientRequest(TestPortProvider.generateURL("/cars/mercedes/concat2/$mlk2006?color=black"));
340 response = get.get(String.class);
341 Assert.assertEquals(200, response.getStatus());
342 Assert.assertEquals("A black 2006 mercedes $mlk", response.getEntity());
343
344 System.out.println("**** Via Concatenated with regex character with $ ***");
345 get = new ClientRequest(TestPortProvider.generateURL("/cars/mercedes/concat3/$glk?color=black"));
346 response = get.get(String.class);
347 Assert.assertEquals(200, response.getStatus());
348 Assert.assertEquals("A black mercedes $glk", response.getEntity());
349
350 System.out.println("**** Via grouping chars in regex ***");
351 get = new ClientRequest(TestPortProvider.generateURL("/cars/mercedes/group/glk()?color=black"));
352 response = get.get(String.class);
353 Assert.assertEquals(200, response.getStatus());
354 Assert.assertEquals("A black mercedes glk", response.getEntity());
355 }
356
357
358 }
0 package org.jboss.resteasy.test.finegrain.methodparams;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.client.ProxyFactory;
5 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
6 import org.jboss.resteasy.core.Dispatcher;
7 import org.jboss.resteasy.test.EmbeddedContainer;
8 import org.jboss.resteasy.util.HttpHeaderNames;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.junit.AfterClass;
11 import org.junit.Assert;
12 import org.junit.BeforeClass;
13 import org.junit.Test;
14
15 import javax.ws.rs.DefaultValue;
16 import javax.ws.rs.GET;
17 import javax.ws.rs.Path;
18 import javax.ws.rs.Produces;
19 import javax.ws.rs.QueryParam;
20 import java.util.ArrayList;
21 import java.util.List;
22
23 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
24 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
25 import static org.jboss.resteasy.util.HttpClient4xUtils.updateQuery;
26
27 /**
28 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
29 * @version $Revision: 1 $
30 */
31 public class QueryParamAsPrimitiveTest
32 {
33 private static final float ASSERT_FLOAT_THRESHOLD = 0.000000001f;
34 private static final double ASSERT_DOUBLE_THRESHOLD = 0.000000000000001d;
35
36 private static Dispatcher dispatcher;
37
38 private static IResourceQueryPrimitives resourceQueryPrimitives;
39
40 private static IResourceQueryPrimitiveWrappers resourceQueryPrimitiveWrappers;
41
42 private static IResourceQueryPrimitiveList resourceQueryPrimitiveList;
43
44 private static IResourceQueryPrimitiveArray resourceQueryPrimitiveArray;
45
46 @BeforeClass
47 public static void before() throws Exception
48 {
49 dispatcher = EmbeddedContainer.start().getDispatcher();
50 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitives.class);
51 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitivesDefault.class);
52 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitivesDefaultOverride.class);
53 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitivesDefaultNull.class);
54 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveWrappers.class);
55 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveWrappersDefault.class);
56 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveWrappersDefaultNull.class);
57 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveWrappersDefaultOverride.class);
58 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveList.class);
59 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveListDefault.class);
60 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveListDefaultNull.class);
61 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveListDefaultOverride.class);
62 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveArray.class);
63 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveArrayDefault.class);
64 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveArrayDefaultNull.class);
65 dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveArrayDefaultOverride.class);
66 resourceQueryPrimitives = ProxyFactory.create(IResourceQueryPrimitives.class, generateBaseUrl());
67 resourceQueryPrimitiveWrappers = ProxyFactory.create(IResourceQueryPrimitiveWrappers.class,
68 generateBaseUrl());
69 resourceQueryPrimitiveList = ProxyFactory.create(IResourceQueryPrimitiveList.class, generateBaseUrl());
70 resourceQueryPrimitiveArray = ProxyFactory.create(IResourceQueryPrimitiveArray.class, generateBaseUrl());
71 }
72
73 @AfterClass
74 public static void after() throws Exception
75 {
76 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitives.class);
77 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitivesDefault.class);
78 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitivesDefaultOverride.class);
79 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitivesDefaultNull.class);
80 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveWrappers.class);
81 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveWrappersDefault.class);
82 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveWrappersDefaultNull.class);
83 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveWrappersDefaultOverride.class);
84 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveList.class);
85 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveListDefault.class);
86 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveListDefaultNull.class);
87 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveListDefaultOverride.class);
88 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveArray.class);
89 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveArrayDefault.class);
90 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveArrayDefaultNull.class);
91 dispatcher.getRegistry().removeRegistrations(ResourceQueryPrimitiveArrayDefaultOverride.class);
92 EmbeddedContainer.stop();
93 }
94
95 @Path("/")
96 public static class ResourceQueryPrimitives implements IResourceQueryPrimitives
97 {
98 @GET
99 @Produces("application/boolean")
100 public String doGet(@QueryParam("boolean") boolean v)
101 {
102 Assert.assertEquals(true, v);
103 return "content";
104 }
105
106 @GET
107 @Produces("application/byte")
108 public String doGet(@QueryParam("byte") byte v)
109 {
110 Assert.assertTrue((byte) 127 == v);
111 return "content";
112 }
113
114 @GET
115 @Produces("application/short")
116 public String doGet(@QueryParam("short") short v)
117 {
118 Assert.assertTrue((short) 32767 == v);
119 return "content";
120 }
121
122 @GET
123 @Produces("application/int")
124 public String doGet(@QueryParam("int") int v)
125 {
126 Assert.assertEquals(2147483647, v);
127 return "content";
128 }
129
130 @GET
131 @Produces("application/long")
132 public String doGet(@QueryParam("long") long v)
133 {
134 Assert.assertEquals(9223372036854775807L, v);
135 return "content";
136 }
137
138 @GET
139 @Produces("application/float")
140 public String doGet(@QueryParam("float") float v)
141 {
142 Assert.assertEquals(3.14159265f, v, ASSERT_FLOAT_THRESHOLD);
143 return "content";
144 }
145
146 @GET
147 @Produces("application/double")
148 public String doGet(@QueryParam("double") double v)
149 {
150 Assert.assertEquals(3.14159265358979d, v, ASSERT_DOUBLE_THRESHOLD);
151 return "content";
152 }
153 }
154
155 @Path("/default/null")
156 public static class ResourceQueryPrimitivesDefaultNull
157 {
158 @GET
159 @Produces("application/boolean")
160 public String doGet(@QueryParam("boolean") boolean v)
161 {
162 Assert.assertEquals(false, v);
163 return "content";
164 }
165
166 @GET
167 @Produces("application/byte")
168 public String doGet(@QueryParam("byte") byte v)
169 {
170 Assert.assertTrue(0 == v);
171 return "content";
172 }
173
174 @GET
175 @Produces("application/short")
176 public String doGet(@QueryParam("short") short v)
177 {
178 Assert.assertTrue(0 == v);
179 return "content";
180 }
181
182 @GET
183 @Produces("application/int")
184 public String doGet(@QueryParam("int") int v)
185 {
186 Assert.assertEquals(0, v);
187 return "content";
188 }
189
190 @GET
191 @Produces("application/long")
192 public String doGet(@QueryParam("long") long v)
193 {
194 Assert.assertEquals(0l, v);
195 return "content";
196 }
197
198 @GET
199 @Produces("application/float")
200 public String doGet(@QueryParam("float") float v)
201 {
202 Assert.assertEquals(0.0f, v, ASSERT_FLOAT_THRESHOLD);
203 return "content";
204 }
205
206 @GET
207 @Produces("application/double")
208 public String doGet(@QueryParam("double") double v)
209 {
210 Assert.assertEquals(0.0d, v, ASSERT_DOUBLE_THRESHOLD);
211 return "content";
212 }
213 }
214
215 @Path("/default")
216 public static class ResourceQueryPrimitivesDefault
217 {
218 @GET
219 @Produces("application/boolean")
220 public String doGet(@QueryParam("boolean") @DefaultValue("true") boolean v)
221 {
222 Assert.assertEquals(true, v);
223 return "content";
224 }
225
226 @GET
227 @Produces("application/byte")
228 public String doGet(@QueryParam("byte") @DefaultValue("127") byte v)
229 {
230 Assert.assertTrue((byte) 127 == v);
231 return "content";
232 }
233
234 @GET
235 @Produces("application/short")
236 public String doGet(@QueryParam("short") @DefaultValue("32767") short v)
237 {
238 Assert.assertTrue((short) 32767 == v);
239 return "content";
240 }
241
242 @GET
243 @Produces("application/int")
244 public String doGet(@QueryParam("int") @DefaultValue("2147483647") int v)
245 {
246 Assert.assertEquals(2147483647, v);
247 return "content";
248 }
249
250 @GET
251 @Produces("application/long")
252 public String doGet(@QueryParam("long") @DefaultValue("9223372036854775807") long v)
253 {
254 Assert.assertEquals(9223372036854775807L, v);
255 return "content";
256 }
257
258 @GET
259 @Produces("application/float")
260 public String doGet(@QueryParam("float") @DefaultValue("3.14159265") float v)
261 {
262 Assert.assertEquals(3.14159265f, v, ASSERT_FLOAT_THRESHOLD);
263 return "content";
264 }
265
266 @GET
267 @Produces("application/double")
268 public String doGet(@QueryParam("double") @DefaultValue("3.14159265358979") double v)
269 {
270 Assert.assertEquals(3.14159265358979d, v, ASSERT_DOUBLE_THRESHOLD);
271 return "content";
272 }
273 }
274
275 @Path("/default/override")
276 public static class ResourceQueryPrimitivesDefaultOverride
277 {
278 @GET
279 @Produces("application/boolean")
280 public String doGet(@QueryParam("boolean") @DefaultValue("false") boolean v)
281 {
282 Assert.assertEquals(true, v);
283 return "content";
284 }
285
286 @GET
287 @Produces("application/byte")
288 public String doGet(@QueryParam("byte") @DefaultValue("1") byte v)
289 {
290 Assert.assertTrue((byte) 127 == v);
291 return "content";
292 }
293
294 @GET
295 @Produces("application/short")
296 public String doGet(@QueryParam("short") @DefaultValue("1") short v)
297 {
298 Assert.assertTrue((short) 32767 == v);
299 return "content";
300 }
301
302 @GET
303 @Produces("application/int")
304 public String doGet(@QueryParam("int") @DefaultValue("1") int v)
305 {
306 Assert.assertEquals(2147483647, v);
307 return "content";
308 }
309
310 @GET
311 @Produces("application/long")
312 public String doGet(@QueryParam("long") @DefaultValue("1") long v)
313 {
314 Assert.assertEquals(9223372036854775807L, v);
315 return "content";
316 }
317
318 @GET
319 @Produces("application/float")
320 public String doGet(@QueryParam("float") @DefaultValue("0.0") float v)
321 {
322 Assert.assertEquals(3.14159265f, v, ASSERT_FLOAT_THRESHOLD);
323 return "content";
324 }
325
326 @GET
327 @Produces("application/double")
328 public String doGet(@QueryParam("double") @DefaultValue("0.0") double v)
329 {
330 Assert.assertEquals(3.14159265358979d, v, ASSERT_DOUBLE_THRESHOLD);
331 return "content";
332 }
333 }
334
335 @Path("/wrappers")
336 public static class ResourceQueryPrimitiveWrappers implements IResourceQueryPrimitiveWrappers
337 {
338 @GET
339 @Produces("application/boolean")
340 public String doGet(@QueryParam("boolean") Boolean v)
341 {
342 Assert.assertEquals(true, v.booleanValue());
343 return "content";
344 }
345
346 @GET
347 @Produces("application/byte")
348 public String doGet(@QueryParam("byte") Byte v)
349 {
350 Assert.assertTrue((byte) 127 == v.byteValue());
351 return "content";
352 }
353
354 @GET
355 @Produces("application/short")
356 public String doGet(@QueryParam("short") Short v)
357 {
358 Assert.assertTrue((short) 32767 == v.shortValue());
359 return "content";
360 }
361
362 @GET
363 @Produces("application/int")
364 public String doGet(@QueryParam("int") Integer v)
365 {
366 Assert.assertEquals(2147483647, v.intValue());
367 return "content";
368 }
369
370 @GET
371 @Produces("application/long")
372 public String doGet(@QueryParam("long") Long v)
373 {
374 Assert.assertEquals(9223372036854775807L, v.longValue());
375 return "content";
376 }
377
378 @GET
379 @Produces("application/float")
380 public String doGet(@QueryParam("float") Float v)
381 {
382 Assert.assertEquals(3.14159265f, v.floatValue(), ASSERT_FLOAT_THRESHOLD);
383 return "content";
384 }
385
386 @GET
387 @Produces("application/double")
388 public String doGet(@QueryParam("double") Double v)
389 {
390 Assert.assertEquals(3.14159265358979d, v.doubleValue(), ASSERT_DOUBLE_THRESHOLD);
391 return "content";
392 }
393 }
394
395 @Path("/wrappers/default/null")
396 public static class ResourceQueryPrimitiveWrappersDefaultNull
397 {
398 @GET
399 @Produces("application/boolean")
400 public String doGet(@QueryParam("boolean") Boolean v)
401 {
402 Assert.assertEquals(null, v);
403 return "content";
404 }
405
406 @GET
407 @Produces("application/byte")
408 public String doGet(@QueryParam("byte") Byte v)
409 {
410 Assert.assertEquals(null, v);
411 return "content";
412 }
413
414 @GET
415 @Produces("application/short")
416 public String doGet(@QueryParam("short") Short v)
417 {
418 Assert.assertEquals(null, v);
419 return "content";
420 }
421
422 @GET
423 @Produces("application/int")
424 public String doGet(@QueryParam("int") Integer v)
425 {
426 Assert.assertEquals(null, v);
427 return "content";
428 }
429
430 @GET
431 @Produces("application/long")
432 public String doGet(@QueryParam("long") Long v)
433 {
434 Assert.assertEquals(null, v);
435 return "content";
436 }
437
438 @GET
439 @Produces("application/float")
440 public String doGet(@QueryParam("float") Float v)
441 {
442 Assert.assertEquals(null, v);
443 return "content";
444 }
445
446 @GET
447 @Produces("application/double")
448 public String doGet(@QueryParam("double") Double v)
449 {
450 Assert.assertEquals(null, v);
451 return "content";
452 }
453 }
454
455 @Path("/wrappers/default")
456 public static class ResourceQueryPrimitiveWrappersDefault
457 {
458 @GET
459 @Produces("application/boolean")
460 public String doGet(@QueryParam("boolean") @DefaultValue("true") Boolean v)
461 {
462 Assert.assertEquals(true, v.booleanValue());
463 return "content";
464 }
465
466 @GET
467 @Produces("application/byte")
468 public String doGet(@QueryParam("byte") @DefaultValue("127") Byte v)
469 {
470 Assert.assertTrue((byte) 127 == v.byteValue());
471 return "content";
472 }
473
474 @GET
475 @Produces("application/short")
476 public String doGet(@QueryParam("short") @DefaultValue("32767") Short v)
477 {
478 Assert.assertTrue((short) 32767 == v.shortValue());
479 return "content";
480 }
481
482 @GET
483 @Produces("application/int")
484 public String doGet(@QueryParam("int") @DefaultValue("2147483647") Integer v)
485 {
486 Assert.assertEquals(2147483647, v.intValue());
487 return "content";
488 }
489
490 @GET
491 @Produces("application/long")
492 public String doGet(@QueryParam("long") @DefaultValue("9223372036854775807") Long v)
493 {
494 Assert.assertEquals(9223372036854775807L, v.longValue());
495 return "content";
496 }
497
498 @GET
499 @Produces("application/float")
500 public String doGet(@QueryParam("float") @DefaultValue("3.14159265") Float v)
501 {
502 Assert.assertEquals(3.14159265f, v.floatValue(), ASSERT_FLOAT_THRESHOLD);
503 return "content";
504 }
505
506 @GET
507 @Produces("application/double")
508 public String doGet(@QueryParam("double") @DefaultValue("3.14159265358979") Double v)
509 {
510 Assert.assertEquals(3.14159265358979d, v.doubleValue(), ASSERT_DOUBLE_THRESHOLD);
511 return "content";
512 }
513 }
514
515 @Path("/wrappers/default/override")
516 public static class ResourceQueryPrimitiveWrappersDefaultOverride
517 {
518 @GET
519 @Produces("application/boolean")
520 public String doGet(@QueryParam("boolean") @DefaultValue("false") Boolean v)
521 {
522 Assert.assertEquals(true, v.booleanValue());
523 return "content";
524 }
525
526 @GET
527 @Produces("application/byte")
528 public String doGet(@QueryParam("byte") @DefaultValue("1") Byte v)
529 {
530 Assert.assertTrue((byte) 127 == v.byteValue());
531 return "content";
532 }
533
534 @GET
535 @Produces("application/short")
536 public String doGet(@QueryParam("short") @DefaultValue("1") Short v)
537 {
538 Assert.assertTrue((short) 32767 == v.shortValue());
539 return "content";
540 }
541
542 @GET
543 @Produces("application/int")
544 public String doGet(@QueryParam("int") @DefaultValue("1") Integer v)
545 {
546 Assert.assertEquals(2147483647, v.intValue());
547 return "content";
548 }
549
550 @GET
551 @Produces("application/long")
552 public String doGet(@QueryParam("long") @DefaultValue("1") Long v)
553 {
554 Assert.assertEquals(9223372036854775807L, v.longValue());
555 return "content";
556 }
557
558 @GET
559 @Produces("application/float")
560 public String doGet(@QueryParam("float") @DefaultValue("0.0") Float v)
561 {
562 Assert.assertEquals(3.14159265f, v.floatValue(), ASSERT_FLOAT_THRESHOLD);
563 return "content";
564 }
565
566 @GET
567 @Produces("application/double")
568 public String doGet(@QueryParam("double") @DefaultValue("0.0") Double v)
569 {
570 Assert.assertEquals(3.14159265358979d, v.doubleValue(), ASSERT_DOUBLE_THRESHOLD);
571 return "content";
572 }
573 }
574
575 @Path("/list")
576 public static class ResourceQueryPrimitiveList implements IResourceQueryPrimitiveList
577 {
578 @GET
579 @Produces("application/boolean")
580 public String doGetBoolean(@QueryParam("boolean") List<Boolean> v)
581 {
582 Assert.assertEquals(true, v.get(0).booleanValue());
583 Assert.assertEquals(true, v.get(1).booleanValue());
584 Assert.assertEquals(true, v.get(2).booleanValue());
585 return "content";
586 }
587
588 @GET
589 @Produces("application/byte")
590 public String doGetByte(@QueryParam("byte") List<Byte> v)
591 {
592 Assert.assertTrue((byte) 127 == v.get(0).byteValue());
593 Assert.assertTrue((byte) 127 == v.get(1).byteValue());
594 Assert.assertTrue((byte) 127 == v.get(2).byteValue());
595 return "content";
596 }
597
598 @GET
599 @Produces("application/short")
600 public String doGetShort(@QueryParam("short") List<Short> v)
601 {
602 Assert.assertTrue((short) 32767 == v.get(0).shortValue());
603 Assert.assertTrue((short) 32767 == v.get(1).shortValue());
604 Assert.assertTrue((short) 32767 == v.get(2).shortValue());
605 return "content";
606 }
607
608 @GET
609 @Produces("application/int")
610 public String doGetInteger(@QueryParam("int") List<Integer> v)
611 {
612 Assert.assertEquals(2147483647, v.get(0).intValue());
613 Assert.assertEquals(2147483647, v.get(1).intValue());
614 Assert.assertEquals(2147483647, v.get(2).intValue());
615 return "content";
616 }
617
618 @GET
619 @Produces("application/long")
620 public String doGetLong(@QueryParam("long") List<Long> v)
621 {
622 Assert.assertEquals(9223372036854775807L, v.get(0).longValue());
623 Assert.assertEquals(9223372036854775807L, v.get(1).longValue());
624 Assert.assertEquals(9223372036854775807L, v.get(2).longValue());
625 return "content";
626 }
627
628 @GET
629 @Produces("application/float")
630 public String doGetFloat(@QueryParam("float") List<Float> v)
631 {
632 Assert.assertEquals(3.14159265f, v.get(0).floatValue(), ASSERT_FLOAT_THRESHOLD);
633 Assert.assertEquals(3.14159265f, v.get(1).floatValue(), ASSERT_FLOAT_THRESHOLD);
634 Assert.assertEquals(3.14159265f, v.get(2).floatValue(), ASSERT_FLOAT_THRESHOLD);
635 return "content";
636 }
637
638 @GET
639 @Produces("application/double")
640 public String doGetDouble(@QueryParam("double") List<Double> v)
641 {
642 Assert.assertEquals(3.14159265358979d, v.get(0).doubleValue(), ASSERT_DOUBLE_THRESHOLD);
643 Assert.assertEquals(3.14159265358979d, v.get(1).doubleValue(), ASSERT_DOUBLE_THRESHOLD);
644 Assert.assertEquals(3.14159265358979d, v.get(2).doubleValue(), ASSERT_DOUBLE_THRESHOLD);
645 return "content";
646 }
647 }
648
649 @Path("/list/default/null")
650 public static class ResourceQueryPrimitiveListDefaultNull
651 {
652 @GET
653 @Produces("application/boolean")
654 public String doGetBoolean(@QueryParam("boolean") List<Boolean> v)
655 {
656 Assert.assertEquals(0, v.size());
657 return "content";
658 }
659
660 @GET
661 @Produces("application/byte")
662 public String doGetByte(@QueryParam("byte") List<Byte> v)
663 {
664 Assert.assertEquals(0, v.size());
665 return "content";
666 }
667
668 @GET
669 @Produces("application/short")
670 public String doGetShort(@QueryParam("short") List<Short> v)
671 {
672 Assert.assertEquals(0, v.size());
673 return "content";
674 }
675
676 @GET
677 @Produces("application/int")
678 public String doGetInteger(@QueryParam("int") List<Integer> v)
679 {
680 Assert.assertEquals(0, v.size());
681 return "content";
682 }
683
684 @GET
685 @Produces("application/long")
686 public String doGetLong(@QueryParam("long") List<Long> v)
687 {
688 Assert.assertEquals(0, v.size());
689 return "content";
690 }
691
692 @GET
693 @Produces("application/float")
694 public String doGetFloat(@QueryParam("float") List<Float> v)
695 {
696 Assert.assertEquals(0, v.size());
697 return "content";
698 }
699
700 @GET
701 @Produces("application/double")
702 public String doGetDouble(@QueryParam("double") List<Double> v)
703 {
704 Assert.assertEquals(0, v.size());
705 return "content";
706 }
707 }
708
709 @Path("/list/default")
710 public static class ResourceQueryPrimitiveListDefault
711 {
712 @GET
713 @Produces("application/boolean")
714 public String doGetBoolean(@QueryParam("boolean") @DefaultValue("true") List<Boolean> v)
715 {
716 Assert.assertEquals(true, v.get(0).booleanValue());
717 return "content";
718 }
719
720 @GET
721 @Produces("application/byte")
722 public String doGetByte(@QueryParam("byte") @DefaultValue("127") List<Byte> v)
723 {
724 Assert.assertTrue((byte) 127 == v.get(0).byteValue());
725 return "content";
726 }
727
728 @GET
729 @Produces("application/short")
730 public String doGetShort(@QueryParam("short") @DefaultValue("32767") List<Short> v)
731 {
732 Assert.assertTrue((short) 32767 == v.get(0).shortValue());
733 return "content";
734 }
735
736 @GET
737 @Produces("application/int")
738 public String doGetInteger(@QueryParam("int") @DefaultValue("2147483647") List<Integer> v)
739 {
740 Assert.assertEquals(2147483647, v.get(0).intValue());
741 return "content";
742 }
743
744 @GET
745 @Produces("application/long")
746 public String doGetLong(@QueryParam("long") @DefaultValue("9223372036854775807") List<Long> v)
747 {
748 Assert.assertEquals(9223372036854775807L, v.get(0).longValue());
749 return "content";
750 }
751
752 @GET
753 @Produces("application/float")
754 public String doGetFloat(@QueryParam("float") @DefaultValue("3.14159265") List<Float> v)
755 {
756 Assert.assertEquals(3.14159265f, v.get(0).floatValue(), ASSERT_FLOAT_THRESHOLD);
757 return "content";
758 }
759
760 @GET
761 @Produces("application/double")
762 public String doGetDouble(@QueryParam("double") @DefaultValue("3.14159265358979") List<Double> v)
763 {
764 Assert.assertEquals(3.14159265358979d, v.get(0).doubleValue(), ASSERT_DOUBLE_THRESHOLD);
765 return "content";
766 }
767 }
768
769 @Path("/list/default/override")
770 public static class ResourceQueryPrimitiveListDefaultOverride
771 {
772 @GET
773 @Produces("application/boolean")
774 public String doGetBoolean(@QueryParam("boolean") @DefaultValue("false") List<Boolean> v)
775 {
776 Assert.assertEquals(true, v.get(0).booleanValue());
777 return "content";
778 }
779
780 @GET
781 @Produces("application/byte")
782 public String doGetByte(@QueryParam("byte") @DefaultValue("0") List<Byte> v)
783 {
784 Assert.assertTrue((byte) 127 == v.get(0).byteValue());
785 return "content";
786 }
787
788 @GET
789 @Produces("application/short")
790 public String doGetShort(@QueryParam("short") @DefaultValue("0") List<Short> v)
791 {
792 Assert.assertTrue((short) 32767 == v.get(0).shortValue());
793 return "content";
794 }
795
796 @GET
797 @Produces("application/int")
798 public String doGetInteger(@QueryParam("int") @DefaultValue("0") List<Integer> v)
799 {
800 Assert.assertEquals(2147483647, v.get(0).intValue());
801 return "content";
802 }
803
804 @GET
805 @Produces("application/long")
806 public String doGetLong(@QueryParam("long") @DefaultValue("0") List<Long> v)
807 {
808 Assert.assertEquals(9223372036854775807L, v.get(0).longValue());
809 return "content";
810 }
811
812 @GET
813 @Produces("application/float")
814 public String doGetFloat(@QueryParam("float") @DefaultValue("0.0") List<Float> v)
815 {
816 Assert.assertEquals(3.14159265f, v.get(0).floatValue(), ASSERT_FLOAT_THRESHOLD);
817 return "content";
818 }
819
820 @GET
821 @Produces("application/double")
822 public String doGetDouble(@QueryParam("double") @DefaultValue("0.0") List<Double> v)
823 {
824 Assert.assertEquals(3.14159265358979d, v.get(0).doubleValue(), ASSERT_DOUBLE_THRESHOLD);
825 return "content";
826 }
827 }
828
829 @Path("/array")
830 public static class ResourceQueryPrimitiveArray implements IResourceQueryPrimitiveArray
831 {
832 @GET
833 @Produces("application/boolean")
834 public String doGetBoolean(@QueryParam("boolean") boolean[] v)
835 {
836 Assert.assertEquals(true, v[0]);
837 Assert.assertEquals(true, v[1]);
838 Assert.assertEquals(true, v[2]);
839 return "content";
840 }
841
842 @GET
843 @Produces("application/byte")
844 public String doGetByte(@QueryParam("byte") byte[] v)
845 {
846 Assert.assertTrue((byte) 127 == v[0]);
847 Assert.assertTrue((byte) 127 == v[1]);
848 Assert.assertTrue((byte) 127 == v[2]);
849 return "content";
850 }
851
852 @GET
853 @Produces("application/short")
854 public String doGetShort(@QueryParam("short") short[] v)
855 {
856 Assert.assertTrue((short) 32767 == v[0]);
857 Assert.assertTrue((short) 32767 == v[1]);
858 Assert.assertTrue((short) 32767 == v[2]);
859 return "content";
860 }
861
862 @GET
863 @Produces("application/int")
864 public String doGetInteger(@QueryParam("int") int[] v)
865 {
866 Assert.assertEquals(2147483647, v[0]);
867 Assert.assertEquals(2147483647, v[1]);
868 Assert.assertEquals(2147483647, v[2]);
869 return "content";
870 }
871
872 @GET
873 @Produces("application/long")
874 public String doGetLong(@QueryParam("long") long[] v)
875 {
876 Assert.assertEquals(9223372036854775807L, v[0]);
877 Assert.assertEquals(9223372036854775807L, v[1]);
878 Assert.assertEquals(9223372036854775807L, v[2]);
879 return "content";
880 }
881
882 @GET
883 @Produces("application/float")
884 public String doGetFloat(@QueryParam("float") float[] v)
885 {
886 Assert.assertEquals(3.14159265f, v[0], ASSERT_FLOAT_THRESHOLD);
887 Assert.assertEquals(3.14159265f, v[1], ASSERT_FLOAT_THRESHOLD);
888 Assert.assertEquals(3.14159265f, v[2], ASSERT_FLOAT_THRESHOLD);
889 return "content";
890 }
891
892 @GET
893 @Produces("application/double")
894 public String doGetDouble(@QueryParam("double") double[] v)
895 {
896 Assert.assertEquals(3.14159265358979d, v[0], ASSERT_DOUBLE_THRESHOLD);
897 Assert.assertEquals(3.14159265358979d, v[1], ASSERT_DOUBLE_THRESHOLD);
898 Assert.assertEquals(3.14159265358979d, v[2], ASSERT_DOUBLE_THRESHOLD);
899 return "content";
900 }
901 }
902
903 @Path("/array/default/null")
904 public static class ResourceQueryPrimitiveArrayDefaultNull
905 {
906 @GET
907 @Produces("application/boolean")
908 public String doGetBoolean(@QueryParam("boolean") boolean[] v)
909 {
910 Assert.assertEquals(0, v.length);
911 return "content";
912 }
913
914 @GET
915 @Produces("application/byte")
916 public String doGetByte(@QueryParam("byte") byte[] v)
917 {
918 Assert.assertEquals(0, v.length);
919 return "content";
920 }
921
922 @GET
923 @Produces("application/short")
924 public String doGetShort(@QueryParam("short") short[] v)
925 {
926 Assert.assertEquals(0, v.length);
927 return "content";
928 }
929
930 @GET
931 @Produces("application/int")
932 public String doGetInteger(@QueryParam("int") int[] v)
933 {
934 Assert.assertEquals(0, v.length);
935 return "content";
936 }
937
938 @GET
939 @Produces("application/long")
940 public String doGetLong(@QueryParam("long") long[] v)
941 {
942 Assert.assertEquals(0, v.length);
943 return "content";
944 }
945
946 @GET
947 @Produces("application/float")
948 public String doGetFloat(@QueryParam("float") float[] v)
949 {
950 Assert.assertEquals(0, v.length);
951 return "content";
952 }
953
954 @GET
955 @Produces("application/double")
956 public String doGetDouble(@QueryParam("double") double[] v)
957 {
958 Assert.assertEquals(0, v.length);
959 return "content";
960 }
961 }
962
963 @Path("/array/default")
964 public static class ResourceQueryPrimitiveArrayDefault
965 {
966 @GET
967 @Produces("application/boolean")
968 public String doGetBoolean(@QueryParam("boolean") @DefaultValue("true") boolean[] v)
969 {
970 Assert.assertEquals(true, v[0]);
971 return "content";
972 }
973
974 @GET
975 @Produces("application/byte")
976 public String doGetByte(@QueryParam("byte") @DefaultValue("127") byte[] v)
977 {
978 Assert.assertTrue((byte) 127 == v[0]);
979 return "content";
980 }
981
982 @GET
983 @Produces("application/short")
984 public String doGetShort(@QueryParam("short") @DefaultValue("32767") short[] v)
985 {
986 Assert.assertTrue((short) 32767 == v[0]);
987 return "content";
988 }
989
990 @GET
991 @Produces("application/int")
992 public String doGetInteger(@QueryParam("int") @DefaultValue("2147483647") int[] v)
993 {
994 Assert.assertEquals(2147483647, v[0]);
995 return "content";
996 }
997
998 @GET
999 @Produces("application/long")
1000 public String doGetLong(@QueryParam("long") @DefaultValue("9223372036854775807") long[] v)
1001 {
1002 Assert.assertEquals(9223372036854775807L, v[0]);
1003 return "content";
1004 }
1005
1006 @GET
1007 @Produces("application/float")
1008 public String doGetFloat(@QueryParam("float") @DefaultValue("3.14159265") float[] v)
1009 {
1010 Assert.assertEquals(3.14159265f, v[0], ASSERT_FLOAT_THRESHOLD);
1011 return "content";
1012 }
1013
1014 @GET
1015 @Produces("application/double")
1016 public String doGetDouble(@QueryParam("double") @DefaultValue("3.14159265358979") double[] v)
1017 {
1018 Assert.assertEquals(3.14159265358979d, v[0], ASSERT_DOUBLE_THRESHOLD);
1019 return "content";
1020 }
1021 }
1022
1023 @Path("/array/default/override")
1024 public static class ResourceQueryPrimitiveArrayDefaultOverride
1025 {
1026 @GET
1027 @Produces("application/boolean")
1028 public String doGetBoolean(@QueryParam("boolean") @DefaultValue("false") boolean[] v)
1029 {
1030 Assert.assertEquals(true, v[0]);
1031 return "content";
1032 }
1033
1034 @GET
1035 @Produces("application/byte")
1036 public String doGetByte(@QueryParam("byte") @DefaultValue("0") byte[] v)
1037 {
1038 Assert.assertTrue((byte) 127 == v[0]);
1039 return "content";
1040 }
1041
1042 @GET
1043 @Produces("application/short")
1044 public String doGetShort(@QueryParam("short") @DefaultValue("0") short[] v)
1045 {
1046 Assert.assertTrue((short) 32767 == v[0]);
1047 return "content";
1048 }
1049
1050 @GET
1051 @Produces("application/int")
1052 public String doGetInteger(@QueryParam("int") @DefaultValue("0") int[] v)
1053 {
1054 Assert.assertEquals(2147483647, v[0]);
1055 return "content";
1056 }
1057
1058 @GET
1059 @Produces("application/long")
1060 public String doGetLong(@QueryParam("long") @DefaultValue("0") long[] v)
1061 {
1062 Assert.assertEquals(9223372036854775807L, v[0]);
1063 return "content";
1064 }
1065
1066 @GET
1067 @Produces("application/float")
1068 public String doGetFloat(@QueryParam("float") @DefaultValue("0.0") float[] v)
1069 {
1070 Assert.assertEquals(3.14159265f, v[0], ASSERT_FLOAT_THRESHOLD);
1071 return "content";
1072 }
1073
1074 @GET
1075 @Produces("application/double")
1076 public String doGetDouble(@QueryParam("double") @DefaultValue("0.0") double[] v)
1077 {
1078 Assert.assertEquals(3.14159265358979d, v[0], ASSERT_DOUBLE_THRESHOLD);
1079 return "content";
1080 }
1081 }
1082
1083 public void _test(String type, String value)
1084 {
1085 String param = type + "=" + value;
1086
1087 {
1088 String uri = updateQuery(generateURL("/"), param);
1089 ClientRequest request = new ClientRequest(uri);
1090 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
1091 try
1092 {
1093 ClientResponse<?> response = request.get();
1094 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
1095 shutdown(request);
1096 }
1097 catch (Exception e)
1098 {
1099 throw new RuntimeException(e);
1100 }
1101 }
1102
1103 {
1104 String uri = updateQuery(generateURL("/wrappers"), param);
1105 ClientRequest request = new ClientRequest(uri);
1106 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
1107 try
1108 {
1109 ClientResponse<?> response = request.get();
1110 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
1111 shutdown(request);
1112 }
1113 catch (Exception e)
1114 {
1115 throw new RuntimeException(e);
1116 }
1117 }
1118
1119 {
1120 String uri = updateQuery(generateURL("/list"), param + "&" + param + "&" + param);
1121 ClientRequest request = new ClientRequest(uri);
1122 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
1123 try
1124 {
1125 ClientResponse<?> response = request.get();
1126 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
1127 shutdown(request);
1128 }
1129 catch (Exception e)
1130 {
1131 throw new RuntimeException(e);
1132 }
1133 }
1134
1135 {
1136 String uri = updateQuery(generateURL("/array"), param + "&" + param + "&" + param);
1137 ClientRequest request = new ClientRequest(uri);
1138 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
1139 try
1140 {
1141 ClientResponse<?> response = request.get();
1142 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
1143 shutdown(request);
1144 }
1145 catch (Exception e)
1146 {
1147 throw new RuntimeException(e);
1148 }
1149 }
1150 }
1151
1152 public void _testDefault(String base, String type, String value)
1153 {
1154 {
1155 ClientRequest request = new ClientRequest(generateURL("" + base + "default/null"));
1156 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
1157 try
1158 {
1159 ClientResponse<?> response = request.get();
1160 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
1161 shutdown(request);
1162 }
1163 catch (Exception e)
1164 {
1165 throw new RuntimeException(e);
1166 }
1167 }
1168
1169 {
1170 ClientRequest request = new ClientRequest(generateURL("" + base + "default"));
1171 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
1172 try
1173 {
1174 ClientResponse<?> response = request.get();
1175 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
1176 shutdown(request);
1177 }
1178 catch (Exception e)
1179 {
1180 throw new RuntimeException(e);
1181 }
1182 }
1183
1184 String param = type + "=" + value;
1185 {
1186 String uri = updateQuery(generateURL("" + base + "default/override"), param);
1187 ClientRequest request = new ClientRequest(uri);
1188 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
1189 try
1190 {
1191 ClientResponse<?> response = request.get();
1192 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
1193 shutdown(request);
1194 }
1195 catch (Exception e)
1196 {
1197 throw new RuntimeException(e);
1198 }
1199 }
1200 }
1201
1202 public void _testDefault(String type, String value)
1203 {
1204 _testDefault("/", type, value);
1205 }
1206
1207 public void _testWrappersDefault(String type, String value)
1208 {
1209 _testDefault("/wrappers/", type, value);
1210 }
1211
1212 public void _testListDefault(String type, String value)
1213 {
1214 _testDefault("/list/", type, value);
1215 }
1216
1217 public void _testArrayDefault(String type, String value)
1218 {
1219 _testDefault("/array/", type, value);
1220 }
1221
1222 @Test
1223 public void testGetBoolean()
1224 {
1225 _test("boolean", "true");
1226 resourceQueryPrimitives.doGet(true);
1227 resourceQueryPrimitiveWrappers.doGet(true);
1228 List<Boolean> list = new ArrayList<Boolean>();
1229 list.add(Boolean.TRUE);
1230 list.add(Boolean.TRUE);
1231 list.add(Boolean.TRUE);
1232 resourceQueryPrimitiveList.doGetBoolean(list);
1233 boolean[] array =
1234 {true, true, true};
1235 resourceQueryPrimitiveArray.doGetBoolean(array);
1236 }
1237
1238 @Test
1239 public void testGetBooleanPrimitivesDefault()
1240 {
1241 _testDefault("boolean", "true");
1242 }
1243
1244 @Test
1245 public void testGetBooleanPrimitiveWrapperDefault()
1246 {
1247 _testWrappersDefault("boolean", "true");
1248 }
1249
1250 @Test
1251 public void testGetBooleanPrimitiveListDefault()
1252 {
1253 _testListDefault("boolean", "true");
1254 }
1255
1256 @Test
1257 public void testGetBooleanPrimitiveArrayDefault()
1258 {
1259 _testArrayDefault("boolean", "true");
1260 }
1261
1262 @Test
1263 public void testGetByte()
1264 {
1265 _test("byte", "127");
1266 resourceQueryPrimitives.doGet((byte) 127);
1267 resourceQueryPrimitiveWrappers.doGet((byte) 127);
1268 List<Byte> list = new ArrayList<Byte>();
1269 list.add(new Byte((byte) 127));
1270 list.add(new Byte((byte) 127));
1271 list.add(new Byte((byte) 127));
1272 resourceQueryPrimitiveList.doGetByte(list);
1273 byte[] array =
1274 {(byte) 127, (byte) 127, (byte) 127};
1275 resourceQueryPrimitiveArray.doGetByte(array);
1276 }
1277
1278 @Test
1279 public void testGetBytePrimitivesDefault()
1280 {
1281 _testDefault("byte", "127");
1282 }
1283
1284 @Test
1285 public void testGetBytePrimitiveWrappersDefault()
1286 {
1287 _testWrappersDefault("byte", "127");
1288 }
1289
1290 @Test
1291 public void testGetBytePrimitiveListDefault()
1292 {
1293 _testListDefault("byte", "127");
1294 }
1295
1296 @Test
1297 public void testGetBytePrimitiveArrayDefault()
1298 {
1299 _testArrayDefault("byte", "127");
1300 }
1301
1302 @Test
1303 public void testGetShort()
1304 {
1305 _test("short", "32767");
1306 }
1307
1308 @Test
1309 public void testGetShortPrimtivesDefault()
1310 {
1311 _testDefault("short", "32767");
1312 }
1313
1314 @Test
1315 public void testGetShortPrimtiveWrappersDefault()
1316 {
1317 _testWrappersDefault("short", "32767");
1318 }
1319
1320 @Test
1321 public void testGetShortPrimtiveListDefault()
1322 {
1323 _testListDefault("short", "32767");
1324 }
1325
1326 @Test
1327 public void testGetInt()
1328 {
1329 _test("int", "2147483647");
1330 }
1331
1332 @Test
1333 public void testGetIntPrimitivesDefault()
1334 {
1335 _testDefault("int", "2147483647");
1336 }
1337
1338 @Test
1339 public void testGetIntPrimitiveWrappersDefault()
1340 {
1341 _testWrappersDefault("int", "2147483647");
1342 }
1343
1344 @Test
1345 public void testGetIntPrimitiveListDefault()
1346 {
1347 _testListDefault("int", "2147483647");
1348 }
1349
1350 @Test
1351 public void testGetLong()
1352 {
1353 _test("long", "9223372036854775807");
1354 }
1355
1356 @Test
1357 public void testGetLongPrimitivesDefault()
1358 {
1359 _testDefault("long", "9223372036854775807");
1360 }
1361
1362 @Test
1363 public void testGetLongPrimitiveWrappersDefault()
1364 {
1365 _testWrappersDefault("long", "9223372036854775807");
1366 }
1367
1368 @Test
1369 public void testGetLongPrimitiveListDefault()
1370 {
1371 _testListDefault("long", "9223372036854775807");
1372 }
1373
1374 @Test
1375 public void testGetFloat()
1376 {
1377 _test("float", "3.14159265");
1378 }
1379
1380 @Test
1381 public void testGetFloatPrimitivesDefault()
1382 {
1383 _testDefault("float", "3.14159265");
1384 }
1385
1386 @Test
1387 public void testGetFloatPrimitiveWrappersDefault()
1388 {
1389 _testWrappersDefault("float", "3.14159265");
1390 }
1391
1392 @Test
1393 public void testGetFloatPrimitiveListDefault()
1394 {
1395 _testListDefault("float", "3.14159265");
1396 }
1397
1398 @Test
1399 public void testGetDouble()
1400 {
1401 _test("double", "3.14159265358979");
1402 }
1403
1404 @Test
1405 public void testGetDoublePrimitivesDefault()
1406 {
1407 _testDefault("double", "3.14159265358979");
1408 }
1409
1410 @Test
1411 public void testGetDoublePrimitiveWrappersDefault()
1412 {
1413 _testWrappersDefault("double", "3.14159265358979");
1414 }
1415
1416 @Test
1417 public void testGetDoublePrimitiveListDefault()
1418 {
1419 _testListDefault("double", "3.14159265358979");
1420 }
1421
1422 @Test
1423 public void testBadPrimitiveValue()
1424 {
1425 {
1426 String uri = updateQuery(generateURL("/"), "int=abcdef");
1427 ClientRequest request = new ClientRequest(uri);
1428 request.header(HttpHeaderNames.ACCEPT, "application/int");
1429 try
1430 {
1431 ClientResponse<?> response = request.get();
1432 Assert.assertEquals(404, response.getStatus());
1433 shutdown(request);
1434 }
1435 catch (Exception e)
1436 {
1437 throw new RuntimeException(e);
1438 }
1439 }
1440 }
1441
1442 @Test
1443 public void testBadPrimitiveWrapperValue()
1444 {
1445 {
1446 String uri = updateQuery(generateURL("/wrappers"), "int=abcdef");
1447 ClientRequest request = new ClientRequest(uri);
1448 request.header(HttpHeaderNames.ACCEPT, "application/int");
1449 try
1450 {
1451 ClientResponse<?> response = request.get();
1452 Assert.assertEquals(404, response.getStatus());
1453 shutdown(request);
1454 }
1455 catch (Exception e)
1456 {
1457 throw new RuntimeException(e);
1458 }
1459 }
1460 }
1461
1462 @Test
1463 public void testBadPrimitiveListValue()
1464 {
1465 {
1466 String uri = updateQuery(generateURL("/list"), "int=abcdef&int=abcdef");
1467 ClientRequest request = new ClientRequest(uri);
1468 request.header(HttpHeaderNames.ACCEPT, "application/int");
1469 try
1470 {
1471 ClientResponse<?> response = request.get();
1472 Assert.assertEquals(404, response.getStatus());
1473 shutdown(request);
1474 }
1475 catch (Exception e)
1476 {
1477 throw new RuntimeException(e);
1478 }
1479 }
1480 }
1481
1482 @Path("/")
1483 public static interface IResourceQueryPrimitives
1484 {
1485 @GET
1486 @Produces("application/boolean")
1487 String doGet(@QueryParam("boolean") boolean v);
1488
1489 @GET
1490 @Produces("application/byte")
1491 String doGet(@QueryParam("byte") byte v);
1492
1493 @GET
1494 @Produces("application/short")
1495 String doGet(@QueryParam("short") short v);
1496
1497 @GET
1498 @Produces("application/int")
1499 String doGet(@QueryParam("int") int v);
1500
1501 @GET
1502 @Produces("application/long")
1503 String doGet(@QueryParam("long") long v);
1504
1505 @GET
1506 @Produces("application/float")
1507 String doGet(@QueryParam("float") float v);
1508
1509 @GET
1510 @Produces("application/double")
1511 String doGet(@QueryParam("double") double v);
1512 }
1513
1514 @Path("/wrappers")
1515 public static interface IResourceQueryPrimitiveWrappers
1516 {
1517 @GET
1518 @Produces("application/boolean")
1519 String doGet(@QueryParam("boolean") Boolean v);
1520
1521 @GET
1522 @Produces("application/byte")
1523 String doGet(@QueryParam("byte") Byte v);
1524
1525 @GET
1526 @Produces("application/short")
1527 String doGet(@QueryParam("short") Short v);
1528
1529 @GET
1530 @Produces("application/int")
1531 String doGet(@QueryParam("int") Integer v);
1532
1533 @GET
1534 @Produces("application/long")
1535 String doGet(@QueryParam("long") Long v);
1536
1537 @GET
1538 @Produces("application/float")
1539 String doGet(@QueryParam("float") Float v);
1540
1541 @GET
1542 @Produces("application/double")
1543 String doGet(@QueryParam("double") Double v);
1544 }
1545
1546 @Path("/list")
1547 public static interface IResourceQueryPrimitiveList
1548 {
1549 @GET
1550 @Produces("application/boolean")
1551 String doGetBoolean(@QueryParam("boolean") List<Boolean> v);
1552
1553 @GET
1554 @Produces("application/byte")
1555 String doGetByte(@QueryParam("byte") List<Byte> v);
1556
1557 @GET
1558 @Produces("application/short")
1559 String doGetShort(@QueryParam("short") List<Short> v);
1560
1561 @GET
1562 @Produces("application/int")
1563 String doGetInteger(@QueryParam("int") List<Integer> v);
1564
1565 @GET
1566 @Produces("application/long")
1567 String doGetLong(@QueryParam("long") List<Long> v);
1568
1569 @GET
1570 @Produces("application/float")
1571 String doGetFloat(@QueryParam("float") List<Float> v);
1572
1573 @GET
1574 @Produces("application/double")
1575 String doGetDouble(@QueryParam("double") List<Double> v);
1576 }
1577
1578 @Path("/array")
1579 public static interface IResourceQueryPrimitiveArray
1580 {
1581 @GET
1582 @Produces("application/boolean")
1583 String doGetBoolean(@QueryParam("boolean") boolean[] v);
1584
1585 @GET
1586 @Produces("application/byte")
1587 String doGetByte(@QueryParam("byte") byte[] v);
1588
1589 @GET
1590 @Produces("application/short")
1591 String doGetShort(@QueryParam("short") short[] v);
1592
1593 @GET
1594 @Produces("application/int")
1595 String doGetInteger(@QueryParam("int") int[] v);
1596
1597 @GET
1598 @Produces("application/long")
1599 String doGetLong(@QueryParam("long") long[] v);
1600
1601 @GET
1602 @Produces("application/float")
1603 String doGetFloat(@QueryParam("float") float[] v);
1604
1605 @GET
1606 @Produces("application/double")
1607 String doGetDouble(@QueryParam("double") double[] v);
1608 }
1609
1610 static private void shutdown(ClientRequest request) throws Exception
1611 {
1612 // request.getExecutor().close();
1613 ApacheHttpClient4Executor executor = (ApacheHttpClient4Executor) request.getExecutor();
1614 executor.getHttpClient().getConnectionManager().shutdown();
1615 }
1616 }
0 package org.jboss.resteasy.test.finegrain.methodparams;
1
2 import org.jboss.resteasy.annotations.StringParameterUnmarshallerBinder;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.spi.StringParameterUnmarshaller;
5 import org.jboss.resteasy.test.BaseResourceTest;
6 import org.jboss.resteasy.util.FindAnnotation;
7 import org.junit.Assert;
8 import org.junit.BeforeClass;
9 import org.junit.Test;
10
11 import javax.ws.rs.GET;
12 import javax.ws.rs.Path;
13 import javax.ws.rs.PathParam;
14 import javax.ws.rs.Produces;
15 import java.lang.annotation.Annotation;
16 import java.lang.annotation.Retention;
17 import java.lang.annotation.RetentionPolicy;
18 import java.text.ParseException;
19 import java.text.SimpleDateFormat;
20 import java.util.Calendar;
21 import java.util.Date;
22
23 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
24
25 /**
26 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
27 * @version $Revision: 1 $
28 */
29 public class StringParamUnmarshallerTest extends BaseResourceTest
30 {
31 @Retention(RetentionPolicy.RUNTIME)
32 @StringParameterUnmarshallerBinder(DateFormatter.class)
33 public @interface DateFormat
34 {
35 String value();
36 }
37
38 public static class DateFormatter implements StringParameterUnmarshaller<Date>
39 {
40 private SimpleDateFormat formatter;
41
42 public void setAnnotations(Annotation[] annotations)
43 {
44 DateFormat format = FindAnnotation.findAnnotation(annotations, DateFormat.class);
45 formatter = new SimpleDateFormat(format.value());
46 }
47
48 public Date fromString(String str)
49 {
50 try
51 {
52 return formatter.parse(str);
53 }
54 catch (ParseException e)
55 {
56 throw new RuntimeException(e);
57 }
58 }
59 }
60
61 public static enum Fruit
62 {
63 ORANGE,
64 PEAR
65 }
66
67 public static class Sport
68 {
69 public String name;
70
71 public static Sport fromString(String str)
72 {
73 Sport s = new Sport();
74 s.name = str;
75 return s;
76 }
77
78
79 }
80
81 @Path("/")
82 public static class Service
83 {
84 @GET
85 @Produces("text/plain")
86 @Path("/datetest/{date}")
87 public String get(@PathParam("date") @DateFormat("MM-dd-yyyy") Date date)
88 {
89 System.out.println(date);
90 Calendar c = Calendar.getInstance();
91 c.setTime(date);
92 Assert.assertEquals(3, c.get(Calendar.MONTH));
93 Assert.assertEquals(23, c.get(Calendar.DAY_OF_MONTH));
94 Assert.assertEquals(1977, c.get(Calendar.YEAR));
95 return date.toString();
96 }
97
98 @GET
99 @Produces("text/plain")
100 @Path("fromstring/{fruit}/{sport}")
101 public String getFromString(@PathParam("fruit") Fruit fruit, @PathParam("sport") Sport sport)
102 {
103 Assert.assertEquals(fruit, Fruit.ORANGE);
104 Assert.assertEquals("football", sport.name);
105 return sport.name + fruit;
106 }
107 }
108
109 @BeforeClass
110 public static void setup() throws Exception
111 {
112 addPerRequestResource(Service.class);
113 }
114
115 @Test
116 public void testMe() throws Exception
117 {
118 ClientRequest request = new ClientRequest(generateURL("/datetest/04-23-1977"));
119 System.out.println(request.getTarget(String.class));
120 }
121
122 @Test
123 public void testMe2() throws Exception
124 {
125 ClientRequest request = new ClientRequest(generateURL("/fromstring/ORANGE/football"));
126 System.out.println(request.getTarget(String.class));
127 }
128 }
0 package org.jboss.resteasy.test.finegrain.methodparams;
1
2 import org.jboss.resteasy.client.ProxyFactory;
3 import org.jboss.resteasy.spi.StringConverter;
4 import org.jboss.resteasy.test.BaseResourceTest;
5 import org.junit.Assert;
6 import org.junit.Before;
7 import org.junit.Test;
8
9 import javax.ws.rs.PUT;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.PathParam;
12 import javax.ws.rs.ext.Provider;
13
14 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
15
16 public class SuperStringConverterTest extends BaseResourceTest
17 {
18 public static class Person
19 {
20 private final String name;
21
22 public Person(String name)
23 {
24 this.name = name;
25 }
26
27 public String getName()
28 {
29 return name;
30 }
31 }
32
33 @Provider
34 public static class PersonConverter extends SuperPersonConverter implements StringConverter<Person>
35 {
36 }
37
38 public abstract static class SuperPersonConverter implements StringConverter<Person>
39 {
40 public Person fromString(String value)
41 {
42 return new Person(value);
43 }
44
45 public String toString(Person value)
46 {
47 return value.getName();
48 }
49 }
50
51 public static class Company
52 {
53 private final String name;
54
55 public Company(String name)
56 {
57 this.name = name;
58 }
59
60 public String getName()
61 {
62 return name;
63 }
64
65 @Override
66 public String toString()
67 {
68 return getName();
69 }
70 }
71
72 @Provider
73 public static class CompanyConverter extends ObjectConverter<Company> implements StringConverter<Company>
74 {
75 public Company fromString(String value)
76 {
77 return new Company(value);
78 }
79
80 }
81
82 public abstract static class ObjectConverter<T> implements StringConverter<T>
83 {
84 public String toString(T value)
85 {
86 return value.toString();
87 }
88 }
89
90 @Path("/")
91 public static class MyResource
92 {
93 @Path("person/{person}")
94 @PUT
95 public void put(@PathParam("person") Person p)
96 {
97 Assert.assertEquals(p.getName(), "name");
98 }
99
100 @Path("company/{company}")
101 @PUT
102 public void putCompany(@PathParam("company") Company c)
103 {
104 Assert.assertEquals(c.getName(), "name");
105 }
106 }
107
108 @Before
109 public void setUp() throws Exception
110 {
111 deployment.getProviderFactory().registerProvider(PersonConverter.class);
112 deployment.getProviderFactory().registerProvider(CompanyConverter.class);
113 deployment.getRegistry().addPerRequestResource(MyResource.class);
114 }
115
116 @Path("/")
117 public static interface MyClient
118 {
119 @Path("person/{person}")
120 @PUT
121 void put(@PathParam("person") Person p);
122
123 @Path("company/{company}")
124 @PUT
125 public void putCompany(@PathParam("company") Company c);
126 }
127
128 @Test
129 public void testPerson() throws Exception
130 {
131 MyClient client = ProxyFactory.create(MyClient.class, generateBaseUrl());
132 Person person = new Person("name");
133 client.put(person);
134 }
135
136 @Test
137 public void testCompany() throws Exception
138 {
139 MyClient client = ProxyFactory.create(MyClient.class, generateBaseUrl());
140 Company company = new Company("name");
141 client.putCompany(company);
142 }
143 }
0 package org.jboss.resteasy.test.finegrain.methodparams;
1
2
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.ProxyFactory;
6 import org.jboss.resteasy.spi.ResteasyDeployment;
7 import org.jboss.resteasy.test.EmbeddedContainer;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.junit.AfterClass;
10 import org.junit.Assert;
11 import org.junit.BeforeClass;
12 import org.junit.Test;
13
14 import javax.ws.rs.GET;
15 import javax.ws.rs.Path;
16 import javax.ws.rs.PathParam;
17
18 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
19 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
20 import static org.jboss.resteasy.util.HttpClient4xUtils.updateQuery;
21
22 /**
23 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
24 * @version $Revision: 1 $
25 */
26 public class UriParamAsPrimitiveTest
27 {
28 private static ResteasyDeployment deployment;
29
30 private static IResourceUriBoolean resourceUriBoolean;
31
32 private static IResourceUriByte resourceUriByte;
33
34 @BeforeClass
35 public static void before() throws Exception
36 {
37 deployment = EmbeddedContainer.start();
38 deployment.getRegistry().addPerRequestResource(ResourceUriBoolean.class);
39 deployment.getRegistry().addPerRequestResource(ResourceUriByte.class);
40 deployment.getRegistry().addPerRequestResource(ResourceUriShort.class);
41 deployment.getRegistry().addPerRequestResource(ResourceUriInt.class);
42 deployment.getRegistry().addPerRequestResource(ResourceUriLong.class);
43 deployment.getRegistry().addPerRequestResource(ResourceUriFloat.class);
44 deployment.getRegistry().addPerRequestResource(ResourceUriDouble.class);
45 deployment.getRegistry().addPerRequestResource(ResourceUriBooleanWrapper.class);
46 deployment.getRegistry().addPerRequestResource(ResourceUriByteWrapper.class);
47 deployment.getRegistry().addPerRequestResource(ResourceUriShortWrapper.class);
48 deployment.getRegistry().addPerRequestResource(ResourceUriIntWrapper.class);
49 deployment.getRegistry().addPerRequestResource(ResourceUriLongWrapper.class);
50 deployment.getRegistry().addPerRequestResource(ResourceUriFloatWrapper.class);
51 deployment.getRegistry().addPerRequestResource(ResourceUriDoubleWrapper.class);
52 resourceUriBoolean = ProxyFactory.create(IResourceUriBoolean.class, generateBaseUrl());
53 resourceUriByte = ProxyFactory.create(IResourceUriByte.class, generateBaseUrl());
54 }
55
56 @AfterClass
57 public static void after() throws Exception
58 {
59 EmbeddedContainer.stop();
60 }
61
62 @Path("/boolean/{arg}")
63 public static class ResourceUriBoolean
64 {
65 @GET
66 public String doGet(@PathParam("arg") boolean v)
67 {
68 Assert.assertEquals(true, v);
69 return "content";
70 }
71 }
72
73 @Path("/boolean/{arg}")
74 public static interface IResourceUriBoolean
75 {
76 @GET
77 public String doGet(@PathParam("arg") boolean v);
78 }
79
80 @Path("/byte/{arg}")
81 public static class ResourceUriByte
82 {
83 @GET
84 public String doGet(@PathParam("arg") byte v)
85 {
86 Assert.assertTrue(127 == v);
87 return "content";
88 }
89 }
90
91 @Path("/byte/{arg}")
92 public static interface IResourceUriByte
93 {
94 @GET
95 public String doGet(@PathParam("arg") byte v);
96 }
97
98 @Path("/short/{arg}")
99 public static class ResourceUriShort
100 {
101 @GET
102 public String doGet(@PathParam("arg") short v)
103 {
104 Assert.assertTrue(32767 == v);
105 return "content";
106 }
107 }
108
109 @Path("/int/{arg}")
110 public static class ResourceUriInt
111 {
112 @GET
113 public String doGet(@PathParam("arg") int v)
114 {
115 Assert.assertEquals(2147483647, v);
116 return "content";
117 }
118 }
119
120 @Path("/long/{arg}")
121 public static class ResourceUriLong
122 {
123 @GET
124 public String doGet(@PathParam("arg") long v)
125 {
126 Assert.assertEquals(9223372036854775807L, v);
127 return "content";
128 }
129 }
130
131 @Path("/float/{arg}")
132 public static class ResourceUriFloat
133 {
134 @GET
135 public String doGet(@PathParam("arg") float v)
136 {
137 Assert.assertEquals(3.14159265f, v, 0.0000000001f);
138 return "content";
139 }
140 }
141
142 @Path("/double/{arg}")
143 public static class ResourceUriDouble
144 {
145 @GET
146 public String doGet(@PathParam("arg") double v)
147 {
148 Assert.assertEquals(3.14159265358979d, v, 0.0000000000000001d);
149 return "content";
150 }
151 }
152
153 @Path("/boolean/wrapper/{arg}")
154 public static class ResourceUriBooleanWrapper
155 {
156 @GET
157 public String doGet(@PathParam("arg") Boolean v)
158 {
159 Assert.assertEquals(true, v.booleanValue());
160 return "content";
161 }
162 }
163
164 @Path("/byte/wrapper/{arg}")
165 public static class ResourceUriByteWrapper
166 {
167 @GET
168 public String doGet(@PathParam("arg") Byte v)
169 {
170 Assert.assertTrue(127 == v.byteValue());
171 return "content";
172 }
173 }
174
175 @Path("/short/wrapper/{arg}")
176 public static class ResourceUriShortWrapper
177 {
178 @GET
179 public String doGet(@PathParam("arg") Short v)
180 {
181 Assert.assertTrue(32767 == v.shortValue());
182 return "content";
183 }
184 }
185
186 @Path("/int/wrapper/{arg}")
187 public static class ResourceUriIntWrapper
188 {
189 @GET
190 public String doGet(@PathParam("arg") Integer v)
191 {
192 Assert.assertEquals(2147483647, v.intValue());
193 return "content";
194 }
195 }
196
197 @Path("/long/wrapper/{arg}")
198 public static class ResourceUriLongWrapper
199 {
200 @GET
201 public String doGet(@PathParam("arg") Long v)
202 {
203 Assert.assertEquals(9223372036854775807L, v.longValue());
204 return "content";
205 }
206 }
207
208 @Path("/float/wrapper/{arg}")
209 public static class ResourceUriFloatWrapper
210 {
211 @GET
212 public String doGet(@PathParam("arg") Float v)
213 {
214 Assert.assertEquals(3.14159265f, v.floatValue(), 0.0000000001f);
215 return "content";
216 }
217 }
218
219 @Path("/double/wrapper/{arg}")
220 public static class ResourceUriDoubleWrapper
221 {
222 @GET
223 public String doGet(@PathParam("arg") Double v)
224 {
225 Assert.assertEquals(3.14159265358979d, v.doubleValue(), 0.0000000000000001d);
226 return "content";
227 }
228 }
229
230 void _test(String type, String value)
231 {
232 {
233 ClientRequest request = new ClientRequest(generateURL("/" + type + "/" + value));
234 try
235 {
236 ClientResponse<?> response = request.get();
237 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
238 response.releaseConnection();
239 } catch (Exception e)
240 {
241 throw new RuntimeException(e);
242 }
243 }
244
245 {
246 ClientRequest request = new ClientRequest(generateURL("/" + type + "/wrapper/" + value));
247 try
248 {
249 ClientResponse<?> response = request.get();
250 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
251 response.releaseConnection();
252 } catch (Exception e)
253 {
254 throw new RuntimeException(e);
255 }
256 }
257 }
258
259 @Test
260 public void testGetBoolean()
261 {
262 _test("boolean", "true");
263 resourceUriBoolean.doGet(true);
264 }
265
266 @Test
267 public void testGetByte()
268 {
269 _test("byte", "127");
270 resourceUriByte.doGet((byte) 127);
271 }
272
273 @Test
274 public void testGetShort()
275 {
276 _test("short", "32767");
277 }
278
279 @Test
280 public void testGetInt()
281 {
282 _test("int", "2147483647");
283 }
284
285 @Test
286 public void testGetLong()
287 {
288 _test("long", "9223372036854775807");
289 }
290
291 @Test
292 public void testGetFloat()
293 {
294 _test("float", "3.14159265");
295 }
296
297 @Test
298 public void testGetDouble()
299 {
300 _test("double", "3.14159265358979");
301 }
302
303 public void testBadPrimitiveValue()
304 {
305 String uri = updateQuery(generateURL("/int/abcdef"), "int=abcdef");
306 ClientRequest request = new ClientRequest(uri);
307 try
308 {
309 ClientResponse<?> response = request.get();
310 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
311 response.releaseConnection();
312 } catch (Exception e)
313 {
314 throw new RuntimeException(e);
315 }
316 }
317
318 public void testBadPrimitiveWrapperValue()
319 {
320 String uri = updateQuery(generateURL("/int/wrapper/abcdef"), "int=abcdef");
321 ClientRequest request = new ClientRequest(uri);
322 try
323 {
324 ClientResponse<?> response = request.get();
325 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
326 response.releaseConnection();
327 } catch (Exception e)
328 {
329 throw new RuntimeException(e);
330 }
331 }
332 }
0 package org.jboss.resteasy.test.finegrain.resource;
1
2 import org.apache.http.HttpResponse;
3 import org.apache.http.client.HttpClient;
4 import org.apache.http.client.methods.HttpPost;
5 import org.apache.http.entity.StringEntity;
6 import org.apache.http.impl.client.DefaultHttpClient;
7 import org.jboss.resteasy.client.ClientRequest;
8 import org.jboss.resteasy.client.ClientResponse;
9 import org.jboss.resteasy.core.Dispatcher;
10 import org.jboss.resteasy.plugins.delegates.MediaTypeHeaderDelegate;
11 import org.jboss.resteasy.test.EmbeddedContainer;
12 import org.jboss.resteasy.util.HttpHeaderNames;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.junit.AfterClass;
15 import org.junit.Assert;
16 import org.junit.BeforeClass;
17 import org.junit.Test;
18
19 import javax.servlet.http.HttpServletResponse;
20 import javax.ws.rs.Consumes;
21 import javax.ws.rs.DELETE;
22 import javax.ws.rs.GET;
23 import javax.ws.rs.POST;
24 import javax.ws.rs.Path;
25 import javax.ws.rs.PathParam;
26 import javax.ws.rs.Produces;
27 import javax.ws.rs.core.MediaType;
28 import java.io.IOException;
29
30 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
31 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
32 import static org.jboss.resteasy.util.HttpClient4xUtils.consumeEntity;
33
34 /**
35 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
36 * @version $Revision: 1 $
37 */
38 public class ClientErrorTest
39 {
40 private static Dispatcher dispatcher;
41
42 @Path("/")
43 public static class WebResourceUnsupportedMediaType
44 {
45 @Consumes("application/bar")
46 @Produces("application/foo")
47 @POST
48 public String doPost(String entity)
49 {
50 return "content";
51 }
52
53 @Produces("text/plain")
54 @GET
55 @Path("complex/match")
56 public String get()
57 {
58 return "content";
59 }
60
61 @Produces("text/xml")
62 @GET
63 @Path("complex/{uriparam: [^/]+}")
64 public String getXml(@PathParam("uriparam") String param)
65 {
66 return "<" + param + "/>";
67 }
68
69 @DELETE
70 public void delete()
71 {
72
73 }
74
75 @Path("/nocontent")
76 @POST
77 public void noreturn(String entity)
78 {
79
80 }
81 }
82
83 @BeforeClass
84 public static void before() throws Exception
85 {
86 dispatcher = EmbeddedContainer.start().getDispatcher();
87 dispatcher.getRegistry().addPerRequestResource(WebResourceUnsupportedMediaType.class);
88 }
89
90 @AfterClass
91 public static void after() throws Exception
92 {
93 EmbeddedContainer.stop();
94 }
95
96 @Test
97 public void testComplex()
98 {
99 // this tests a Accept failure match and that another method can match the accept
100 ClientRequest request = new ClientRequest(generateURL("/complex/match"));
101 request.header(HttpHeaderNames.ACCEPT, "text/xml");
102 try
103 {
104 ClientResponse<?> response = request.get();
105 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
106 response.releaseConnection();
107 }
108 catch (Exception e)
109 {
110 throw new RuntimeException(e);
111 }
112 }
113
114 @Test
115 public void testNotFound()
116 {
117 ClientRequest request = new ClientRequest(generateURL("/foo/notthere"));
118 request.header(HttpHeaderNames.ACCEPT, "application/foo");
119 try
120 {
121 ClientResponse<?> response = request.get();
122 Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
123 response.releaseConnection();
124 }
125 catch (Exception e)
126 {
127 throw new RuntimeException(e);
128 }
129 }
130
131 @Test
132 public void testMethodNotAllowed()
133 {
134 ClientRequest request = new ClientRequest(generateURL(""));
135 request.header(HttpHeaderNames.ACCEPT, "application/foo");
136 try
137 {
138 ClientResponse<?> response = request.get();
139 Assert.assertEquals(HttpServletResponse.SC_METHOD_NOT_ALLOWED, response.getStatus());
140 response.releaseConnection();
141 }
142 catch (Exception e)
143 {
144 throw new RuntimeException(e);
145 }
146 }
147
148 @Test
149 public void testNotAcceptable()
150 {
151 ClientRequest request = new ClientRequest(generateBaseUrl());
152 request.header(HttpHeaderNames.ACCEPT, "application/bar");
153 request.body("application/bar", "content");
154 try
155 {
156 ClientResponse<?> response = request.post();
157 Assert.assertEquals(HttpServletResponse.SC_NOT_ACCEPTABLE, response.getStatus());
158 response.releaseConnection();
159 }
160 catch (Exception e)
161 {
162 throw new RuntimeException(e);
163 }
164 }
165
166 @Test
167 public void testNoContentPost()
168 {
169 ClientRequest request = new ClientRequest(generateURL("/nocontent"));
170 request.body("text/plain", "content");
171 try
172 {
173 ClientResponse<?> response = request.post();
174 Assert.assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
175 response.releaseConnection();
176 }
177 catch (Exception e)
178 {
179 throw new RuntimeException(e);
180 }
181 }
182
183 @Test
184 public void testNoContent()
185 {
186 ClientRequest request = new ClientRequest(generateBaseUrl());
187 try
188 {
189 ClientResponse<?> response = request.delete();
190 Assert.assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
191 response.releaseConnection();
192 }
193 catch (Exception e)
194 {
195 throw new RuntimeException(e);
196 }
197 }
198
199 @Test
200 public void testUnsupportedMediaType()
201 {
202 ClientRequest request = new ClientRequest(generateBaseUrl());
203 request.header(HttpHeaderNames.ACCEPT, "application/foo");
204 request.body("text/plain", "content");
205 try
206 {
207 ClientResponse<?> response = request.post();
208 Assert.assertEquals(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, response.getStatus());
209 response.releaseConnection();
210 }
211 catch (Exception e)
212 {
213 throw new RuntimeException(e);
214 }
215 }
216
217 @Test
218 public void testBadAcceptMediaTypeNoSubType()
219 {
220 ClientRequest request = new ClientRequest(generateURL("/complex/match"));
221 request.header(HttpHeaderNames.ACCEPT, "text");
222 try
223 {
224 ClientResponse<?> response = request.get();
225 Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
226 response.releaseConnection();
227 }
228 catch (Exception e)
229 {
230 throw new RuntimeException(e);
231 }
232 }
233
234 @Test
235 public void testBadAcceptMediaTypeNonNumericQualityValue()
236 {
237 ClientRequest request = new ClientRequest(generateURL("/complex/match"));
238 request.header(HttpHeaderNames.ACCEPT, "text/plain; q=bad");
239 try
240 {
241 ClientResponse<?> response = request.get();
242 Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
243 response.releaseConnection();
244 }
245 catch (Exception e)
246 {
247 throw new RuntimeException(e);
248 }
249 }
250
251 /**
252 * This test needs a special extension of MediaTypeHeaderDelegate
253 * to work with the RESTEasy client framework, so it has been moved
254 * to a separate class, ClientErrorBadMediaTest.
255 */
256 @Test
257 public void testBadContentType()
258 {
259 HttpClient client = new DefaultHttpClient();
260 HttpPost method = new HttpPost(generateURL("/"));
261 HttpResponse response = null;
262 try
263 {
264 method.setEntity(new StringEntity("content", "text", null));
265 response = client.execute(method);
266 Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpResponseCodes.SC_BAD_REQUEST);
267 }
268 catch (IOException e)
269 {
270 throw new RuntimeException(e);
271 }
272 finally
273 {
274 consumeEntity(response);
275 }
276 }
277
278 static class TestMediaTypeHeaderDelegate extends MediaTypeHeaderDelegate
279 {
280 public static MediaType parse(String type)
281 {
282 if ("text".equals(type))
283 {
284 return new MediaType("text", "");
285 }
286 return MediaTypeHeaderDelegate.parse(type);
287 }
288 }
289 }
0 package org.jboss.resteasy.test.finegrain.resource;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.core.Dispatcher;
5 import org.jboss.resteasy.test.EmbeddedContainer;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.junit.AfterClass;
8 import org.junit.Assert;
9 import org.junit.BeforeClass;
10 import org.junit.Test;
11
12 import javax.ws.rs.GET;
13 import javax.ws.rs.Path;
14
15 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
16
17 /**
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 */
21 public class EncodedPathTest
22 {
23 private static Dispatcher dispatcher;
24
25 @BeforeClass
26 public static void before() throws Exception
27 {
28 }
29
30 @AfterClass
31 public static void after() throws Exception
32 {
33 }
34
35 @Path("/")
36 public static class SimpleResource
37 {
38 @Path("/hello world")
39 @GET
40 public String get()
41 {
42 System.out.println("Hello");
43 return "HELLO";
44 }
45
46 @Path("/goodbye%7Bworld")
47 @GET
48 public String goodbye()
49 {
50 System.out.println("Goodbye");
51 return "GOODBYE";
52 }
53 }
54
55 private void _test(String path)
56 {
57 ClientRequest request = new ClientRequest(generateURL(path));
58 try
59 {
60 ClientResponse<?> response = request.get();
61 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
62 response.releaseConnection();
63 }
64 catch (Exception e)
65 {
66 throw new RuntimeException(e);
67 }
68 }
69
70 @Test
71 public void testEncoded() throws Exception
72 {
73 dispatcher = EmbeddedContainer.start().getDispatcher();
74 try
75 {
76 dispatcher.getRegistry().addPerRequestResource(SimpleResource.class);
77 _test("/hello%20world");
78 _test("/goodbye%7Bworld");
79 }
80 finally
81 {
82 EmbeddedContainer.stop();
83 }
84 }
85 }
0 package org.jboss.resteasy.test.finegrain.resource;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.client.ProxyFactory;
5 import org.jboss.resteasy.core.Dispatcher;
6 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
7 import org.jboss.resteasy.test.EmbeddedContainer;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.junit.AfterClass;
10 import org.junit.Assert;
11 import org.junit.BeforeClass;
12 import org.junit.Test;
13
14 import javax.ws.rs.Consumes;
15 import javax.ws.rs.POST;
16 import javax.ws.rs.Path;
17 import javax.ws.rs.Produces;
18 import javax.ws.rs.QueryParam;
19 import javax.ws.rs.core.MediaType;
20 import javax.ws.rs.core.MultivaluedMap;
21 import javax.ws.rs.core.StreamingOutput;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25
26 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
27 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
28
29 /**
30 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
31 * @version $Revision: 1 $
32 */
33 public class FormUrlEncodedTest
34 {
35 private static Dispatcher dispatcher;
36
37 @BeforeClass
38 public static void before() throws Exception
39 {
40 dispatcher = EmbeddedContainer.start().getDispatcher();
41 dispatcher.getRegistry().addPerRequestResource(SimpleResource.class);
42 }
43
44 @AfterClass
45 public static void after() throws Exception
46 {
47 EmbeddedContainer.stop();
48 }
49
50 @Path("/")
51 public static class SimpleResource
52 {
53 @Path("/simple")
54 @POST
55 public StreamingOutput post(@QueryParam("hello") String abs, InputStream entityStream) throws IOException
56 {
57 Assert.assertNull(abs);
58 final InputStream is = entityStream;
59 return new StreamingOutput()
60 {
61 public void write(OutputStream output) throws IOException
62 {
63 System.out.println("WITHIN STREAMING OUTPUT!!!!");
64 int c;
65 while ((c = is.read()) != -1)
66 {
67 output.write(c);
68 }
69 }
70 };
71 }
72
73 @Path("/form")
74 @POST
75 @Produces("application/x-www-form-urlencoded")
76 @Consumes("application/x-www-form-urlencoded")
77 public MultivaluedMap<String, String> post(MultivaluedMap<String, String> form)
78 {
79 Assert.assertEquals("world", form.getFirst("hello"));
80 return form;
81 }
82
83 @Path("/form/twoparams")
84 @POST
85 @Produces("application/x-www-form-urlencoded")
86 @Consumes("application/x-www-form-urlencoded")
87 public MultivaluedMap<String, String> post2Parameters(MultivaluedMap<String, String> form)
88 {
89 Assert.assertEquals(2, form.size());
90 Assert.assertEquals("world", form.getFirst("hello"));
91 Assert.assertEquals("mama", form.getFirst("yo"));
92 return form;
93 }
94
95 @Path("/RESTEASY-109")
96 @POST
97 public void post109(MultivaluedMap<String, String> form)
98 {
99 Assert.assertEquals(form.getFirst("name"), "jon");
100 Assert.assertEquals(form.getFirst("address1"), "123 Main St");
101 Assert.assertEquals(form.getFirst("address2"), "");
102 Assert.assertEquals(form.getFirst("zip"), "12345");
103 }
104
105 }
106
107 /**
108 * Testing JIRA RESTEASY-109
109 */
110 @Test
111 public void testResteasy109()
112 {
113 ClientRequest request = new ClientRequest(generateURL("/RESTEASY-109"));
114 request.body(MediaType.APPLICATION_FORM_URLENCODED,
115 "name=jon&address1=123+Main+St&address2=&zip=12345");
116 try
117 {
118 ClientResponse<?> response = request.post();
119 Assert.assertEquals(204, response.getStatus());
120 response.releaseConnection();
121 }
122 catch (Exception e)
123 {
124 throw new RuntimeException(e);
125 }
126 }
127
128 //@Test
129 public void testQueryParamIsNull()
130 {
131 ClientRequest request = new ClientRequest(generateURL("/simple"));
132 request.formParameter("hello", "world");
133 try
134 {
135 ClientResponse<String> response = request.post(String.class);
136 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
137 Assert.assertEquals("hello=world", response.getEntity());
138 }
139 catch (Exception e)
140 {
141 throw new RuntimeException(e);
142 }
143 }
144
145 //@Test
146 public void testPost()
147 {
148 ClientRequest request = new ClientRequest(generateURL("/form"));
149 request.formParameter("hello", "world");
150 try
151 {
152 ClientResponse<String> response = request.post(String.class);
153 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
154 Assert.assertEquals("hello=world", response.getEntity());
155 }
156 catch (Exception e)
157 {
158 throw new RuntimeException(e);
159 }
160 }
161
162 //@Test
163 public void testPostTwoParameters()
164 {
165 ClientRequest request = new ClientRequest(generateURL("/form/twoparams"));
166 request.formParameter("hello", "world");
167 request.formParameter("yo", "mama");
168 try
169 {
170 ClientResponse<String> response = request.post(String.class);
171 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
172 String body = response.getEntity();
173 Assert.assertTrue(body.indexOf("hello=world") != -1);
174 Assert.assertTrue(body.indexOf("yo=mama") != -1);
175 }
176 catch (Exception e)
177 {
178 throw new RuntimeException(e);
179 }
180 }
181
182 @Path("/")
183 public static interface TestProxy
184 {
185 @Path("/form")
186 @POST
187 @Produces("application/x-www-form-urlencoded")
188 @Consumes("application/x-www-form-urlencoded")
189 public String post(MultivaluedMap<String, String> form);
190
191 @Path("/form")
192 @POST
193 @Produces("application/x-www-form-urlencoded")
194 @Consumes("application/x-www-form-urlencoded")
195 public MultivaluedMap<String, String> post2(MultivaluedMap<String, String> form);
196 }
197
198 //@Test
199 public void testProxy()
200 {
201 TestProxy proxy = ProxyFactory.create(TestProxy.class, generateBaseUrl());
202 MultivaluedMapImpl<String, String> form = new MultivaluedMapImpl<String, String>();
203 form.add("hello", "world");
204 String body = proxy.post(form);
205 Assert.assertEquals("hello=world", body);
206
207 MultivaluedMap<String, String> rtn = proxy.post2(form);
208 Assert.assertEquals(rtn.getFirst("hello"), "world");
209 }
210
211 }
0 package org.jboss.resteasy.test.finegrain.resource;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.test.BaseResourceTest;
5 import org.jboss.resteasy.test.TestPortProvider;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.junit.Assert;
8 import org.junit.Before;
9 import org.junit.Test;
10
11 import javax.ws.rs.GET;
12 import javax.ws.rs.Path;
13 import javax.ws.rs.Produces;
14
15 /**
16 * Spec requires that HEAD and OPTIONS are handled in a default manner
17 *
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 */
21 public class InheritanceTest extends BaseResourceTest
22 {
23
24
25 public static interface ParentResource
26 {
27
28 @GET
29 @Produces("text/plain")
30 public String firstest();
31
32 }
33
34 @Path(value = "/InheritanceTest")
35 public static class ChildResource implements ParentResource
36 {
37
38 public String firstest()
39 {
40 return "First";
41 }
42 }
43
44 public static interface ParentResource1
45 {
46
47 @GET
48 @Produces("text/xml")
49 public String secondtest();
50 }
51
52
53 @Path(value = "/InheritanceTest1")
54 public static class ChildResource1 implements ParentResource1
55 {
56 static String html_content =
57 "<html>" + "<head><title>JAX-RS Test</title></head>" +
58 "<body>Second</body></html>";
59
60 @GET
61 @Produces("text/html")
62 public String secondtest()
63 {
64 return html_content;
65 }
66 }
67
68
69 @Before
70 public void setUp() throws Exception
71 {
72 deployment.getRegistry().addPerRequestResource(ChildResource.class);
73 deployment.getRegistry().addPerRequestResource(ChildResource1.class);
74 }
75
76 /*
77 *
78 * Client sends a request on a resource at /InheritanceTest,
79 * Verify that inheritance works.
80 */
81 @Test
82 public void Test1() throws Exception
83 {
84 ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/InheritanceTest"));
85 request.header("Accept", "text/plain");
86 ClientResponse<String> response = request.get(String.class);
87 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
88 Assert.assertEquals("First", response.getEntity());
89 }
90
91
92 /*
93 * Client sends a request on a resource at /InheritanceTest1,
94 * Verify that inheritance works.
95 */
96 @Test
97 public void Test2() throws Exception
98 {
99 ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/InheritanceTest1"));
100 request.header("Accept", "text/html");
101 ClientResponse<String> response = request.get(String.class);
102 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
103 Assert.assertTrue(response.getEntity().indexOf("Second") > -1);
104 }
105
106
107 }
0 package org.jboss.resteasy.test.finegrain.resource;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.core.Dispatcher;
5 import org.jboss.resteasy.test.EmbeddedContainer;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.junit.AfterClass;
8 import org.junit.Assert;
9 import org.junit.BeforeClass;
10 import org.junit.Test;
11
12 import javax.ws.rs.DELETE;
13 import javax.ws.rs.GET;
14 import javax.ws.rs.HttpMethod;
15 import javax.ws.rs.Path;
16 import javax.ws.rs.core.Response;
17 import java.lang.annotation.Retention;
18 import java.lang.annotation.RetentionPolicy;
19 import java.util.HashSet;
20
21 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
22
23 /**
24 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
25 * @version $Revision: 1 $
26 */
27 public class OptionsTest
28 {
29 private static Dispatcher dispatcher;
30
31 @HttpMethod("OPTIONS")
32 @Retention(RetentionPolicy.RUNTIME)
33 private static @interface OPTIONS
34 {
35 }
36
37 @Path("/")
38 public static class SimpleResource
39 {
40 @OPTIONS
41 @Path("/options")
42 public Response options()
43 {
44 return Response.ok().header("Allow", "GET, POST").build();
45 }
46
47 @Path("/stuff")
48 @GET
49 public String goodbye()
50 {
51 System.out.println("Goodbye");
52 return "GOODBYE";
53 }
54
55 @Path("/stuff")
56 @DELETE
57 public void stuff()
58 {
59 }
60 }
61
62 @BeforeClass
63 public static void before() throws Exception
64 {
65 dispatcher = EmbeddedContainer.start().getDispatcher();
66 dispatcher.getRegistry().addPerRequestResource(SimpleResource.class);
67 }
68
69 @AfterClass
70 public static void after() throws Exception
71 {
72 EmbeddedContainer.stop();
73 }
74
75 @Test
76 public void testOptions() throws Exception
77 {
78 ClientRequest request = new ClientRequest(generateURL("/options"));
79 try
80 {
81 ClientResponse<?> response = request.options();
82 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
83 Assert.assertEquals("GET, POST", response.getResponseHeaders().getFirst("Allow"));
84 response.releaseConnection();
85 }
86 catch (Exception e)
87 {
88 throw new RuntimeException(e);
89 }
90 }
91
92 @Test
93 public void testDefaultOptions() throws Exception
94 {
95 ClientRequest request = new ClientRequest(generateURL("/stuff"));
96 try
97 {
98 ClientResponse<?> response = request.options();
99 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
100 String allowed = response.getResponseHeaders().getFirst("Allow");
101 Assert.assertNotNull(allowed);
102 HashSet<String> vals = new HashSet<String>();
103 for (String v : allowed.split(","))
104 {
105 vals.add(v.trim());
106 }
107 Assert.assertEquals(4, vals.size());
108 Assert.assertTrue(vals.contains("GET"));
109 Assert.assertTrue(vals.contains("DELETE"));
110 Assert.assertTrue(vals.contains("HEAD"));
111 Assert.assertTrue(vals.contains("OPTIONS"));
112 response.releaseConnection();
113 }
114 catch (Exception e)
115 {
116 throw new RuntimeException(e);
117 }
118 }
119
120 @Test
121 public void testMethodNotAllowed() throws Exception
122 {
123 ClientRequest request = new ClientRequest(generateURL("/stuff"));
124 try
125 {
126 ClientResponse<?> response = request.post();
127 Assert.assertEquals(HttpResponseCodes.SC_METHOD_NOT_ALLOWED, response.getStatus());
128 String allowed = response.getResponseHeaders().getFirst("Allow");
129 Assert.assertNotNull(allowed);
130 HashSet<String> vals = new HashSet<String>();
131 for (String v : allowed.split(","))
132 {
133 vals.add(v.trim());
134 }
135 Assert.assertEquals(4, vals.size());
136 Assert.assertTrue(vals.contains("GET"));
137 Assert.assertTrue(vals.contains("DELETE"));
138 Assert.assertTrue(vals.contains("HEAD"));
139 Assert.assertTrue(vals.contains("OPTIONS"));
140 response.releaseConnection();
141 }
142 catch (Exception e)
143 {
144 throw new RuntimeException(e);
145 }
146 }
147 }
0 package org.jboss.resteasy.test.finegrain.resource;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.core.Dispatcher;
5 import org.jboss.resteasy.mock.MockDispatcherFactory;
6 import org.jboss.resteasy.mock.MockHttpRequest;
7 import org.jboss.resteasy.mock.MockHttpResponse;
8 import org.jboss.resteasy.test.EmbeddedContainer;
9 import org.junit.AfterClass;
10 import org.junit.Assert;
11 import org.junit.BeforeClass;
12 import org.junit.Test;
13
14 import javax.servlet.http.HttpServletResponse;
15 import javax.ws.rs.Consumes;
16 import javax.ws.rs.DELETE;
17 import javax.ws.rs.GET;
18 import javax.ws.rs.POST;
19 import javax.ws.rs.Path;
20 import javax.ws.rs.PathParam;
21 import javax.ws.rs.Produces;
22 import javax.ws.rs.QueryParam;
23 import javax.ws.rs.core.Context;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.UriInfo;
26 import java.lang.reflect.InvocationHandler;
27 import java.lang.reflect.Method;
28 import java.lang.reflect.Proxy;
29 import java.util.List;
30
31 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
32
33 /**
34 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
35 * @version $Revision: 1 $
36 */
37 public class ResourceLocatorTest
38 {
39
40 private static Dispatcher dispatcher;
41
42
43 @BeforeClass
44 public static void before() throws Exception
45 {
46 dispatcher = EmbeddedContainer.start().getDispatcher();
47 dispatcher.getRegistry().addPerRequestResource(BaseResource.class);
48 }
49
50 @AfterClass
51 public static void after() throws Exception
52 {
53 EmbeddedContainer.stop();
54 }
55
56
57 public static class Subresource2
58 {
59 @GET
60 @Path("stuff/{param}/bar")
61 public String doGet(@PathParam("param") String param, @Context UriInfo uri)
62 {
63 System.out.println("Uri Ancesstors for Subresource2.doGet():");
64 Assert.assertEquals(4, uri.getMatchedURIs().size());
65 Assert.assertEquals("base/1/resources/subresource2/stuff/2/bar", uri.getMatchedURIs().get(0));
66 Assert.assertEquals("base/1/resources/subresource2", uri.getMatchedURIs().get(1));
67 Assert.assertEquals("base/1/resources", uri.getMatchedURIs().get(2));
68 Assert.assertEquals("", uri.getMatchedURIs().get(3));
69 for (String ancestor : uri.getMatchedURIs()) System.out.println(" " + ancestor);
70
71
72 System.out.println("Uri Ancesstors Object for Subresource2.doGet():");
73 Assert.assertEquals(3, uri.getMatchedResources().size());
74 Assert.assertEquals(Subresource2.class, uri.getMatchedResources().get(0).getClass());
75 Assert.assertEquals(Subresource.class, uri.getMatchedResources().get(1).getClass());
76 Assert.assertEquals(BaseResource.class, uri.getMatchedResources().get(2).getClass());
77 for (Object ancestor : uri.getMatchedResources()) System.out.println(" " + ancestor.getClass().getName());
78 Assert.assertEquals("2", param);
79 return this.getClass().getName() + "-" + param;
80 }
81 }
82
83
84 public static class Subresource
85 {
86 @GET
87 public String doGet(@Context UriInfo uri)
88 {
89 System.out.println("Uri Ancesstors for Subresource.doGet():");
90 List<String> matchedURIs = uri.getMatchedURIs();
91 Assert.assertEquals(2, matchedURIs.size());
92 Assert.assertEquals("base/1/resources", matchedURIs.get(0));
93 Assert.assertEquals("", matchedURIs.get(1));
94 for (String ancestor : matchedURIs) System.out.println(" " + ancestor);
95
96 System.out.println("Uri Ancesstors Object for Subresource.doGet():");
97 Assert.assertEquals(2, uri.getMatchedResources().size());
98 Assert.assertEquals(Subresource.class, uri.getMatchedResources().get(0).getClass());
99 Assert.assertEquals(BaseResource.class, uri.getMatchedResources().get(1).getClass());
100 for (Object ancestor : uri.getMatchedResources()) System.out.println(" " + ancestor.getClass().getName());
101 return this.getClass().getName();
102 }
103
104 @Path("/subresource2")
105 public Object getSubresource2(@Context UriInfo uri)
106 {
107 System.out.println("Uri Ancesstors for Subresource.getSubresource2():");
108 List<String> matchedURIs = uri.getMatchedURIs();
109 Assert.assertEquals(3, matchedURIs.size());
110 Assert.assertEquals("base/1/resources/subresource2", matchedURIs.get(0));
111 Assert.assertEquals("base/1/resources", matchedURIs.get(1));
112 Assert.assertEquals("", matchedURIs.get(2));
113 for (String ancestor : matchedURIs) System.out.println(" " + ancestor);
114
115 System.out.println("Uri Ancesstors Object for Subresource.getSubresource2():");
116 Assert.assertEquals(2, uri.getMatchedResources().size());
117 Assert.assertEquals(Subresource.class, uri.getMatchedResources().get(0).getClass());
118 Assert.assertEquals(BaseResource.class, uri.getMatchedResources().get(1).getClass());
119 for (Object ancestor : uri.getMatchedResources()) System.out.println(" " + ancestor.getClass().getName());
120 return new Subresource2();
121 }
122 }
123
124 @Path("/")
125 public static class BaseResource
126 {
127 @Path("base/{param}/resources")
128 public Object getSubresource(@PathParam("param") String param, @Context UriInfo uri)
129 {
130 System.out.println("Here in BaseResource");
131 Assert.assertEquals("1", param);
132 List<String> matchedURIs = uri.getMatchedURIs();
133 Assert.assertEquals(2, matchedURIs.size());
134 Assert.assertEquals("base/1/resources", matchedURIs.get(0));
135 Assert.assertEquals("", matchedURIs.get(1));
136 for (String ancestor : matchedURIs) System.out.println(" " + ancestor);
137
138 System.out.println("Uri Ancesstors Object for Subresource.doGet():");
139 Assert.assertEquals(1, uri.getMatchedResources().size());
140 Assert.assertEquals(BaseResource.class, uri.getMatchedResources().get(0).getClass());
141 return new Subresource();
142 }
143 @Path("proxy")
144 public Subresource3Interface sub3()
145 {
146
147 return (Subresource3Interface) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[]{Subresource3Interface.class}, new InvocationHandler()
148 {
149 @Override
150 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
151 {
152 return method.invoke(new Subresource3(), args);
153 }
154 });
155
156
157
158 //return new Subresource3();
159 }
160 }
161
162 public static interface Subresource3Interface
163 {
164 @GET
165 @Path("3")
166 String get(@QueryParam("foo") List<Double> params);
167 }
168
169
170 public static class Subresource3 implements Subresource3Interface
171 {
172 @Override
173 public String get(List<Double> params)
174 {
175 Assert.assertNotNull(params);
176 Assert.assertEquals(2, params.size());
177 double p1 = params.get(0);
178 double p2 = params.get(1);
179 return "Subresource3";
180 }
181 }
182
183 @Test
184 public void testProxiedSubresource() throws Exception
185 {
186 ClientRequest request = new ClientRequest(generateURL("/proxy/3"));
187 ClientResponse res = request.queryParameter("foo", "1.2").queryParameter("foo", "1.3").get();
188 Assert.assertEquals(200, res.getStatus());
189
190 }
191
192 @Test
193 public void testSubresource() throws Exception
194 {
195 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
196
197 dispatcher.getRegistry().addPerRequestResource(BaseResource.class);
198 {
199 MockHttpRequest request = MockHttpRequest.get("/base/1/resources");
200 MockHttpResponse response = new MockHttpResponse();
201
202 dispatcher.invoke(request, response);
203
204
205 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
206 Assert.assertEquals(Subresource.class.getName(), response.getContentAsString());
207 }
208
209 /*
210 HttpClient client = new HttpClient();
211 GetMethod method = createGetMethod("/base/1/resources");
212 try
213 {
214 int status = client.executeMethod(method);
215 Assert.assertEquals(status, HttpResponseCodes.SC_OK);
216 String response = method.getResponseBodyAsString();
217 Assert.assertEquals(Subresource.class.getName(), response);
218 }
219 catch (IOException e)
220 {
221 throw new RuntimeException(e);
222 }
223 method.releaseConnection();
224 */
225
226 {
227 MockHttpRequest request = MockHttpRequest.get("/base/1/resources/subresource2/stuff/2/bar");
228 MockHttpResponse response = new MockHttpResponse();
229
230 dispatcher.invoke(request, response);
231
232
233 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
234 Assert.assertEquals(Subresource2.class.getName() + "-2", response.getContentAsString());
235 }
236 }
237
238 public static class Receiver
239 {
240 @Path("/head")
241 @GET
242 public String get()
243 {
244 return this.getClass().getName();
245 }
246 }
247
248 public static class QueueReceiver extends Receiver
249 {
250
251 }
252
253 @Path("/directory")
254 public static class Directory
255 {
256 @Path("/receivers/{id}")
257 public QueueReceiver getReceiver(@PathParam("id") String id)
258 {
259 return new QueueReceiver();
260 }
261
262 @DELETE
263 @Path("/receivers/{id}")
264 public String closeReceiver(@PathParam("id") String id) throws Exception
265 {
266 return Directory.class.getName();
267 }
268 }
269
270 @Test
271 public void testSameUri() throws Exception
272 {
273 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
274
275 dispatcher.getRegistry().addPerRequestResource(Directory.class);
276 {
277 MockHttpRequest request = MockHttpRequest.delete("/directory/receivers/1");
278 MockHttpResponse response = new MockHttpResponse();
279
280 dispatcher.invoke(request, response);
281
282
283 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
284 Assert.assertEquals(Directory.class.getName(), new String(response.getOutput()));
285 }
286 }
287
288 @Path("/collection")
289 public static class CollectionResource
290 {
291 @Path("annotation_free_subresource")
292 public Object getAnnotationFreeSubResource()
293 {
294 return new AnnotationFreeSubResource();
295 }
296 }
297
298 @Produces(MediaType.TEXT_PLAIN)
299 public interface RootInterface
300 {
301 @GET
302 String get();
303
304 @Path("{id}")
305 Object getSubSubResource(@PathParam("id") String id);
306 }
307
308 @Produces(MediaType.TEXT_PLAIN)
309 public interface SubInterface extends RootInterface
310 {
311 @POST
312 @Consumes(MediaType.TEXT_PLAIN)
313 String post(String s);
314 }
315
316 public static abstract class AbstractAnnotationFreeResouce implements RootInterface
317 {
318 public String get()
319 {
320 return "got";
321 }
322 }
323
324 public static class AnnotationFreeSubResource extends AbstractAnnotationFreeResouce implements SubInterface
325 {
326 public String post(String s)
327 {
328 return "posted: " + s;
329 }
330
331 public Object getSubSubResource(String id)
332 {
333 return null;
334 }
335 }
336
337 @Test
338 public void testAnnotationFreeSubresource() throws Exception
339 {
340 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
341
342 dispatcher.getRegistry().addPerRequestResource(CollectionResource.class);
343 {
344 MockHttpRequest request = MockHttpRequest.get("/collection/annotation_free_subresource");
345 MockHttpResponse response = new MockHttpResponse();
346
347 dispatcher.invoke(request, response);
348
349 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
350 Assert.assertEquals("got", response.getContentAsString());
351 Assert.assertNotNull(response.getOutputHeaders().get("Content-Type"));
352 Assert.assertTrue(response.getOutputHeaders().get("Content-Type").size() > 0);
353 Assert.assertEquals(MediaType.TEXT_PLAIN_TYPE.withCharset("UTF-8").toString(), response.getOutputHeaders().get("Content-Type").get(0));
354 }
355
356 {
357 MockHttpRequest request = MockHttpRequest.post("/collection/annotation_free_subresource");
358 request.content("hello!".getBytes()).contentType(MediaType.TEXT_PLAIN);
359 MockHttpResponse response = new MockHttpResponse();
360
361 dispatcher.invoke(request, response);
362
363 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
364 Assert.assertEquals("posted: hello!", response.getContentAsString());
365 }
366 }
367 }
0 package org.jboss.resteasy.test.finegrain.resource;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.core.Dispatcher;
5 import org.jboss.resteasy.plugins.server.resourcefactory.SingletonResource;
6 import org.jboss.resteasy.test.EmbeddedContainer;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.junit.AfterClass;
9 import org.junit.Assert;
10 import org.junit.BeforeClass;
11 import org.junit.Test;
12
13 import javax.ws.rs.GET;
14 import javax.ws.rs.MatrixParam;
15 import javax.ws.rs.Path;
16 import javax.ws.rs.PathParam;
17 import javax.ws.rs.QueryParam;
18 import javax.ws.rs.core.Context;
19 import javax.ws.rs.core.MultivaluedMap;
20 import javax.ws.rs.core.PathSegment;
21 import javax.ws.rs.core.UriInfo;
22 import java.net.URI;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.Map;
26
27 import static org.jboss.resteasy.test.TestPortProvider.createURI;
28 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
29
30 /**
31 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
32 * @version $Revision: 1 $
33 */
34 public class UriInfoTest
35 {
36 private static Dispatcher dispatcher;
37
38 @BeforeClass
39 public static void before() throws Exception
40 {
41 }
42
43 @AfterClass
44 public static void after() throws Exception
45 {
46 }
47
48 @Path("/")
49 public static class SimpleResource
50 {
51 @Path("/simple")
52 @GET
53 public String get(@Context UriInfo info, @QueryParam("abs") String abs)
54 {
55 System.out.println("abs query: " + abs);
56 URI base = null;
57 if (abs == null)
58 {
59 base = createURI("/");
60 }
61 else
62 {
63 base = createURI("/" + abs + "/");
64 }
65
66 System.out.println("BASE URI: " + info.getBaseUri());
67 System.out.println("Request URI: " + info.getRequestUri());
68 Assert.assertEquals(base.getPath(), info.getBaseUri().getPath());
69 Assert.assertEquals("/simple", info.getPath());
70 return "CONTENT";
71 }
72
73 @Context
74 UriInfo myInfo;
75
76 @Path("/simple/fromField")
77 @GET
78 public String get(@QueryParam("abs") String abs)
79 {
80 System.out.println("abs query: " + abs);
81 URI base = null;
82 if (abs == null)
83 {
84 base = createURI("/");
85 }
86 else
87 {
88 base = createURI("/" + abs + "/");
89 }
90
91 System.out.println("BASE URI: " + myInfo.getBaseUri());
92 System.out.println("Request URI: " + myInfo.getRequestUri());
93 Assert.assertEquals(base.getPath(), myInfo.getBaseUri().getPath());
94 Assert.assertEquals("/simple/fromField", myInfo.getPath());
95 return "CONTENT";
96 }
97
98 }
99
100 private void _test(String path)
101 {
102 ClientRequest request = new ClientRequest(generateURL(path));
103 try
104 {
105 ClientResponse<?> response = request.get();
106 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
107 response.releaseConnection();
108 }
109 catch (Exception e)
110 {
111 throw new RuntimeException(e);
112 }
113 }
114
115 @Test
116 public void testUriInfoWithSingleton() throws Exception
117 {
118 dispatcher = EmbeddedContainer.start().getDispatcher();
119 try
120 {
121 dispatcher.getRegistry().addResourceFactory(new SingletonResource(new SimpleResource()));
122 _test("/simple/fromField");
123 }
124 finally
125 {
126 EmbeddedContainer.stop();
127 }
128
129 }
130
131 @Test
132 public void testUriInfo() throws Exception
133 {
134 dispatcher = EmbeddedContainer.start().getDispatcher();
135 try
136 {
137 dispatcher.getRegistry().addPerRequestResource(SimpleResource.class);
138 _test("/simple");
139 _test("/simple/fromField");
140 }
141 finally
142 {
143 EmbeddedContainer.stop();
144 }
145 }
146
147 @Test
148 public void testUriInfo2() throws Exception
149 {
150 dispatcher = EmbeddedContainer.start("/resteasy").getDispatcher();
151 try
152 {
153 dispatcher.getRegistry().addPerRequestResource(SimpleResource.class);
154 _test("/resteasy/simple?abs=resteasy");
155 }
156 finally
157 {
158 EmbeddedContainer.stop();
159 }
160 }
161
162 @Path("/{a}/{b}")
163 public static class EncodedTemplateResource
164 {
165 @GET
166 public String doGet(@PathParam("a") String a, @PathParam("b") String b, @Context UriInfo info)
167 {
168 Assert.assertEquals("a b", a);
169 Assert.assertEquals("x y", b);
170 Assert.assertEquals("a b", info.getPathParameters().getFirst("a"));
171 Assert.assertEquals("x y", info.getPathParameters().getFirst("b"));
172 Assert.assertEquals("a%20b", info.getPathParameters(false).getFirst("a"));
173 Assert.assertEquals("x%20y", info.getPathParameters(false).getFirst("b"));
174
175 List<PathSegment> decoded = info.getPathSegments(true);
176 Assert.assertEquals(decoded.size(), 2);
177 Assert.assertEquals("a b", decoded.get(0).getPath());
178 Assert.assertEquals("x y", decoded.get(1).getPath());
179
180 List<PathSegment> encoded = info.getPathSegments(false);
181 Assert.assertEquals(encoded.size(), 2);
182 Assert.assertEquals("a%20b", encoded.get(0).getPath());
183 Assert.assertEquals("x%20y", encoded.get(1).getPath());
184 return "content";
185 }
186 }
187
188 @Path("/queryEscapedMatrParam")
189 public static class EscapedMatrParamResource
190 {
191 @GET
192 public String doGet(@MatrixParam("a") String a, @MatrixParam("b") String b, @MatrixParam("c") String c, @MatrixParam("d") String d)
193 {
194 Assert.assertEquals("a;b", a);
195 Assert.assertEquals("x/y", b);
196 Assert.assertEquals("m\\n", c);
197 Assert.assertEquals("k=l", d);
198 return "content";
199 }
200 }
201
202 @Test
203 public void testEscapedMatrParam() throws Exception
204 {
205 dispatcher = EmbeddedContainer.start().getDispatcher();
206 try
207 {
208 dispatcher.getRegistry().addPerRequestResource(EscapedMatrParamResource.class);
209 _test("/queryEscapedMatrParam;a=a%3Bb;b=x%2Fy;c=m%5Cn;d=k%3Dl");
210 }
211 finally
212 {
213 EmbeddedContainer.stop();
214 }
215 }
216
217 @Test
218 public void testEncodedTemplateParams() throws Exception
219 {
220 dispatcher = EmbeddedContainer.start().getDispatcher();
221 try
222 {
223 dispatcher.getRegistry().addPerRequestResource(EncodedTemplateResource.class);
224 _test("/a%20b/x%20y");
225 }
226 finally
227 {
228 EmbeddedContainer.stop();
229 }
230 }
231
232 @Path("/query")
233 public static class EncodedQueryResource
234 {
235 @GET
236 public String doGet(@QueryParam("a") String a, @Context UriInfo info)
237 {
238 Assert.assertEquals("a b", a);
239 Assert.assertEquals("a b", info.getQueryParameters().getFirst("a"));
240 Assert.assertEquals("a%20b", info.getQueryParameters(false).getFirst("a"));
241 return "content";
242 }
243 }
244
245 @Test
246 public void testEncodedQueryParams() throws Exception
247 {
248 dispatcher = EmbeddedContainer.start().getDispatcher();
249 try
250 {
251 dispatcher.getRegistry().addPerRequestResource(EncodedQueryResource.class);
252 _test("/query?a=a%20b");
253 }
254 finally
255 {
256 EmbeddedContainer.stop();
257 }
258 }
259
260 @Path("/queryParams")
261 public static class QueryParamsResource
262 {
263 @GET
264 public String doGet(@QueryParam("a") String a, @Context UriInfo info)
265 {
266 Assert.assertNotNull(info);
267
268 Assert.assertNotNull(info.getQueryParameters());
269 assertNotMutable(info.getQueryParameters());
270
271 return "content";
272 }
273 }
274
275 @Test
276 public void testQueryParamsMutability() throws Exception {
277 dispatcher = EmbeddedContainer.start().getDispatcher();
278 try
279 {
280 dispatcher.getRegistry().addPerRequestResource(QueryParamsResource.class);
281 _test("/queryParams?a=a,b");
282 }
283 finally
284 {
285 EmbeddedContainer.stop();
286 }
287 }
288
289 private static void assertNotMutable(MultivaluedMap<String, String> params) {
290
291 final String param = "param";
292 final String key = params.keySet().iterator().next();
293
294 try {
295 params.put(param, Collections.singletonList(param));
296 Assert.fail("mutable UriInfo");
297 } catch (UnsupportedOperationException uoe) {
298 //OK
299 }
300
301 try {
302 params.add(param, param);
303 Assert.fail("mutable UriInfo");
304 } catch (UnsupportedOperationException uoe) {
305 //OK
306 }
307
308 try {
309 params.addAll(param, Collections.singletonList(param));
310 Assert.fail("mutable UriInfo");
311 } catch (UnsupportedOperationException uoe) {
312 //OK
313 }
314
315 try {
316 params.addAll(param, param);
317 Assert.fail("mutable UriInfo");
318 } catch (UnsupportedOperationException uoe) {
319 //OK
320 }
321
322 try {
323 params.addFirst(param, param);
324 Assert.fail("mutable UriInfo");
325 } catch (UnsupportedOperationException uoe) {
326 //OK
327 }
328
329 try {
330 params.putSingle(param, param);
331 Assert.fail("mutable UriInfo");
332 } catch (UnsupportedOperationException uoe) {
333 //OK
334 }
335
336 try {
337 params.entrySet().add(new Map.Entry<String, List<String>>() {
338 @Override
339 public String getKey() {
340 return param;
341 }
342
343 @Override
344 public List<String> getValue() {
345 return Collections.singletonList(param);
346 }
347
348 @Override
349 public List<String> setValue(List<String> value) {
350 return Collections.singletonList(param);
351 }
352 });
353 Assert.fail("mutable UriInfo");
354 } catch (UnsupportedOperationException uoe) {
355 //OK
356 }
357
358 try {
359 params.keySet().add(param);
360 Assert.fail("mutable UriInfo");
361 } catch (UnsupportedOperationException uoe) {
362 //OK
363 }
364
365 try {
366 params.clear();
367 Assert.fail("mutable UriInfo");
368 } catch (UnsupportedOperationException uoe) {
369 //OK
370 }
371
372 try {
373 params.putAll(params);
374 Assert.fail("mutable UriInfo");
375 } catch (UnsupportedOperationException uoe) {
376 //OK
377 }
378
379 try {
380 params.remove(key);
381 Assert.fail("mutable UriInfo");
382 } catch (UnsupportedOperationException uoe) {
383 //OK
384 }
385
386 try {
387 params.remove(null);
388 Assert.fail("mutable UriInfo");
389 } catch (UnsupportedOperationException uoe) {
390 //OK
391 }
392
393 try {
394 params.values().add(Collections.singletonList(param));
395 Assert.fail("mutable UriInfo");
396 } catch (UnsupportedOperationException uoe) {
397 //OK
398 }
399
400 }
401 }
0 package org.jboss.resteasy.test.finegrain.resource;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.core.Dispatcher;
5 import org.jboss.resteasy.test.EmbeddedContainer;
6 import org.jboss.resteasy.util.HttpHeaderNames;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.junit.AfterClass;
9 import org.junit.Assert;
10 import org.junit.BeforeClass;
11 import org.junit.Test;
12
13 import javax.ws.rs.GET;
14 import javax.ws.rs.Path;
15 import javax.ws.rs.Produces;
16 import javax.ws.rs.core.Context;
17 import javax.ws.rs.core.MediaType;
18 import javax.ws.rs.core.Request;
19 import javax.ws.rs.core.Response;
20 import javax.ws.rs.core.Variant;
21 import java.util.List;
22 import java.util.Locale;
23
24 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
25
26 /**
27 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
28 * @version $Revision: 1 $
29 */
30 public class VariantsTest
31 {
32 private static Dispatcher dispatcher;
33
34 @BeforeClass
35 public static void before() throws Exception
36 {
37 dispatcher = EmbeddedContainer.start().getDispatcher();
38 dispatcher.getRegistry().addPerRequestResource(LanguageVariantResource.class);
39 dispatcher.getRegistry().addPerRequestResource(ComplexVariantResource.class);
40 dispatcher.getRegistry().addPerRequestResource(EncodingVariantResource.class);
41 }
42
43 @AfterClass
44 public static void after() throws Exception
45 {
46 EmbeddedContainer.stop();
47 }
48
49 @Path("/")
50 public static class LanguageVariantResource
51 {
52 @GET
53 @Produces("text/plain")
54 public Response doGet(@Context Request r)
55 {
56 List<Variant> vs = Variant.VariantListBuilder.newInstance().languages(new Locale("zh")).languages(
57 new Locale("fr")).languages(new Locale("en")).add().build();
58
59 Variant v = r.selectVariant(vs);
60 if (v == null)
61 return Response.notAcceptable(vs).build();
62 else
63 return Response.ok(v.getLanguage(), v).build();
64 }
65 @Path("/brazil")
66 @GET
67 @Produces("text/plain")
68 public Response doGetBrazil(@Context Request r)
69 {
70 List<Variant> vs = Variant.VariantListBuilder.newInstance().languages(new Locale("pt", "BR")).add().build();
71
72 Variant v = r.selectVariant(vs);
73 if (v == null)
74 return Response.notAcceptable(vs).build();
75 else
76 return Response.ok(v.getLanguage(), v).build();
77 }
78 }
79
80 @Test
81 public void testGetLanguageEn() throws Exception
82 {
83 ClientRequest request = new ClientRequest(generateURL("/"));
84 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "en");
85 ClientResponse<String> response = request.get(String.class);
86 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
87 Assert.assertEquals("en", response.getEntity());
88 Assert.assertEquals("en", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_LANGUAGE));
89 }
90
91 @Test
92 public void testGetLanguageWildcard() throws Exception
93 {
94 ClientRequest request = new ClientRequest(generateURL("/"));
95 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "*");
96 ClientResponse<String> response = request.get(String.class);
97 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
98 System.out.println(response.getEntity());
99 Assert.assertNotNull(response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_LANGUAGE));
100 }
101
102 @Test
103 public void testGetLanguageSubLocal() throws Exception
104 {
105 ClientRequest request = new ClientRequest(generateURL("/brazil"));
106 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "pt");
107 ClientResponse<String> response = request.get(String.class);
108 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
109 System.out.println(response.getEntity());
110 Assert.assertNotNull(response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_LANGUAGE));
111 }
112
113 @Test
114 public void testGetLanguageZero() throws Exception
115 {
116 ClientRequest request = new ClientRequest(generateURL("/"));
117 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "*,zh;q=0,en;q=0,fr;q=0");
118 ClientResponse<String> response = request.get(String.class);
119 Assert.assertEquals(HttpResponseCodes.SC_NOT_ACCEPTABLE, response.getStatus());
120 System.out.println(response.getEntity());
121 }
122
123 @Test
124 public void testGetLanguageZh() throws Exception
125 {
126 ClientRequest request = new ClientRequest(generateURL("/"));
127 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "zh");
128 ClientResponse<String> response = request.get(String.class);
129 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
130 Assert.assertEquals("zh", response.getEntity());
131 Assert.assertEquals("zh", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_LANGUAGE));
132 }
133
134 @Test
135 public void testGetLanguageMultiple() throws Exception
136 {
137 ClientRequest request = new ClientRequest(generateURL("/"));
138 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "en;q=0.3, zh;q=0.4, fr");
139 ClientResponse<String> response = request.get(String.class);
140 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
141 Assert.assertEquals("fr", response.getEntity());
142 Assert.assertEquals("fr", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_LANGUAGE));
143 }
144
145 @Path("/complex")
146 public static class ComplexVariantResource
147 {
148 @GET
149 public Response doGet(@Context Request r)
150 {
151 List<Variant> vs = Variant.VariantListBuilder.newInstance().mediaTypes(MediaType.valueOf("image/jpeg")).add()
152 .mediaTypes(MediaType.valueOf("application/xml")).languages(new Locale("en", "us")).add().mediaTypes(
153 MediaType.valueOf("text/xml")).languages(new Locale("en")).add().mediaTypes(
154 MediaType.valueOf("text/xml")).languages(new Locale("en", "us")).add().build();
155
156 Variant v = r.selectVariant(vs);
157 if (v == null)
158 return Response.notAcceptable(vs).build();
159 else
160 return Response.ok("GET", v).build();
161 }
162 }
163
164 @Test
165 public void testGetComplex1() throws Exception
166 {
167 ClientRequest request = new ClientRequest(generateURL("/complex"));
168 request.header(HttpHeaderNames.ACCEPT, "text/xml");
169 request.header(HttpHeaderNames.ACCEPT, "application/xml");
170 request.header(HttpHeaderNames.ACCEPT, "application/xhtml+xml");
171 request.header(HttpHeaderNames.ACCEPT, "image/png");
172 request.header(HttpHeaderNames.ACCEPT, "text/html;q=0.9");
173 request.header(HttpHeaderNames.ACCEPT, "text/plain;q=0.8");
174 request.header(HttpHeaderNames.ACCEPT, "*/*;q=0.5");
175 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "en-us, en;q=0.5");
176 ClientResponse<String> response = request.get(String.class);
177 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
178 Assert.assertEquals("GET", response.getEntity());
179 Assert.assertEquals("application/xml;charset=UTF-8", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_TYPE));
180 Assert.assertEquals("en-us", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_LANGUAGE));
181 }
182
183 @Test
184 public void testGetComplex2() throws Exception
185 {
186 ClientRequest request = new ClientRequest(generateURL("/complex"));
187 request.header(HttpHeaderNames.ACCEPT, "text/xml");
188 request.header(HttpHeaderNames.ACCEPT, "application/xml");
189 request.header(HttpHeaderNames.ACCEPT, "application/xhtml+xml");
190 request.header(HttpHeaderNames.ACCEPT, "image/png");
191 request.header(HttpHeaderNames.ACCEPT, "text/html;q=0.9");
192 request.header(HttpHeaderNames.ACCEPT, "text/plain;q=0.8");
193 request.header(HttpHeaderNames.ACCEPT, "*/*;q=0.5");
194 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "en, en-us");
195 ClientResponse<String> response = request.get(String.class);
196 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
197 Assert.assertEquals("GET", response.getEntity());
198 Assert.assertEquals("application/xml;charset=UTF-8", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_TYPE));
199 Assert.assertEquals("en-us", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_LANGUAGE));
200 }
201
202 @Test
203 public void testGetComplex3() throws Exception
204 {
205 ClientRequest request = new ClientRequest(generateURL("/complex"));
206 request.header(HttpHeaderNames.ACCEPT, "application/xml");
207 request.header(HttpHeaderNames.ACCEPT, "text/xml");
208 request.header(HttpHeaderNames.ACCEPT, "application/xhtml+xml");
209 request.header(HttpHeaderNames.ACCEPT, "image/png");
210 request.header(HttpHeaderNames.ACCEPT, "text/html;q=0.9");
211 request.header(HttpHeaderNames.ACCEPT, "text/plain;q=0.8");
212 request.header(HttpHeaderNames.ACCEPT, "*/*;q=0.5");
213 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "en-us, en;q=0.5");
214 ClientResponse<String> response = request.get(String.class);
215 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
216 Assert.assertEquals("GET", response.getEntity());
217 Assert.assertEquals("application/xml;charset=UTF-8", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_TYPE));
218 Assert.assertEquals("en-us", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_LANGUAGE));
219 }
220
221 @Test
222 public void testGetComplex4() throws Exception
223 {
224 ClientRequest request = new ClientRequest(generateURL("/complex"));
225 request.header(HttpHeaderNames.ACCEPT, "application/xml");
226 request.header(HttpHeaderNames.ACCEPT, "text/xml");
227 request.header(HttpHeaderNames.ACCEPT, "application/xhtml+xml");
228 request.header(HttpHeaderNames.ACCEPT, "image/png");
229 request.header(HttpHeaderNames.ACCEPT, "text/html;q=0.9");
230 request.header(HttpHeaderNames.ACCEPT, "text/plain;q=0.8");
231 request.header(HttpHeaderNames.ACCEPT, "*/*;q=0.5");
232 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "en, en-us;q=0.5");
233 ClientResponse<String> response = request.get(String.class);
234 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
235 Assert.assertEquals("GET", response.getEntity());
236 Assert.assertEquals("en", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_LANGUAGE));
237 Assert.assertEquals("text/xml;charset=UTF-8", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_TYPE));
238 }
239
240
241 @Test
242 public void testGetComplexNotAcceptable() throws Exception
243 {
244 {
245 ClientRequest request = new ClientRequest(generateURL("/complex"));
246 request.header(HttpHeaderNames.ACCEPT, "application/atom+xml");
247 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "en-us, en");
248 ClientResponse<?> response = request.get();
249 Assert.assertEquals(406, response.getStatus());;
250 String vary = response.getResponseHeaders().getFirst(HttpHeaderNames.VARY);
251 Assert.assertNotNull(vary);
252 System.out.println("vary: " + vary);
253 Assert.assertTrue(contains(vary, "Accept"));
254 Assert.assertTrue(contains(vary, "Accept-Language"));
255 response.releaseConnection();
256 }
257
258 {
259 ClientRequest request = new ClientRequest(generateURL("/complex"));
260 request.header(HttpHeaderNames.ACCEPT, "application/xml");
261 request.header(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
262 ClientResponse<?> response = request.get();
263 Assert.assertEquals(406, response.getStatus());;
264 String vary = response.getResponseHeaders().getFirst(HttpHeaderNames.VARY);
265 Assert.assertNotNull(vary);
266 System.out.println("vary: " + vary);
267 Assert.assertTrue(contains(vary, "Accept"));
268 Assert.assertTrue(contains(vary, "Accept-Language"));
269 response.releaseConnection();
270 }
271 }
272
273 @Path("/encoding")
274 public static class EncodingVariantResource
275 {
276 @GET
277 public Response doGet(@Context Request r)
278 {
279 List<Variant> vs = Variant.VariantListBuilder.newInstance().encodings("enc1", "enc2", "enc3").add().build();
280 Variant v = r.selectVariant(vs);
281 if (v == null)
282 return Response.notAcceptable(vs).build();
283 else
284 return Response.ok(v.getEncoding(), v).build();
285 }
286 }
287
288 @Test
289 public void testGetEncoding1() throws Exception
290 {
291 ClientRequest request = new ClientRequest(generateURL("/encoding"));
292 request.header(HttpHeaderNames.ACCEPT_ENCODING, "enc1");
293 ClientResponse<String> response = request.get(String.class);
294 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());;
295 Assert.assertEquals("enc1", response.getEntity());
296 Assert.assertEquals("enc1", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_ENCODING));
297 }
298
299 @Test
300 public void testGetEncoding2() throws Exception
301 {
302 ClientRequest request = new ClientRequest(generateURL("/encoding"));
303 request.header(HttpHeaderNames.ACCEPT_ENCODING, "enc2");
304 ClientResponse<String> response = request.get(String.class);
305 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());;
306 Assert.assertEquals("enc2", response.getEntity());
307 Assert.assertEquals("enc2", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_ENCODING));
308 }
309
310 @Test
311 public void testGetEncoding3() throws Exception
312 {
313 ClientRequest request = new ClientRequest(generateURL("/encoding"));
314 request.header(HttpHeaderNames.ACCEPT_ENCODING, "enc3");
315 ClientResponse<String> response = request.get(String.class);
316 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());;
317 Assert.assertEquals("enc3", response.getEntity());
318 Assert.assertEquals("enc3", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_ENCODING));
319 }
320
321 @Test
322 public void testGetEncodingQ() throws Exception
323 {
324 ClientRequest request = new ClientRequest(generateURL("/encoding"));
325 request.header(HttpHeaderNames.ACCEPT_ENCODING, "enc1;q=0.5, enc2;q=0.9");
326 ClientResponse<String> response = request.get(String.class);
327 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());;
328 Assert.assertEquals("enc2", response.getEntity());
329 Assert.assertEquals("enc2", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_ENCODING));
330 }
331
332 @Test
333 public void testGetEncodingQ2() throws Exception
334 {
335 ClientRequest request = new ClientRequest(generateURL("/encoding"));
336 request.header(HttpHeaderNames.ACCEPT_ENCODING, "enc1;q=0, enc2;q=0.888, enc3;q=0.889");
337 ClientResponse<String> response = request.get(String.class);
338 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());;
339 Assert.assertEquals("enc3", response.getEntity());
340 Assert.assertEquals("enc3", response.getResponseHeaders().getFirst(HttpHeaderNames.CONTENT_ENCODING));
341 }
342
343 private boolean contains(String l, String v)
344 {
345 String[] vs = l.split(",");
346 for (String s : vs)
347 {
348 s = s.trim();
349 if (s.equalsIgnoreCase(v))
350 return true;
351 }
352
353 return false;
354 }
355 }
0 package org.jboss.resteasy.test.form;
1
2 import javax.ws.rs.FormParam;
3 import javax.ws.rs.HeaderParam;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.QueryParam;
6 import java.io.Serializable;
7
8
9 /**
10 * A FormValueHolder.
11 *
12 * @author <a href="ryan@damnhandy.com">Ryan J. McDonough</a>
13 * @version $Revision:$
14 */
15 public class ClientForm implements Serializable
16 {
17
18
19 /**
20 * The serialVersionUID
21 */
22 private static final long serialVersionUID = 1L;
23
24 @HeaderParam("custom-header")
25 private int headerParam;
26
27 @FormParam("booleanValue")
28 private Boolean booleanValue;
29
30 @FormParam("name")
31 private String name;
32
33 @FormParam("doubleValue")
34 private Double doubleValue;
35
36 @FormParam("longValue")
37 private Long longValue;
38
39 @FormParam("integerValue")
40 private Integer integerValue;
41
42 @FormParam("shortValue")
43 private Short shortValue;
44
45 private int id;
46 private int queryParam;
47
48 public int getHeaderParam()
49 {
50 return headerParam;
51 }
52
53 public void setHeaderParam(int headerParam)
54 {
55 this.headerParam = headerParam;
56 }
57
58 @PathParam("id")
59 public int getId()
60 {
61 return id;
62 }
63
64 public void setId(int id)
65 {
66 this.id = id;
67 }
68
69 @QueryParam("query")
70 public int getQueryParam()
71 {
72 return queryParam;
73 }
74
75 public void setQueryParam(int queryParam)
76 {
77 this.queryParam = queryParam;
78 }
79
80 /**
81 * Get the booleanValue.
82 *
83 * @return the booleanValue.
84 */
85 public Boolean getBooleanValue()
86 {
87 return booleanValue;
88 }
89
90 /**
91 * Set the booleanValue.
92 *
93 * @param booleanValue The booleanValue to set.
94 */
95 public void setBooleanValue(Boolean booleanValue)
96 {
97 this.booleanValue = booleanValue;
98 }
99
100 /**
101 * Get the name.
102 *
103 * @return the name.
104 */
105 public String getName()
106 {
107 return name;
108 }
109
110 /**
111 * Set the name.
112 *
113 * @param name The name to set.
114 */
115 public void setName(String name)
116 {
117 this.name = name;
118 }
119
120 /**
121 * Get the doubleValue.
122 *
123 * @return the doubleValue.
124 */
125 public Double getDoubleValue()
126 {
127 return doubleValue;
128 }
129
130 /**
131 * Set the doubleValue.
132 *
133 * @param doubleValue The doubleValue to set.
134 */
135 public void setDoubleValue(Double doubleValue)
136 {
137 this.doubleValue = doubleValue;
138 }
139
140 /**
141 * Get the longValue.
142 *
143 * @return the longValue.
144 */
145 public Long getLongValue()
146 {
147 return longValue;
148 }
149
150 /**
151 * Set the longValue.
152 *
153 * @param longValue The longValue to set.
154 */
155 public void setLongValue(Long longValue)
156 {
157 this.longValue = longValue;
158 }
159
160 /**
161 * Get the integerValue.
162 *
163 * @return the integerValue.
164 */
165 public Integer getIntegerValue()
166 {
167 return integerValue;
168 }
169
170 /**
171 * Set the integerValue.
172 *
173 * @param integerValue The integerValue to set.
174 */
175 public void setIntegerValue(Integer integerValue)
176 {
177 this.integerValue = integerValue;
178 }
179
180 /**
181 * Get the shortValue.
182 *
183 * @return the shortValue.
184 */
185 public Short getShortValue()
186 {
187 return shortValue;
188 }
189
190 /**
191 * Set the shortValue.
192 *
193 * @param shortValue The shortValue to set.
194 */
195 public void setShortValue(Short shortValue)
196 {
197 this.shortValue = shortValue;
198 }
199 }
0 package org.jboss.resteasy.test.form;
1
2 import org.jboss.resteasy.annotations.Form;
3 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
4 import org.junit.Assert;
5
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.core.MultivaluedMap;
11
12 /**
13 * A FormResource.
14 *
15 * @author <a href="ryan@damnhandy.com">Ryan J. McDonough</a>
16 * @version $Revision:$
17 */
18 @Path("/form/{id}")
19 @Produces("application/x-www-form-urlencoded")
20 @Consumes("application/x-www-form-urlencoded")
21 public class FormResource
22 {
23
24 @POST
25 public MultivaluedMap<String, String> postObject(@Form FormValueHolder value)
26 {
27 MultivaluedMap<String, String> rtn = new MultivaluedMapImpl<String, String>();
28 rtn.add("booleanValue", value.getBooleanValue().toString());
29 rtn.add("doubleValue", value.getDoubleValue().toString());
30 rtn.add("integerValue", value.getIntegerValue().toString());
31 rtn.add("longValue", value.getLongValue().toString());
32 rtn.add("shortValue", value.getShortValue().toString());
33 rtn.add("name", value.getName());
34
35 Assert.assertEquals(value.getHeaderParam(), 42);
36 Assert.assertEquals(value.getQueryParam(), 42);
37 Assert.assertEquals(value.getId(), 42);
38 Assert.assertEquals(value.getDefaultValue(), 42);
39 return rtn;
40 }
41 }
0 package org.jboss.resteasy.test.form;
1
2 import javax.ws.rs.DefaultValue;
3 import javax.ws.rs.FormParam;
4 import javax.ws.rs.HeaderParam;
5 import javax.ws.rs.PathParam;
6 import javax.ws.rs.QueryParam;
7 import java.io.Serializable;
8
9
10 /**
11 * A FormValueHolder.
12 *
13 * @author <a href="ryan@damnhandy.com">Ryan J. McDonough</a>
14 * @version $Revision:$
15 */
16 public class FormValueHolder implements Serializable
17 {
18
19
20 /**
21 * The serialVersionUID
22 */
23 private static final long serialVersionUID = 1L;
24
25 @FormParam("booleanValue")
26 private Boolean booleanValue;
27
28 @FormParam("name")
29 private String name;
30
31 @FormParam("doubleValue")
32 private Double doubleValue;
33
34 @FormParam("longValue")
35 private Long longValue;
36
37 @FormParam("integerValue")
38 private Integer integerValue;
39
40 @FormParam("shortValue")
41 private Short shortValue;
42
43 @QueryParam("defaultValue")
44 @DefaultValue("42")
45 public int defaultValue;
46
47 private int headerParam;
48 private int id;
49 private int queryParam;
50
51 public int getDefaultValue()
52 {
53 return defaultValue;
54 }
55
56 public int getHeaderParam()
57 {
58 return headerParam;
59 }
60
61 @HeaderParam("custom-header")
62 public void setHeaderParam(int headerParam)
63 {
64 this.headerParam = headerParam;
65 }
66
67 public int getId()
68 {
69 return id;
70 }
71
72 @PathParam("id")
73 public void setId(int id)
74 {
75 this.id = id;
76 }
77
78 public int getQueryParam()
79 {
80 return queryParam;
81 }
82
83 @QueryParam("query")
84 public void setQueryParam(int queryParam)
85 {
86 this.queryParam = queryParam;
87 }
88
89 /**
90 * Get the booleanValue.
91 *
92 * @return the booleanValue.
93 */
94 public Boolean getBooleanValue()
95 {
96 return booleanValue;
97 }
98
99 /**
100 * Set the booleanValue.
101 *
102 * @param booleanValue The booleanValue to set.
103 */
104 public void setBooleanValue(Boolean booleanValue)
105 {
106 this.booleanValue = booleanValue;
107 }
108
109 /**
110 * Get the name.
111 *
112 * @return the name.
113 */
114 public String getName()
115 {
116 return name;
117 }
118
119 /**
120 * Set the name.
121 *
122 * @param name The name to set.
123 */
124 public void setName(String name)
125 {
126 this.name = name;
127 }
128
129 /**
130 * Get the doubleValue.
131 *
132 * @return the doubleValue.
133 */
134 public Double getDoubleValue()
135 {
136 return doubleValue;
137 }
138
139 /**
140 * Set the doubleValue.
141 *
142 * @param doubleValue The doubleValue to set.
143 */
144 public void setDoubleValue(Double doubleValue)
145 {
146 this.doubleValue = doubleValue;
147 }
148
149 /**
150 * Get the longValue.
151 *
152 * @return the longValue.
153 */
154 public Long getLongValue()
155 {
156 return longValue;
157 }
158
159 /**
160 * Set the longValue.
161 *
162 * @param longValue The longValue to set.
163 */
164 public void setLongValue(Long longValue)
165 {
166 this.longValue = longValue;
167 }
168
169 /**
170 * Get the integerValue.
171 *
172 * @return the integerValue.
173 */
174 public Integer getIntegerValue()
175 {
176 return integerValue;
177 }
178
179 /**
180 * Set the integerValue.
181 *
182 * @param integerValue The integerValue to set.
183 */
184 public void setIntegerValue(Integer integerValue)
185 {
186 this.integerValue = integerValue;
187 }
188
189 /**
190 * Get the shortValue.
191 *
192 * @return the shortValue.
193 */
194 public Short getShortValue()
195 {
196 return shortValue;
197 }
198
199 /**
200 * Set the shortValue.
201 *
202 * @param shortValue The shortValue to set.
203 */
204 public void setShortValue(Short shortValue)
205 {
206 this.shortValue = shortValue;
207 }
208 }
0 package org.jboss.resteasy.test.form;
1
2 import org.jboss.resteasy.annotations.Form;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.ProxyFactory;
6 import org.jboss.resteasy.logging.Logger;
7 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
8 import org.jboss.resteasy.test.BaseResourceTest;
9 import org.jboss.resteasy.util.GenericType;
10 import org.junit.Assert;
11 import org.junit.Before;
12 import org.junit.Test;
13
14 import javax.servlet.http.HttpServletResponse;
15 import javax.ws.rs.GET;
16 import javax.ws.rs.HeaderParam;
17 import javax.ws.rs.POST;
18 import javax.ws.rs.Path;
19 import javax.ws.rs.Produces;
20 import javax.ws.rs.core.MediaType;
21 import javax.ws.rs.core.MultivaluedMap;
22 import java.io.BufferedInputStream;
23 import java.io.InputStream;
24 import java.net.URLDecoder;
25 import java.util.HashMap;
26 import java.util.Map;
27
28 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
29 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
30
31 /**
32 * A TestFormResource.
33 *
34 * @author <a href="ryan@damnhandy.com">Ryan J. McDonough</a>
35 * @version $Revision:$
36 */
37 public class TestFormResource extends BaseResourceTest
38 {
39 private static final String SHORT_VALUE_FIELD = "shortValue";
40
41 private static final String INTEGER_VALUE_FIELD = "integerValue";
42
43 private static final String LONG_VALUE_FIELD = "longValue";
44
45 private static final String DOUBLE_VALUE_FIELD = "doubleValue";
46
47 private static final String NAME_FIELD = "name";
48
49 private static final String BOOLEAN_VALUE_FIELD = "booleanValue";
50
51 private static final String TEST_URI = generateURL("/form/42?query=42");
52
53 @SuppressWarnings("unused")
54 private static final Logger logger = Logger.getLogger(TestFormResource.class);
55
56 @Path("/form/{id}")
57 public interface FormClientProxy
58 {
59 @Produces(MediaType.APPLICATION_FORM_URLENCODED)
60 @POST
61 MultivaluedMap<String, String> post(@Form ClientForm form);
62
63 @Produces(MediaType.APPLICATION_FORM_URLENCODED)
64 @POST
65 String postString(@Form ClientForm form);
66
67 }
68
69 public static class ClientForm2
70 {
71 @HeaderParam("custom-header")
72 protected String foo;
73
74
75 public String getFoo()
76 {
77 return foo;
78 }
79
80 public void setFoo(String foo)
81 {
82 this.foo = foo;
83 }
84 }
85
86 @Path("/myform")
87 public interface MyFormProxy
88 {
89 @POST
90 public void post(@Form ClientForm2 form2);
91 }
92
93 @Path("/myform")
94 public static class MyFormResource
95 {
96 @GET
97 @Path("/server")
98 @Produces("application/x-www-form-urlencoded")
99 public MultivaluedMap<String, String> retrieveServername()
100 {
101
102 MultivaluedMap<String, String> serverMap = new MultivaluedMapImpl<String, String>();
103 serverMap.add("servername", "srv1");
104 serverMap.add("servername", "srv2");
105
106 return serverMap;
107 }
108
109 @POST
110 public void post()
111 {
112
113 }
114 }
115
116 /**
117 * FIXME Comment this
118 *
119 * @throws java.lang.Exception
120 */
121 @Before
122 public void setUp() throws Exception
123 {
124 addPerRequestResource(FormResource.class);
125 addPerRequestResource(MyFormResource.class);
126 }
127
128 /**
129 * RESTEASY-261
130 *
131 * @throws Exception
132 */
133 @Test
134 public void testMultiValueParam() throws Exception
135 {
136 ClientRequest request = new ClientRequest(generateURL("/myform/server"));
137 ClientResponse<MultivaluedMap<String, String>> response = request.get(new GenericType<MultivaluedMap<String, String>>()
138 {
139 });
140 int status = response.getStatus();
141 Assert.assertEquals(200, status);
142 boolean sv1 = false;
143 boolean sv2 = false;
144 MultivaluedMap<String, String> form = response.getEntity();
145 Assert.assertEquals(2, form.get("servername").size());
146 for (String str : form.get("servername"))
147 {
148 if (str.equals("srv1")) sv1 = true;
149 else if (str.equals("srv2")) sv2 = true;
150 }
151 Assert.assertTrue(sv1);
152 Assert.assertTrue(sv2);
153 }
154
155 /**
156 * RESTEASY-691
157 *
158 * @throws Exception
159 */
160 @Test
161 public void testProxy691() throws Exception
162 {
163 MyFormProxy proxy = ProxyFactory.create(MyFormProxy.class, generateBaseUrl());
164 proxy.post(null);
165 }
166
167 @Test
168 public void testProxy() throws Exception
169 {
170 FormClientProxy proxy = ProxyFactory.create(FormClientProxy.class, generateBaseUrl());
171 ClientForm form = new ClientForm();
172 form.setBooleanValue(true);
173 form.setName("This is My Name");
174 form.setDoubleValue(123.45);
175 form.setLongValue(566780L);
176 form.setIntegerValue(3);
177 form.setShortValue((short) 12345);
178 form.setHeaderParam(42);
179 form.setQueryParam(42);
180 form.setId(42);
181 MultivaluedMap<String, String> rtn = proxy.post(form);
182 Assert.assertEquals(rtn.getFirst(BOOLEAN_VALUE_FIELD), "true");
183 Assert.assertEquals(rtn.getFirst(NAME_FIELD), "This is My Name");
184 Assert.assertEquals(rtn.getFirst(DOUBLE_VALUE_FIELD), "123.45");
185 Assert.assertEquals(rtn.getFirst(LONG_VALUE_FIELD), "566780");
186 Assert.assertEquals(rtn.getFirst(INTEGER_VALUE_FIELD), "3");
187 Assert.assertEquals(rtn.getFirst(SHORT_VALUE_FIELD), "12345");
188 String str = proxy.postString(form);
189 System.out.println("STR: " + str);
190 String[] params = str.split("&");
191 Map<String, String> map = new HashMap<String, String>();
192 for (int i = 0; i < params.length; i++)
193 {
194 int index = params[i].indexOf('=');
195 String key = params[i].substring(0, index).trim();
196 String value = params[i].substring(index + 1).trim().replace('+', ' ');
197 map.put(key, value);
198 }
199 Assert.assertEquals(map.get(BOOLEAN_VALUE_FIELD), "true");
200 Assert.assertEquals(map.get(NAME_FIELD), "This is My Name");
201 Assert.assertEquals(map.get(DOUBLE_VALUE_FIELD), "123.45");
202 Assert.assertEquals(map.get(LONG_VALUE_FIELD), "566780");
203 Assert.assertEquals(map.get(INTEGER_VALUE_FIELD), "3");
204 Assert.assertEquals(map.get(SHORT_VALUE_FIELD), "12345");
205 }
206
207 @Test
208 public void testFormResource() throws Exception
209 {
210 InputStream in = null;
211 try
212 {
213 ClientRequest request = new ClientRequest(TEST_URI);
214 request.header("custom-header", "42");
215 request.formParameter(BOOLEAN_VALUE_FIELD, "true");
216 request.formParameter(NAME_FIELD, "This is My Name");
217 request.formParameter(DOUBLE_VALUE_FIELD, "123.45");
218 request.formParameter(LONG_VALUE_FIELD, "566780");
219 request.formParameter(INTEGER_VALUE_FIELD, "3");
220 request.formParameter(SHORT_VALUE_FIELD, "12345");
221 ClientResponse<InputStream> response = request.post(InputStream.class);
222 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
223 String contentType = response.getResponseHeaders().getFirst("content-type");
224 Assert.assertEquals("application/x-www-form-urlencoded", contentType);
225 InputStream responseStream = response.getEntity();
226 in = new BufferedInputStream(responseStream);
227 String formData = readString(in);
228 String[] keys = formData.split("&");
229 Map<String, String> values = new HashMap<String, String>();
230 for (String pair : keys)
231 {
232 int index = pair.indexOf('=');
233 if (index < 0)
234 {
235 values.put(URLDecoder.decode(pair, "UTF-8"), null);
236 }
237 else if (index > 0)
238 {
239 values.put(URLDecoder.decode(pair.substring(0, index), "UTF-8"), URLDecoder.decode(pair
240 .substring(index + 1), "UTF-8"));
241 }
242 }
243 Assert.assertEquals(values.get(BOOLEAN_VALUE_FIELD), "true");
244 Assert.assertEquals(values.get(NAME_FIELD), "This is My Name");
245 Assert.assertEquals(values.get(DOUBLE_VALUE_FIELD), "123.45");
246 Assert.assertEquals(values.get(LONG_VALUE_FIELD), "566780");
247 Assert.assertEquals(values.get(INTEGER_VALUE_FIELD), "3");
248 }
249 finally
250 {
251 if (in != null)
252 {
253 in.close();
254 }
255 }
256 }
257
258 static class StringPair
259 {
260 public String key;
261 public String value;
262
263 public StringPair(String key, String value)
264 {
265 this.key = key;
266 this.value = value;
267 }
268 }
269 }
0 package org.jboss.resteasy.test.interceptors;
1
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.core.interception.InterceptorRegistry;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.junit.Assert;
6 import org.junit.Test;
7
8 import java.lang.annotation.ElementType;
9 import java.lang.annotation.Retention;
10 import java.lang.annotation.RetentionPolicy;
11 import java.lang.annotation.Target;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 */
17 public class PrecedenceTest
18 {
19
20 @Precedence("A")
21 public static class A
22 {
23 }
24
25 @Precedence("B")
26 public static class B
27 {
28 }
29
30 @Precedence("C")
31 public static class C
32 {
33 }
34
35 @Target({ElementType.TYPE})
36 @Retention(RetentionPolicy.RUNTIME)
37 @Precedence("D")
38 public static @interface D
39 {
40
41 }
42
43 @D
44 public static class DClass
45 {
46 }
47
48 @Precedence("BeforeB")
49 public static class BeforeB
50 {
51 }
52
53
54 @Precedence("AfterC")
55 public static class AfterC
56 {
57 }
58
59 @Precedence("BeforeA")
60 public static class BeforeA
61 {
62 }
63
64 @Precedence("AfterD")
65 public static class AfterD
66 {
67 }
68
69 @Test
70 public void testPrecedence() throws Exception
71 {
72 InterceptorRegistry registry = new InterceptorRegistry(Object.class, ResteasyProviderFactory.getInstance());
73 registry.appendPrecedence("A");
74 registry.appendPrecedence("B");
75 registry.appendPrecedence("C");
76 registry.appendPrecedence("D");
77 registry.insertPrecedenceAfter("C", "AfterC");
78 registry.insertPrecedenceBefore("B", "BeforeB");
79 registry.insertPrecedenceBefore("A", "BeforeA");
80 registry.insertPrecedenceAfter("D", "AfterD");
81
82 registry.register(PrecedenceTest.class);
83 registry.register(B.class);
84 registry.register(DClass.class);
85 registry.register(C.class);
86 registry.register(A.class);
87 registry.register(AfterD.class);
88 registry.register(BeforeA.class);
89 registry.register(BeforeB.class);
90 registry.register(AfterC.class);
91
92 Object[] array = registry.bind(null, null);
93
94 for (Object obj : array) System.out.println(obj.getClass().getName());
95
96 Assert.assertEquals(array[0].getClass(), BeforeA.class);
97 Assert.assertEquals(array[1].getClass(), A.class);
98 Assert.assertEquals(array[2].getClass(), BeforeB.class);
99 Assert.assertEquals(array[3].getClass(), B.class);
100 Assert.assertEquals(array[4].getClass(), C.class);
101 Assert.assertEquals(array[5].getClass(), AfterC.class);
102 Assert.assertEquals(array[6].getClass(), DClass.class);
103 Assert.assertEquals(array[7].getClass(), AfterD.class);
104 Assert.assertEquals(array[8].getClass(), PrecedenceTest.class);
105 }
106 }
0 package org.jboss.resteasy.test.mediatype;
1
2 import java.util.HashSet;
3 import java.util.Hashtable;
4 import java.util.Set;
5
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10 import javax.ws.rs.core.Application;
11 import javax.ws.rs.core.Context;
12 import javax.ws.rs.core.UriInfo;
13 import javax.ws.rs.ext.Provider;
14
15 import org.junit.Assert;
16
17 import org.jboss.resteasy.client.ClientRequest;
18 import org.jboss.resteasy.client.ClientResponse;
19 import org.jboss.resteasy.spi.ResteasyDeployment;
20 import org.jboss.resteasy.test.EmbeddedContainer;
21 import org.junit.After;
22 import org.junit.Before;
23 import org.junit.Test;
24
25 /**
26 *
27 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
28 * @version $Revision: 1.1 $
29 *
30 * Copyright Aug 3, 2012
31 */
32 public class FileExtensionMappingTest
33 {
34 protected ResteasyDeployment deployment;
35
36 @Path("/test")
37 static public class TestResource
38 {
39 @GET
40 @Produces("text/plain")
41 public String testPlain(@Context UriInfo uriInfo, @QueryParam("query") String query)
42 {
43 System.out.println(uriInfo.getRequestUri());
44 return "plain: " + query;
45 }
46
47 @GET
48 @Produces("text/html")
49 public String testHtml(@Context UriInfo uriInfo, @QueryParam("query") String query)
50 {
51 System.out.println(uriInfo.getRequestUri());
52 return "html: " + query;
53 }
54 }
55
56 @Provider
57 static public class TestApplication extends Application
58 {
59 public Set<Class<?>> getClasses()
60 {
61 HashSet<Class<?>> classes = new HashSet<Class<?>>();
62 classes.add(TestResource.class);
63 return classes;
64 }
65 }
66
67 @Before
68 public void before() throws Exception
69 {
70 Hashtable<String,String> initParams = new Hashtable<String,String>();
71 Hashtable<String,String> contextParams = new Hashtable<String,String>();
72 contextParams.put("javax.ws.rs.Application", TestApplication.class.getName());
73 contextParams.put("resteasy.media.type.mappings", "txt : text/plain, html : text/html");
74 deployment = EmbeddedContainer.start(initParams, contextParams);
75 }
76
77 @After
78 public void after() throws Exception
79 {
80 EmbeddedContainer.stop();
81 deployment = null;
82 }
83
84 @Test
85 public void testFileExtensionMappingPlain() throws Exception
86 {
87 // ClientRequest request = new ClientRequest("http://localhost:8081/test.txt?query=whosOnFirst");
88 // ClientResponse<String> response = request.get(String.class);
89 // System.out.println("status: " + response.getStatus());
90 // System.out.println("response: " + response.getEntity());
91 // Assert.assertEquals(200, response.getStatus());
92 // Assert.assertEquals("plain: whosOnFirst", response.getEntity());
93 }
94
95
96 @Test
97 public void testFileExtensionMappingHtml() throws Exception
98 {
99 // ClientRequest request = new ClientRequest("http://localhost:8081/test.html?query=whosOnFirst");
100 // ClientResponse<String> response = request.get(String.class);
101 // System.out.println("status: " + response.getStatus());
102 // System.out.println("response: " + response.getEntity());
103 // Assert.assertEquals(200, response.getStatus());
104 // Assert.assertEquals("html: whosOnFirst", response.getEntity());
105 }
106 }
0 package org.jboss.resteasy.test.nextgen.encoding;
1
2 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
3 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
4 import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;
5 import org.jboss.resteasy.test.TestPortProvider;
6 import org.jboss.resteasy.util.Encode;
7 import org.junit.AfterClass;
8 import org.junit.Assert;
9 import org.junit.BeforeClass;
10 import org.junit.Test;
11
12 import javax.ws.rs.core.Response;
13 import java.io.InputStream;
14 import java.io.InputStreamReader;
15 import java.io.Reader;
16 import java.io.UnsupportedEncodingException;
17 import java.net.HttpURLConnection;
18 import java.net.URI;
19 import java.nio.charset.CharacterCodingException;
20
21 public class EncodingTest
22 {
23 private static TJWSEmbeddedJaxrsServer tjws;
24 private static ResteasyClient client;
25 private static TestClient testClient;
26
27 @BeforeClass
28 public static void setupContainer()
29 {
30 tjws = new TJWSEmbeddedJaxrsServer();
31 tjws.setPort(TestPortProvider.getPort());
32 tjws.setRootResourcePath("/");
33 tjws.start();
34 tjws.getDeployment().getDispatcher().getRegistry().addSingletonResource(new MyTestResource());
35 String url = "http://localhost:" + TestPortProvider.getPort();
36 client = new ResteasyClientBuilder().build();
37 testClient = client.target(url).proxy(TestClient.class);
38
39 }
40
41 @AfterClass
42 public static void teardownContainer()
43 {
44 client.close();
45 tjws.stop();
46 }
47
48 Character[] RESERVED_CHARACTERS = {
49 '?', ':', '@', '&', '=', '+', '$', ','
50 };
51
52 //also includes a-zA-Z0-9
53 Character[] UNRESERVED_CHARACTERS = {
54 '-', '_', '.', '!', '~', '*', '\'', '(', ')'
55 };
56
57 //also includes 0x00-0x1F and 0x7F
58 Character[] EXCLUDED_CHARACTERS = {
59 ' ', '<', '>', '#', '%', '\"'
60 };
61
62 Character[] UNWISE_CHARACTERS = {
63 '{', '}', '|', '\\', '^', '[', ']', '`'
64 };
65
66 /**
67 * Tests requesting special characters via a ClientProxy.
68 */
69 @Test
70 public void testEncodingCharacters() throws Exception
71 {
72 for (Character ch : RESERVED_CHARACTERS)
73 {
74 encodingCharacter(ch);
75 }
76 for (Character ch : UNRESERVED_CHARACTERS)
77 {
78 encodingCharacter(ch);
79 }
80 for (Character ch : EXCLUDED_CHARACTERS)
81 {
82 encodingCharacter(ch);
83 }
84 for (Character ch : UNWISE_CHARACTERS)
85 {
86 encodingCharacter(ch);
87 }
88 }
89
90 public void encodingCharacter(Character toTest)
91 {
92 String paramWithChar = "start" + toTest + "end";
93 System.out.println("*** " + paramWithChar);
94 Response returned = testClient.getPathParam(paramWithChar);
95 Assert.assertNotNull(returned);
96 Assert.assertEquals(returned.getStatus(), HttpURLConnection.HTTP_OK);
97 Assert.assertEquals(returned.readEntity(String.class), paramWithChar);
98 returned.close();
99 }
100
101 @Test
102 public void testPercent()
103 {
104 encodingCharacter('\\');
105 }
106
107 /**
108 * Tests requesting special characters via manual URL construction.
109 */
110 @Test
111 public void testViaDirectURI() throws Exception
112 {
113 for (Character ch : RESERVED_CHARACTERS)
114 {
115 viaDirectURI(ch);
116 }
117 for (Character ch : UNRESERVED_CHARACTERS)
118 {
119 viaDirectURI(ch);
120 }
121 for (Character ch : EXCLUDED_CHARACTERS)
122 {
123 viaDirectURI(ch);
124 }
125 for (Character ch : UNWISE_CHARACTERS)
126 {
127 viaDirectURI(ch);
128 }
129
130 }
131
132 @Test
133 public void decodeChineseInPath() throws Exception
134 {
135 String path = Encode.decodePath("/%E5%B9%B4%E5%81%87%E6%9C%9F/%E5%B9%B4%E5%81%87%E6%9C%9F");
136 System.out.println(path);
137 Assert.assertEquals("/\u5E74\u5047\u671F/\u5E74\u5047\u671F", path);
138 }
139
140 @Test
141 public void decodeWesternEuropeanCharsInPath() throws Exception
142 {
143 Assert.assertEquals("Gr\u00FC\u00DF Gott", Encode.decodePath("Gr%C3%BC%C3%9F%20Gott"));
144 Assert.assertEquals("D\u00E6lenenga Gr\u00FCnerl\u00F8kka", Encode.decodePath("D%C3%A6lenenga%20Gr%C3%BCnerl%C3%B8kka"));
145 Assert.assertEquals("\u00C4lv\u00E5s V\u00E4stra G\u00F6taland", Encode.decodePath("%C3%84lv%C3%A5s%20V%C3%A4stra%20G%C3%B6taland"));
146 }
147
148 public void viaDirectURI(Character toTest) throws Exception
149 {
150 System.out.println("*** testing character '" + toTest + "'");
151 String uriBase = "http://localhost:" + TestPortProvider.getPort() + "/test/path-param/";
152 String expected = "start" + toTest + "end";
153 String encoded = "start%" + Integer.toHexString(toTest).toUpperCase() + "end";
154 URI uri = URI.create(uriBase + encoded);
155
156 HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
157 connection.setRequestMethod("GET");
158 connection.setRequestProperty("accept", "text/plain");
159 InputStream is = connection.getInputStream();
160 Reader r = new InputStreamReader(is, "UTF-8");
161 StringBuffer buf = new StringBuffer();
162 char[] chars = new char[1024];
163 int charsRead;
164 while ((charsRead = r.read(chars)) != -1)
165 {
166 buf.append(chars, 0, charsRead);
167 }
168 r.close();
169 is.close();
170
171 Assert.assertEquals(buf.toString(), expected);
172 }
173
174 /**
175 * Test method for
176 * {@link org.jboss.resteasy.util.Encode#encodeQueryParam(String)}
177 * .
178 */
179 @Test
180 public void testEncodeQueryParam()
181 {
182 Assert.assertEquals("Test", Encode.encodeQueryParam("Test"));
183 }
184
185 @Test
186 public void testEncodeQueryParam_special()
187 {
188 Assert.assertEquals(".-%2B%2F%7C", Encode.encodeQueryParam(".-+/|"));
189 }
190
191 @Test
192 public void testEncodeQueryParam_scands() throws UnsupportedEncodingException
193 {
194 String input = "\u00E5\u00E4\u00F6\u00C5\u00C4\u00D6";
195 String expected = "%C3%A5%C3%A4%C3%B6%C3%85%C3%84%C3%96";
196 Assert.assertEquals(expected, Encode.encodeQueryParam(input));
197 }
198
199 @Test
200 public void testEncodeQueryParam_utf8_2byte() throws CharacterCodingException, UnsupportedEncodingException
201 {
202 StringBuilder sb = new StringBuilder();
203 for (int n = 0; n < 2047; n++)
204 {
205 sb.append((char) n);
206 }
207 String characters = sb.toString();
208 String encodedQueryParam = Encode.encodeQueryParam(characters);
209 String expected = "%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F+%21%22%23%24%25%26%27%28%29*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E?%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz{|}~%7F%C2%80%C2%81%C2%82%C2%83%C2%84%C2%85%C2%86%C2%87%C2%88%C2%89%C2%8A%C2%8B%C2%8C%C2%8D%C2%8E%C2%8F%C2%90%C2%91%C2%92%C2%93%C2%94%C2%95%C2%96%C2%97%C2%98%C2%99%C2%9A%C2%9B%C2%9C%C2%9D%C2%9E%C2%9F%C2%A0%C2%A1%C2%A2%C2%A3%C2%A4%C2%A5%C2%A6%C2%A7%C2%A8%C2%A9%C2%AA%C2%AB%C2%AC%C2%AD%C2%AE%C2%AF%C2%B0%C2%B1%C2%B2%C2%B3%C2%B4%C2%B5%C2%B6%C2%B7%C2%B8%C2%B9%C2%BA%C2%BB%C2%BC%C2%BD%C2%BE%C2%BF%C3%80%C3%81%C3%82%C3%83%C3%84%C3%85%C3%86%C3%87%C3%88%C3%89%C3%8A%C3%8B%C3%8C%C3%8D%C3%8E%C3%8F%C3%90%C3%91%C3%92%C3%93%C3%94%C3%95%C3%96%C3%97%C3%98%C3%99%C3%9A%C3%9B%C3%9C%C3%9D%C3%9E%C3%9F%C3%A0%C3%A1%C3%A2%C3%A3%C3%A4%C3%A5%C3%A6%C3%A7%C3%A8%C3%A9%C3%AA%C3%AB%C3%AC%C3%AD%C3%AE%C3%AF%C3%B0%C3%B1%C3%B2%C3%B3%C3%B4%C3%B5%C3%B6%C3%B7%C3%B8%C3%B9%C3%BA%C3%BB%C3%BC%C3%BD%C3%BE%C3%BF%C4%80%C4%81%C4%82%C4%83%C4%84%C4%85%C4%86%C4%87%C4%88%C4%89%C4%8A%C4%8B%C4%8C%C4%8D%C4%8E%C4%8F%C4%90%C4%91%C4%92%C4%93%C4%94%C4%95%C4%96%C4%97%C4%98%C4%99%C4%9A%C4%9B%C4%9C%C4%9D%C4%9E%C4%9F%C4%A0%C4%A1%C4%A2%C4%A3%C4%A4%C4%A5%C4%A6%C4%A7%C4%A8%C4%A9%C4%AA%C4%AB%C4%AC%C4%AD%C4%AE%C4%AF%C4%B0%C4%B1%C4%B2%C4%B3%C4%B4%C4%B5%C4%B6%C4%B7%C4%B8%C4%B9%C4%BA%C4%BB%C4%BC%C4%BD%C4%BE%C4%BF%C5%80%C5%81%C5%82%C5%83%C5%84%C5%85%C5%86%C5%87%C5%88%C5%89%C5%8A%C5%8B%C5%8C%C5%8D%C5%8E%C5%8F%C5%90%C5%91%C5%92%C5%93%C5%94%C5%95%C5%96%C5%97%C5%98%C5%99%C5%9A%C5%9B%C5%9C%C5%9D%C5%9E%C5%9F%C5%A0%C5%A1%C5%A2%C5%A3%C5%A4%C5%A5%C5%A6%C5%A7%C5%A8%C5%A9%C5%AA%C5%AB%C5%AC%C5%AD%C5%AE%C5%AF%C5%B0%C5%B1%C5%B2%C5%B3%C5%B4%C5%B5%C5%B6%C5%B7%C5%B8%C5%B9%C5%BA%C5%BB%C5%BC%C5%BD%C5%BE%C5%BF%C6%80%C6%81%C6%82%C6%83%C6%84%C6%85%C6%86%C6%87%C6%88%C6%89%C6%8A%C6%8B%C6%8C%C6%8D%C6%8E%C6%8F%C6%90%C6%91%C6%92%C6%93%C6%94%C6%95%C6%96%C6%97%C6%98%C6%99%C6%9A%C6%9B%C6%9C%C6%9D%C6%9E%C6%9F%C6%A0%C6%A1%C6%A2%C6%A3%C6%A4%C6%A5%C6%A6%C6%A7%C6%A8%C6%A9%C6%AA%C6%AB%C6%AC%C6%AD%C6%AE%C6%AF%C6%B0%C6%B1%C6%B2%C6%B3%C6%B4%C6%B5%C6%B6%C6%B7%C6%B8%C6%B9%C6%BA%C6%BB%C6%BC%C6%BD%C6%BE%C6%BF%C7%80%C7%81%C7%82%C7%83%C7%84%C7%85%C7%86%C7%87%C7%88%C7%89%C7%8A%C7%8B%C7%8C%C7%8D%C7%8E%C7%8F%C7%90%C7%91%C7%92%C7%93%C7%94%C7%95%C7%96%C7%97%C7%98%C7%99%C7%9A%C7%9B%C7%9C%C7%9D%C7%9E%C7%9F%C7%A0%C7%A1%C7%A2%C7%A3%C7%A4%C7%A5%C7%A6%C7%A7%C7%A8%C7%A9%C7%AA%C7%AB%C7%AC%C7%AD%C7%AE%C7%AF%C7%B0%C7%B1%C7%B2%C7%B3%C7%B4%C7%B5%C7%B6%C7%B7%C7%B8%C7%B9%C7%BA%C7%BB%C7%BC%C7%BD%C7%BE%C7%BF%C8%80%C8%81%C8%82%C8%83%C8%84%C8%85%C8%86%C8%87%C8%88%C8%89%C8%8A%C8%8B%C8%8C%C8%8D%C8%8E%C8%8F%C8%90%C8%91%C8%92%C8%93%C8%94%C8%95%C8%96%C8%97%C8%98%C8%99%C8%9A%C8%9B%C8%9C%C8%9D%C8%9E%C8%9F%C8%A0%C8%A1%C8%A2%C8%A3%C8%A4%C8%A5%C8%A6%C8%A7%C8%A8%C8%A9%C8%AA%C8%AB%C8%AC%C8%AD%C8%AE%C8%AF%C8%B0%C8%B1%C8%B2%C8%B3%C8%B4%C8%B5%C8%B6%C8%B7%C8%B8%C8%B9%C8%BA%C8%BB%C8%BC%C8%BD%C8%BE%C8%BF%C9%80%C9%81%C9%82%C9%83%C9%84%C9%85%C9%86%C9%87%C9%88%C9%89%C9%8A%C9%8B%C9%8C%C9%8D%C9%8E%C9%8F%C9%90%C9%91%C9%92%C9%93%C9%94%C9%95%C9%96%C9%97%C9%98%C9%99%C9%9A%C9%9B%C9%9C%C9%9D%C9%9E%C9%9F%C9%A0%C9%A1%C9%A2%C9%A3%C9%A4%C9%A5%C9%A6%C9%A7%C9%A8%C9%A9%C9%AA%C9%AB%C9%AC%C9%AD%C9%AE%C9%AF%C9%B0%C9%B1%C9%B2%C9%B3%C9%B4%C9%B5%C9%B6%C9%B7%C9%B8%C9%B9%C9%BA%C9%BB%C9%BC%C9%BD%C9%BE%C9%BF%CA%80%CA%81%CA%82%CA%83%CA%84%CA%85%CA%86%CA%87%CA%88%CA%89%CA%8A%CA%8B%CA%8C%CA%8D%CA%8E%CA%8F%CA%90%CA%91%CA%92%CA%93%CA%94%CA%95%CA%96%CA%97%CA%98%CA%99%CA%9A%CA%9B%CA%9C%CA%9D%CA%9E%CA%9F%CA%A0%CA%A1%CA%A2%CA%A3%CA%A4%CA%A5%CA%A6%CA%A7%CA%A8%CA%A9%CA%AA%CA%AB%CA%AC%CA%AD%CA%AE%CA%AF%CA%B0%CA%B1%CA%B2%CA%B3%CA%B4%CA%B5%CA%B6%CA%B7%CA%B8%CA%B9%CA%BA%CA%BB%CA%BC%CA%BD%CA%BE%CA%BF%CB%80%CB%81%CB%82%CB%83%CB%84%CB%85%CB%86%CB%87%CB%88%CB%89%CB%8A%CB%8B%CB%8C%CB%8D%CB%8E%CB%8F%CB%90%CB%91%CB%92%CB%93%CB%94%CB%95%CB%96%CB%97%CB%98%CB%99%CB%9A%CB%9B%CB%9C%CB%9D%CB%9E%CB%9F%CB%A0%CB%A1%CB%A2%CB%A3%CB%A4%CB%A5%CB%A6%CB%A7%CB%A8%CB%A9%CB%AA%CB%AB%CB%AC%CB%AD%CB%AE%CB%AF%CB%B0%CB%B1%CB%B2%CB%B3%CB%B4%CB%B5%CB%B6%CB%B7%CB%B8%CB%B9%CB%BA%CB%BB%CB%BC%CB%BD%CB%BE%CB%BF%CC%80%CC%81%CC%82%CC%83%CC%84%CC%85%CC%86%CC%87%CC%88%CC%89%CC%8A%CC%8B%CC%8C%CC%8D%CC%8E%CC%8F%CC%90%CC%91%CC%92%CC%93%CC%94%CC%95%CC%96%CC%97%CC%98%CC%99%CC%9A%CC%9B%CC%9C%CC%9D%CC%9E%CC%9F%CC%A0%CC%A1%CC%A2%CC%A3%CC%A4%CC%A5%CC%A6%CC%A7%CC%A8%CC%A9%CC%AA%CC%AB%CC%AC%CC%AD%CC%AE%CC%AF%CC%B0%CC%B1%CC%B2%CC%B3%CC%B4%CC%B5%CC%B6%CC%B7%CC%B8%CC%B9%CC%BA%CC%BB%CC%BC%CC%BD%CC%BE%CC%BF%CD%80%CD%81%CD%82%CD%83%CD%84%CD%85%CD%86%CD%87%CD%88%CD%89%CD%8A%CD%8B%CD%8C%CD%8D%CD%8E%CD%8F%CD%90%CD%91%CD%92%CD%93%CD%94%CD%95%CD%96%CD%97%CD%98%CD%99%CD%9A%CD%9B%CD%9C%CD%9D%CD%9E%CD%9F%CD%A0%CD%A1%CD%A2%CD%A3%CD%A4%CD%A5%CD%A6%CD%A7%CD%A8%CD%A9%CD%AA%CD%AB%CD%AC%CD%AD%CD%AE%CD%AF%CD%B0%CD%B1%CD%B2%CD%B3%CD%B4%CD%B5%CD%B6%CD%B7%CD%B8%CD%B9%CD%BA%CD%BB%CD%BC%CD%BD%CD%BE%CD%BF%CE%80%CE%81%CE%82%CE%83%CE%84%CE%85%CE%86%CE%87%CE%88%CE%89%CE%8A%CE%8B%CE%8C%CE%8D%CE%8E%CE%8F%CE%90%CE%91%CE%92%CE%93%CE%94%CE%95%CE%96%CE%97%CE%98%CE%99%CE%9A%CE%9B%CE%9C%CE%9D%CE%9E%CE%9F%CE%A0%CE%A1%CE%A2%CE%A3%CE%A4%CE%A5%CE%A6%CE%A7%CE%A8%CE%A9%CE%AA%CE%AB%CE%AC%CE%AD%CE%AE%CE%AF%CE%B0%CE%B1%CE%B2%CE%B3%CE%B4%CE%B5%CE%B6%CE%B7%CE%B8%CE%B9%CE%BA%CE%BB%CE%BC%CE%BD%CE%BE%CE%BF%CF%80%CF%81%CF%82%CF%83%CF%84%CF%85%CF%86%CF%87%CF%88%CF%89%CF%8A%CF%8B%CF%8C%CF%8D%CF%8E%CF%8F%CF%90%CF%91%CF%92%CF%93%CF%94%CF%95%CF%96%CF%97%CF%98%CF%99%CF%9A%CF%9B%CF%9C%CF%9D%CF%9E%CF%9F%CF%A0%CF%A1%CF%A2%CF%A3%CF%A4%CF%A5%CF%A6%CF%A7%CF%A8%CF%A9%CF%AA%CF%AB%CF%AC%CF%AD%CF%AE%CF%AF%CF%B0%CF%B1%CF%B2%CF%B3%CF%B4%CF%B5%CF%B6%CF%B7%CF%B8%CF%B9%CF%BA%CF%BB%CF%BC%CF%BD%CF%BE%CF%BF%D0%80%D0%81%D0%82%D0%83%D0%84%D0%85%D0%86%D0%87%D0%88%D0%89%D0%8A%D0%8B%D0%8C%D0%8D%D0%8E%D0%8F%D0%90%D0%91%D0%92%D0%93%D0%94%D0%95%D0%96%D0%97%D0%98%D0%99%D0%9A%D0%9B%D0%9C%D0%9D%D0%9E%D0%9F%D0%A0%D0%A1%D0%A2%D0%A3%D0%A4%D0%A5%D0%A6%D0%A7%D0%A8%D0%A9%D0%AA%D0%AB%D0%AC%D0%AD%D0%AE%D0%AF%D0%B0%D0%B1%D0%B2%D0%B3%D0%B4%D0%B5%D0%B6%D0%B7%D0%B8%D0%B9%D0%BA%D0%BB%D0%BC%D0%BD%D0%BE%D0%BF%D1%80%D1%81%D1%82%D1%83%D1%84%D1%85%D1%86%D1%87%D1%88%D1%89%D1%8A%D1%8B%D1%8C%D1%8D%D1%8E%D1%8F%D1%90%D1%91%D1%92%D1%93%D1%94%D1%95%D1%96%D1%97%D1%98%D1%99%D1%9A%D1%9B%D1%9C%D1%9D%D1%9E%D1%9F%D1%A0%D1%A1%D1%A2%D1%A3%D1%A4%D1%A5%D1%A6%D1%A7%D1%A8%D1%A9%D1%AA%D1%AB%D1%AC%D1%AD%D1%AE%D1%AF%D1%B0%D1%B1%D1%B2%D1%B3%D1%B4%D1%B5%D1%B6%D1%B7%D1%B8%D1%B9%D1%BA%D1%BB%D1%BC%D1%BD%D1%BE%D1%BF%D2%80%D2%81%D2%82%D2%83%D2%84%D2%85%D2%86%D2%87%D2%88%D2%89%D2%8A%D2%8B%D2%8C%D2%8D%D2%8E%D2%8F%D2%90%D2%91%D2%92%D2%93%D2%94%D2%95%D2%96%D2%97%D2%98%D2%99%D2%9A%D2%9B%D2%9C%D2%9D%D2%9E%D2%9F%D2%A0%D2%A1%D2%A2%D2%A3%D2%A4%D2%A5%D2%A6%D2%A7%D2%A8%D2%A9%D2%AA%D2%AB%D2%AC%D2%AD%D2%AE%D2%AF%D2%B0%D2%B1%D2%B2%D2%B3%D2%B4%D2%B5%D2%B6%D2%B7%D2%B8%D2%B9%D2%BA%D2%BB%D2%BC%D2%BD%D2%BE%D2%BF%D3%80%D3%81%D3%82%D3%83%D3%84%D3%85%D3%86%D3%87%D3%88%D3%89%D3%8A%D3%8B%D3%8C%D3%8D%D3%8E%D3%8F%D3%90%D3%91%D3%92%D3%93%D3%94%D3%95%D3%96%D3%97%D3%98%D3%99%D3%9A%D3%9B%D3%9C%D3%9D%D3%9E%D3%9F%D3%A0%D3%A1%D3%A2%D3%A3%D3%A4%D3%A5%D3%A6%D3%A7%D3%A8%D3%A9%D3%AA%D3%AB%D3%AC%D3%AD%D3%AE%D3%AF%D3%B0%D3%B1%D3%B2%D3%B3%D3%B4%D3%B5%D3%B6%D3%B7%D3%B8%D3%B9%D3%BA%D3%BB%D3%BC%D3%BD%D3%BE%D3%BF%D4%80%D4%81%D4%82%D4%83%D4%84%D4%85%D4%86%D4%87%D4%88%D4%89%D4%8A%D4%8B%D4%8C%D4%8D%D4%8E%D4%8F%D4%90%D4%91%D4%92%D4%93%D4%94%D4%95%D4%96%D4%97%D4%98%D4%99%D4%9A%D4%9B%D4%9C%D4%9D%D4%9E%D4%9F%D4%A0%D4%A1%D4%A2%D4%A3%D4%A4%D4%A5%D4%A6%D4%A7%D4%A8%D4%A9%D4%AA%D4%AB%D4%AC%D4%AD%D4%AE%D4%AF%D4%B0%D4%B1%D4%B2%D4%B3%D4%B4%D4%B5%D4%B6%D4%B7%D4%B8%D4%B9%D4%BA%D4%BB%D4%BC%D4%BD%D4%BE%D4%BF%D5%80%D5%81%D5%82%D5%83%D5%84%D5%85%D5%86%D5%87%D5%88%D5%89%D5%8A%D5%8B%D5%8C%D5%8D%D5%8E%D5%8F%D5%90%D5%91%D5%92%D5%93%D5%94%D5%95%D5%96%D5%97%D5%98%D5%99%D5%9A%D5%9B%D5%9C%D5%9D%D5%9E%D5%9F%D5%A0%D5%A1%D5%A2%D5%A3%D5%A4%D5%A5%D5%A6%D5%A7%D5%A8%D5%A9%D5%AA%D5%AB%D5%AC%D5%AD%D5%AE%D5%AF%D5%B0%D5%B1%D5%B2%D5%B3%D5%B4%D5%B5%D5%B6%D5%B7%D5%B8%D5%B9%D5%BA%D5%BB%D5%BC%D5%BD%D5%BE%D5%BF%D6%80%D6%81%D6%82%D6%83%D6%84%D6%85%D6%86%D6%87%D6%88%D6%89%D6%8A%D6%8B%D6%8C%D6%8D%D6%8E%D6%8F%D6%90%D6%91%D6%92%D6%93%D6%94%D6%95%D6%96%D6%97%D6%98%D6%99%D6%9A%D6%9B%D6%9C%D6%9D%D6%9E%D6%9F%D6%A0%D6%A1%D6%A2%D6%A3%D6%A4%D6%A5%D6%A6%D6%A7%D6%A8%D6%A9%D6%AA%D6%AB%D6%AC%D6%AD%D6%AE%D6%AF%D6%B0%D6%B1%D6%B2%D6%B3%D6%B4%D6%B5%D6%B6%D6%B7%D6%B8%D6%B9%D6%BA%D6%BB%D6%BC%D6%BD%D6%BE%D6%BF%D7%80%D7%81%D7%82%D7%83%D7%84%D7%85%D7%86%D7%87%D7%88%D7%89%D7%8A%D7%8B%D7%8C%D7%8D%D7%8E%D7%8F%D7%90%D7%91%D7%92%D7%93%D7%94%D7%95%D7%96%D7%97%D7%98%D7%99%D7%9A%D7%9B%D7%9C%D7%9D%D7%9E%D7%9F%D7%A0%D7%A1%D7%A2%D7%A3%D7%A4%D7%A5%D7%A6%D7%A7%D7%A8%D7%A9%D7%AA%D7%AB%D7%AC%D7%AD%D7%AE%D7%AF%D7%B0%D7%B1%D7%B2%D7%B3%D7%B4%D7%B5%D7%B6%D7%B7%D7%B8%D7%B9%D7%BA%D7%BB%D7%BC%D7%BD%D7%BE%D7%BF%D8%80%D8%81%D8%82%D8%83%D8%84%D8%85%D8%86%D8%87%D8%88%D8%89%D8%8A%D8%8B%D8%8C%D8%8D%D8%8E%D8%8F%D8%90%D8%91%D8%92%D8%93%D8%94%D8%95%D8%96%D8%97%D8%98%D8%99%D8%9A%D8%9B%D8%9C%D8%9D%D8%9E%D8%9F%D8%A0%D8%A1%D8%A2%D8%A3%D8%A4%D8%A5%D8%A6%D8%A7%D8%A8%D8%A9%D8%AA%D8%AB%D8%AC%D8%AD%D8%AE%D8%AF%D8%B0%D8%B1%D8%B2%D8%B3%D8%B4%D8%B5%D8%B6%D8%B7%D8%B8%D8%B9%D8%BA%D8%BB%D8%BC%D8%BD%D8%BE%D8%BF%D9%80%D9%81%D9%82%D9%83%D9%84%D9%85%D9%86%D9%87%D9%88%D9%89%D9%8A%D9%8B%D9%8C%D9%8D%D9%8E%D9%8F%D9%90%D9%91%D9%92%D9%93%D9%94%D9%95%D9%96%D9%97%D9%98%D9%99%D9%9A%D9%9B%D9%9C%D9%9D%D9%9E%D9%9F%D9%A0%D9%A1%D9%A2%D9%A3%D9%A4%D9%A5%D9%A6%D9%A7%D9%A8%D9%A9%D9%AA%D9%AB%D9%AC%D9%AD%D9%AE%D9%AF%D9%B0%D9%B1%D9%B2%D9%B3%D9%B4%D9%B5%D9%B6%D9%B7%D9%B8%D9%B9%D9%BA%D9%BB%D9%BC%D9%BD%D9%BE%D9%BF%DA%80%DA%81%DA%82%DA%83%DA%84%DA%85%DA%86%DA%87%DA%88%DA%89%DA%8A%DA%8B%DA%8C%DA%8D%DA%8E%DA%8F%DA%90%DA%91%DA%92%DA%93%DA%94%DA%95%DA%96%DA%97%DA%98%DA%99%DA%9A%DA%9B%DA%9C%DA%9D%DA%9E%DA%9F%DA%A0%DA%A1%DA%A2%DA%A3%DA%A4%DA%A5%DA%A6%DA%A7%DA%A8%DA%A9%DA%AA%DA%AB%DA%AC%DA%AD%DA%AE%DA%AF%DA%B0%DA%B1%DA%B2%DA%B3%DA%B4%DA%B5%DA%B6%DA%B7%DA%B8%DA%B9%DA%BA%DA%BB%DA%BC%DA%BD%DA%BE%DA%BF%DB%80%DB%81%DB%82%DB%83%DB%84%DB%85%DB%86%DB%87%DB%88%DB%89%DB%8A%DB%8B%DB%8C%DB%8D%DB%8E%DB%8F%DB%90%DB%91%DB%92%DB%93%DB%94%DB%95%DB%96%DB%97%DB%98%DB%99%DB%9A%DB%9B%DB%9C%DB%9D%DB%9E%DB%9F%DB%A0%DB%A1%DB%A2%DB%A3%DB%A4%DB%A5%DB%A6%DB%A7%DB%A8%DB%A9%DB%AA%DB%AB%DB%AC%DB%AD%DB%AE%DB%AF%DB%B0%DB%B1%DB%B2%DB%B3%DB%B4%DB%B5%DB%B6%DB%B7%DB%B8%DB%B9%DB%BA%DB%BB%DB%BC%DB%BD%DB%BE%DB%BF%DC%80%DC%81%DC%82%DC%83%DC%84%DC%85%DC%86%DC%87%DC%88%DC%89%DC%8A%DC%8B%DC%8C%DC%8D%DC%8E%DC%8F%DC%90%DC%91%DC%92%DC%93%DC%94%DC%95%DC%96%DC%97%DC%98%DC%99%DC%9A%DC%9B%DC%9C%DC%9D%DC%9E%DC%9F%DC%A0%DC%A1%DC%A2%DC%A3%DC%A4%DC%A5%DC%A6%DC%A7%DC%A8%DC%A9%DC%AA%DC%AB%DC%AC%DC%AD%DC%AE%DC%AF%DC%B0%DC%B1%DC%B2%DC%B3%DC%B4%DC%B5%DC%B6%DC%B7%DC%B8%DC%B9%DC%BA%DC%BB%DC%BC%DC%BD%DC%BE%DC%BF%DD%80%DD%81%DD%82%DD%83%DD%84%DD%85%DD%86%DD%87%DD%88%DD%89%DD%8A%DD%8B%DD%8C%DD%8D%DD%8E%DD%8F%DD%90%DD%91%DD%92%DD%93%DD%94%DD%95%DD%96%DD%97%DD%98%DD%99%DD%9A%DD%9B%DD%9C%DD%9D%DD%9E%DD%9F%DD%A0%DD%A1%DD%A2%DD%A3%DD%A4%DD%A5%DD%A6%DD%A7%DD%A8%DD%A9%DD%AA%DD%AB%DD%AC%DD%AD%DD%AE%DD%AF%DD%B0%DD%B1%DD%B2%DD%B3%DD%B4%DD%B5%DD%B6%DD%B7%DD%B8%DD%B9%DD%BA%DD%BB%DD%BC%DD%BD%DD%BE%DD%BF%DE%80%DE%81%DE%82%DE%83%DE%84%DE%85%DE%86%DE%87%DE%88%DE%89%DE%8A%DE%8B%DE%8C%DE%8D%DE%8E%DE%8F%DE%90%DE%91%DE%92%DE%93%DE%94%DE%95%DE%96%DE%97%DE%98%DE%99%DE%9A%DE%9B%DE%9C%DE%9D%DE%9E%DE%9F%DE%A0%DE%A1%DE%A2%DE%A3%DE%A4%DE%A5%DE%A6%DE%A7%DE%A8%DE%A9%DE%AA%DE%AB%DE%AC%DE%AD%DE%AE%DE%AF%DE%B0%DE%B1%DE%B2%DE%B3%DE%B4%DE%B5%DE%B6%DE%B7%DE%B8%DE%B9%DE%BA%DE%BB%DE%BC%DE%BD%DE%BE%DE%BF%DF%80%DF%81%DF%82%DF%83%DF%84%DF%85%DF%86%DF%87%DF%88%DF%89%DF%8A%DF%8B%DF%8C%DF%8D%DF%8E%DF%8F%DF%90%DF%91%DF%92%DF%93%DF%94%DF%95%DF%96%DF%97%DF%98%DF%99%DF%9A%DF%9B%DF%9C%DF%9D%DF%9E%DF%9F%DF%A0%DF%A1%DF%A2%DF%A3%DF%A4%DF%A5%DF%A6%DF%A7%DF%A8%DF%A9%DF%AA%DF%AB%DF%AC%DF%AD%DF%AE%DF%AF%DF%B0%DF%B1%DF%B2%DF%B3%DF%B4%DF%B5%DF%B6%DF%B7%DF%B8%DF%B9%DF%BA%DF%BB%DF%BC%DF%BD%DF%BE";
210 Assert.assertEquals(expected, encodedQueryParam);
211 }
212
213 public void testPathParamWithDoublePercent()
214 {
215 String paramWithDoublePercent = "start%%end";
216 System.out.println("*** " + paramWithDoublePercent);
217 Response returned = testClient.getPathParam(paramWithDoublePercent);
218 Assert.assertNotNull(returned);
219 Assert.assertEquals(HttpURLConnection.HTTP_OK, returned.getStatus());
220 Assert.assertEquals(paramWithDoublePercent, returned.readEntity(String.class));
221 returned.close();
222 }
223
224 @Test
225 public void testPathParamWithBraces()
226 {
227 String paramWithBraces = "start{param}end";
228 System.out.println("*** " + paramWithBraces);
229 Response returned = testClient.getPathParam(paramWithBraces);
230 Assert.assertNotNull(returned);
231 Assert.assertEquals(HttpURLConnection.HTTP_OK, returned.getStatus());
232 Assert.assertEquals(paramWithBraces, returned.readEntity(String.class));
233 returned.close();
234 }
235
236 @Test
237 public void testPathParamWithLifePercentDeath()
238 {
239 String paramWithLifePercentDeath = "life%death";
240 System.out.println("*** " + paramWithLifePercentDeath);
241 Response returned = testClient.getPathParam(paramWithLifePercentDeath);
242 Assert.assertNotNull(returned);
243 Assert.assertEquals(HttpURLConnection.HTTP_OK, returned.getStatus());
244 Assert.assertEquals(paramWithLifePercentDeath, returned.readEntity(String.class));
245 returned.close();
246 }
247
248 @Test
249 public void testQueryParamWithDoublePercent()
250 {
251 String paramWithDoublePercent = "start%%end";
252 System.out.println("*** " + paramWithDoublePercent);
253 Response returned = testClient.getQueryParam(paramWithDoublePercent);
254 Assert.assertNotNull(returned);
255 Assert.assertEquals(HttpURLConnection.HTTP_OK, returned.getStatus());
256 Assert.assertEquals(paramWithDoublePercent, returned.readEntity(String.class));
257 returned.close();
258 }
259
260 @Test
261 public void testQueryParamWithBraces()
262 {
263 String paramWithBraces = "start{param}end";
264 System.out.println("*** " + paramWithBraces);
265 Response returned = testClient.getQueryParam(paramWithBraces);
266 Assert.assertNotNull(returned);
267 Assert.assertEquals(HttpURLConnection.HTTP_OK, returned.getStatus());
268 Assert.assertEquals(paramWithBraces, returned.readEntity(String.class));
269 returned.close();
270 }
271
272 @Test
273 public void testQueryParamWithLifePercentDeath()
274 {
275 String paramWithLifePercentDeath = "life%death";
276 System.out.println("*** " + paramWithLifePercentDeath);
277 Response returned = testClient.getQueryParam(paramWithLifePercentDeath);
278 Assert.assertNotNull(returned);
279 Assert.assertEquals(HttpURLConnection.HTTP_OK, returned.getStatus());
280 Assert.assertEquals(paramWithLifePercentDeath, returned.readEntity(String.class));
281 returned.close();
282 }
283
284 @Test
285 public void testEncodeNonCodes()
286 {
287 Assert.assertEquals("", Encode.encodeNonCodes(""));
288 Assert.assertEquals("a simple string", Encode.encodeNonCodes("a simple string"));
289 Assert.assertEquals("%25", Encode.encodeNonCodes("%"));
290 Assert.assertEquals("%25%25%25%25", Encode.encodeNonCodes("%%%%"));
291 Assert.assertEquals("%25%25", Encode.encodeNonCodes("%%25"));
292 Assert.assertEquals("%25a%25", Encode.encodeNonCodes("%a%25"));
293 Assert.assertEquals("a%25b", Encode.encodeNonCodes("a%b"));
294 Assert.assertEquals("a%25b", Encode.encodeNonCodes("a%25b"));
295 Assert.assertEquals("a%25%25%25%25b%25%25%25%25c", Encode.encodeNonCodes("a%%%%b%%25%%c"));
296 }
297
298 }
0 package org.jboss.resteasy.test.nextgen.encoding;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.QueryParam;
7
8 @Path("/test")
9 public class MyTestResource
10 {
11 @GET
12 @Produces("text/plain")
13 @Path("/path-param/{pathParam}")
14 public String getPathParam(@PathParam("pathParam") String pathParam)
15 {
16 return pathParam;
17 }
18
19
20 @GET
21 @Produces("text/plain")
22 @Path("/query-param")
23 public String getQueryParam(@QueryParam("queryParam") String queryParam)
24 {
25 return queryParam;
26 }
27 }
0 package org.jboss.resteasy.test.nextgen.encoding;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.QueryParam;
7 import javax.ws.rs.core.Response;
8
9 @Path("/test")
10 public interface TestClient
11 {
12 @GET
13 @Produces("text/plain")
14 @Path("/path-param/{pathParam}")
15 public Response getPathParam(@PathParam("pathParam") String pathParam);
16
17
18
19 @GET
20 @Produces("text/plain")
21 @Path("/query-param")
22 public Response getQueryParam(@QueryParam("queryParam") String queryParam);
23 }
0 package org.jboss.resteasy.test.nextgen.finegrain;
1
2 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
3 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
4 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
5 import org.jboss.resteasy.test.BaseResourceTest;
6 import org.junit.Assert;
7 import org.junit.BeforeClass;
8 import org.junit.Test;
9
10 import javax.ws.rs.GET;
11 import javax.ws.rs.Path;
12 import javax.ws.rs.Produces;
13 import javax.ws.rs.client.Invocation;
14 import javax.ws.rs.core.Context;
15 import javax.ws.rs.core.HttpHeaders;
16 import java.util.List;
17 import java.util.Locale;
18
19 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
20
21 /**
22 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
23 * @version $Revision: 1 $
24 */
25 public class AcceptLanguagesTest extends BaseResourceTest
26 {
27 @Path("/lang")
28 public static class Accept
29 {
30
31 @GET
32 @Produces("text/plain")
33 public String get(@Context HttpHeaders headers)
34 {
35 // en-US;q=0,en;q=0.8,de-AT,de;q=0.9
36 List<Locale> accepts = headers.getAcceptableLanguages();
37 for (Locale locale : accepts)
38 {
39 System.out.println(locale);
40 }
41 Assert.assertEquals(accepts.get(0).toString(), "de_AT");
42 Assert.assertEquals(accepts.get(1).toString(), "de");
43 Assert.assertEquals(accepts.get(2).toString(), "en");
44 Assert.assertEquals(accepts.get(3).toString(), "en_US");
45 return "hello";
46 }
47 }
48
49 @BeforeClass
50 public static void setUp() throws Exception
51 {
52 deployment.getRegistry().addPerRequestResource(Accept.class);
53 }
54
55 @Test
56 public void testMe() throws Exception
57 {
58 ResteasyClient client = new ResteasyClientBuilder().build();
59 ResteasyWebTarget target = client.target(generateURL("/lang"));
60 Invocation.Builder request = target.request().header("Accept-Language", "en-US;q=0,en;q=0.8,de-AT,de;q=0.9");
61 Assert.assertEquals(request.get().getStatus(), 200);
62 client.close();
63
64 }
65
66 }
0 package org.jboss.resteasy.test.nextgen.finegrain.client;
1
2 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
3 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
4 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
5 import org.jboss.resteasy.spi.ResteasyDeployment;
6 import org.jboss.resteasy.test.EmbeddedContainer;
7 import org.jboss.resteasy.util.ReadFromStream;
8 import org.junit.AfterClass;
9 import org.junit.Assert;
10 import org.junit.BeforeClass;
11 import org.junit.Test;
12
13 import javax.ws.rs.Consumes;
14 import javax.ws.rs.GET;
15 import javax.ws.rs.POST;
16 import javax.ws.rs.Path;
17 import javax.ws.rs.Produces;
18 import javax.ws.rs.core.Response;
19 import java.io.ByteArrayInputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22
23 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
24
25 /**
26 * Simple smoke test
27 *
28 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
29 * @version $Revision: 1 $
30 */
31 @SuppressWarnings("unchecked")
32 public class InputStreamResourceTest
33 {
34
35 private static ResteasyDeployment deployment;
36
37 @Path("/inputStream")
38 @Produces("text/plain")
39 @Consumes("text/plain")
40 public interface Client
41 {
42 @GET
43 String getAsString();
44
45 @GET
46 Response getAsInputStream();
47
48 @POST
49 Response postInputStream(InputStream is);
50
51 @POST
52 Response postString(String s);
53 }
54
55 @Path("/inputStream")
56 public static class Service
57 {
58 String result = "hello";
59
60 @GET
61 @Produces("text/plain")
62 public InputStream get()
63 {
64 return new ByteArrayInputStream(result.getBytes());
65 }
66
67 @POST
68 @Consumes("text/plain")
69 public void post(InputStream is) throws IOException
70 {
71 result = new String(ReadFromStream.readFromStream(1024, is));
72 }
73
74 }
75
76 @BeforeClass
77 public static void before() throws Exception
78 {
79 deployment = EmbeddedContainer.start();
80 deployment.getRegistry().addSingletonResource(new Service());
81 }
82
83 @AfterClass
84 public static void after() throws Exception
85 {
86 EmbeddedContainer.stop();
87 }
88
89 @Test
90 public void testClientResponse() throws Exception
91 {
92 ResteasyClient resteasyClient = new ResteasyClientBuilder().build();
93 Client client = ProxyBuilder.builder(Client.class, resteasyClient.target(generateBaseUrl())).build();
94
95 Assert.assertEquals("hello", client.getAsString());
96 Response is = client.getAsInputStream();
97 Assert.assertEquals("hello", new String(ReadFromStream.readFromStream(
98 1024, is.readEntity(InputStream.class))));
99 is.close();
100 client.postString("new value");
101 Assert.assertEquals("new value", client.getAsString());
102 client.postInputStream(new ByteArrayInputStream("new value 2".getBytes()));
103 Assert.assertEquals("new value 2", client.getAsString());
104 resteasyClient.close();
105
106 }
107 }
0 package org.jboss.resteasy.test.nextgen.interceptors;
1
2 import org.apache.http.HttpResponse;
3 import org.apache.http.client.HttpClient;
4 import org.apache.http.client.methods.HttpGet;
5 import org.apache.http.impl.client.DefaultHttpClient;
6 import org.apache.http.util.EntityUtils;
7 import org.jboss.resteasy.annotations.GZIP;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
11 import org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPInterceptor;
12 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor;
13 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor;
14 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
15 import org.jboss.resteasy.test.BaseResourceTest;
16 import org.jboss.resteasy.test.TestPortProvider;
17 import org.jboss.resteasy.spi.ResteasyProviderFactory;
18 import org.jboss.resteasy.util.ReadFromStream;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22
23 import javax.ws.rs.Consumes;
24 import javax.ws.rs.GET;
25 import javax.ws.rs.PUT;
26 import javax.ws.rs.Path;
27 import javax.ws.rs.Produces;
28 import javax.ws.rs.WebApplicationException;
29 import javax.ws.rs.client.Entity;
30 import javax.ws.rs.client.WebTarget;
31 import javax.ws.rs.core.Context;
32 import javax.ws.rs.core.HttpHeaders;
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.core.StreamingOutput;
35 import java.io.ByteArrayInputStream;
36 import java.io.ByteArrayOutputStream;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.OutputStream;
40
41 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
42
43 /**
44 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
45 * @version $Revision: 1 $
46 */
47 public class GzipTest extends BaseResourceTest
48 {
49
50 @Path("/")
51 public static interface IGZIP
52 {
53 @GET
54 @Path("text")
55 @Produces("text/plain")
56 public String getText();
57
58 @GET
59 @Path("encoded/text")
60 @GZIP
61 public String getGzipText();
62
63 @GET
64 @Path("encoded/text/error")
65 @GZIP
66 public String getGzipErrorText();
67
68 }
69
70 @Path("/")
71 public static class GZIPService
72 {
73 @GET
74 @Path("text")
75 @Produces("text/plain")
76 public Response getText(@Context HttpHeaders headers)
77 {
78 /* Can't test this anymore because TCK expects that no accept encoding is set by default
79 String acceptEncoding = headers.getRequestHeaders().getFirst(HttpHeaders.ACCEPT_ENCODING);
80 System.out.println(acceptEncoding);
81 Assert.assertEquals("gzip, deflate", acceptEncoding);
82 */
83 return Response.ok("HELLO WORLD").header("Content-Encoding", "gzip").build();
84 }
85
86 @GET
87 @Path("encoded/text")
88 @GZIP
89 public String getGzipText()
90 {
91 return "HELLO WORLD";
92 }
93
94 @GET
95 @Path("bytes")
96 @GZIP
97 @Produces("text/plain")
98 public byte[] getBytes()
99 {
100 return "HELLO WORLD".getBytes();
101 }
102
103 @GET
104 @Path("error")
105 @GZIP
106 @Produces({"application/json;charset=UTF-8"})
107 public StreamingOutput getTest()
108 {
109 return new StreamingOutput()
110 {
111 @Override
112 public void write(OutputStream outputStream) throws IOException, WebApplicationException
113 {
114 throw new WebApplicationException(405);
115 }
116 };
117 }
118
119 @GET
120 @Path("encoded/text/error")
121 @GZIP
122 public String getGzipErrorText()
123 {
124 throw new WebApplicationException(
125 Response.status(500).entity("Hello").type("text/plain").build()
126 );
127 }
128
129 @PUT
130 @Consumes("text/plain")
131 @Path("stream")
132 public void putStream(InputStream is) throws Exception
133 {
134 byte[] bytes = ReadFromStream.readFromStream(1024, is);
135 String str = new String(bytes);
136 Assert.assertEquals("hello world", str);
137 }
138
139 @PUT
140 @Consumes("text/plain")
141 @Path("text")
142 public void putText(String text) throws Exception
143 {
144 Assert.assertEquals("hello world", text);
145 }
146 }
147
148 @Before
149 public void setUp() throws Exception
150 {
151 ResteasyProviderFactory.getInstance().registerProvider(AcceptEncodingGZIPInterceptor.class);
152 ResteasyProviderFactory.getInstance().registerProvider(GZIPEncodingInterceptor.class);
153 ResteasyProviderFactory.getInstance().registerProvider(GZIPDecodingInterceptor.class);
154 addPerRequestResource(GZIPService.class);
155 }
156
157 @Test
158 public void testRawStreams() throws Exception
159 {
160 ByteArrayOutputStream baos = new ByteArrayOutputStream();
161 GZIPEncodingInterceptor.EndableGZIPOutputStream os = new GZIPEncodingInterceptor.EndableGZIPOutputStream(baos);
162 os.write("hello world".getBytes());
163 os.finish();
164 os.close();
165
166 byte[] bytes1 = baos.toByteArray();
167 System.out.println(bytes1.length);
168 System.out.println(new String(bytes1));
169 ByteArrayInputStream bis = new ByteArrayInputStream(bytes1);
170 GZIPDecodingInterceptor.FinishableGZIPInputStream is = new GZIPDecodingInterceptor.FinishableGZIPInputStream(bis);
171 byte[] bytes = ReadFromStream.readFromStream(1024, is);
172 is.finish();
173 String str = new String(bytes);
174 Assert.assertEquals("hello world", str);
175
176
177 }
178
179
180 @Test
181 public void testProxy() throws Exception
182 {
183 ResteasyClient client = getClient();
184 ResteasyWebTarget target = client.target(generateBaseUrl());
185 IGZIP proxy = target.proxy(IGZIP.class);
186 Assert.assertEquals("HELLO WORLD", proxy.getText());
187 Assert.assertEquals("HELLO WORLD", proxy.getGzipText());
188
189 // resteasy-651
190 try
191 {
192 String error = proxy.getGzipErrorText();
193 Assert.fail("unreachable");
194 }
195 catch (WebApplicationException failure)
196 {
197 Assert.assertEquals(500, failure.getResponse().getStatus());
198 String txt = (String) failure.getResponse().readEntity(String.class);
199 Assert.assertEquals("Hello", txt);
200 }
201 finally
202 {
203 client.close();
204 }
205 }
206
207 /**
208 * RESTEASY-692
209 *
210 * @throws Exception
211 */
212 @Test
213 public void testContentLength() throws Exception
214 {
215 ResteasyClient client = getClient();
216 {
217 WebTarget target = client.target(TestPortProvider.generateURL("/text"));
218 Response response = target.request().get();
219 Assert.assertEquals("HELLO WORLD", response.readEntity(String.class));
220 String cl = response.getHeaderString("Content-Length");
221 if (cl != null)
222 {
223 // make sure the content length is greater than 11 because this will be a gzipped encoding
224 Assert.assertTrue(response.getLength() > 11);
225 }
226 }
227 {
228 WebTarget target = client.target(TestPortProvider.generateURL("/bytes"));
229 Response response = target.request().acceptEncoding("gzip").get();
230 String cl = response.getHeaderString("Content-Length");
231 if (cl != null)
232 {
233 // make sure the content length is greater than 11 because this will be a gzipped encoding
234 int i = response.getLength();
235 System.out.println("***");
236 System.out.println("Content-Length: " + i);
237 System.out.println("***");
238 Assert.assertTrue(i > 11);
239 }
240 Assert.assertEquals("HELLO WORLD", response.readEntity(String.class));
241 }
242 client.close();
243 }
244
245 @Test
246 public void testRequestError() throws Exception
247 {
248 ResteasyClient client = getClient();
249 WebTarget target = client.target(TestPortProvider.generateURL("/error"));
250 Response response = target.request().get();
251 Assert.assertEquals(405, response.getStatus());
252 client.close();
253
254 }
255
256 @Test
257 public void testPutStream() throws Exception
258 {
259 ResteasyClient client = getClient();
260 WebTarget target = client.target(TestPortProvider.generateURL("/stream"));
261 Response res = target.request().header("Content-Encoding", "gzip").put(Entity.text("hello world"));
262 Assert.assertEquals(204, res.getStatus());
263 client.close();
264 }
265
266 @Test
267 public void testPutText() throws Exception
268 {
269 ResteasyClient client = getClient();
270 WebTarget target = client.target(TestPortProvider.generateURL("/text"));
271 Response res = target.request().header("Content-Encoding", "gzip").put(Entity.text("hello world"));
272 Assert.assertEquals(204, res.getStatus());
273 client.close();
274 }
275
276 @Test
277 public void testRequest() throws Exception
278 {
279 ResteasyClient client = getClient();
280 WebTarget target = client.target(TestPortProvider.generateURL("/text"));
281 String val = target.request().get(String.class);
282 Assert.assertEquals("HELLO WORLD", val);
283 client.close();
284
285 }
286
287 @Test
288 public void testRequest2() throws Exception
289 {
290 ResteasyClient client = getClient();
291 WebTarget target = client.target(TestPortProvider.generateURL("/encoded/text"));
292 Response response = target.request().get();
293 Assert.assertEquals("HELLO WORLD", response.readEntity(String.class));
294 client.close();
295
296 }
297
298 @Test
299 public void testWasZipped() throws Exception
300 {
301 // test that it was zipped by running it through Apache HTTP Client which does not automatically unzip
302
303 HttpClient client = new DefaultHttpClient();
304 {
305 HttpGet get = new HttpGet(TestPortProvider.generateURL("/encoded/text"));
306 get.addHeader("Accept-Encoding", "gzip, deflate");
307 HttpResponse response = client.execute(get);
308 Assert.assertEquals(200, response.getStatusLine().getStatusCode());
309 Assert.assertEquals("gzip", response.getFirstHeader("Content-Encoding").getValue());
310
311 // test that it is actually zipped
312 String entity = EntityUtils.toString(response.getEntity());
313 System.out.println(entity);
314 Assert.assertNotSame(entity, "HELLO WORLD");
315 }
316
317
318 {
319 HttpGet get = new HttpGet(TestPortProvider.generateURL("/text"));
320 get.addHeader("Accept-Encoding", "gzip, deflate");
321 HttpResponse response = client.execute(get);
322 Assert.assertEquals(200, response.getStatusLine().getStatusCode());
323 Assert.assertEquals("gzip", response.getFirstHeader("Content-Encoding").getValue());
324
325 // test that it is actually zipped
326 String entity = EntityUtils.toString(response.getEntity());
327 Assert.assertNotSame(entity, "HELLO WORLD");
328 }
329 client.getConnectionManager().shutdown();
330 }
331
332 @Test
333 public void testWithoutAcceptEncoding() throws Exception
334 {
335 // test that if there is no accept-encoding: gzip header that result isn't encoded
336
337 HttpClient client = new DefaultHttpClient();
338 HttpGet get = new HttpGet(TestPortProvider.generateURL("/encoded/text"));
339 HttpResponse response = client.execute(get);
340 Assert.assertEquals(200, response.getStatusLine().getStatusCode());
341 Assert.assertNull(response.getFirstHeader("Content-Encoding"));
342
343 // test that it is actually zipped
344 String entity = EntityUtils.toString(response.getEntity());
345 Assert.assertEquals(entity, "HELLO WORLD");
346 client.getConnectionManager().shutdown();
347
348 }
349
350 private ResteasyClient getClient()
351 {
352 // register gzip explicitly
353 ResteasyProviderFactory rpf = new ResteasyProviderFactory();
354 RegisterBuiltin.register(rpf);
355 rpf.registerProvider(AcceptEncodingGZIPInterceptor.class);
356 rpf.registerProvider(GZIPEncodingInterceptor.class);
357 rpf.registerProvider(GZIPDecodingInterceptor.class);
358 return new ResteasyClientBuilder().providerFactory(rpf).build();
359 }
360
361 }
0 package org.jboss.resteasy.test.nextgen.proxy;
1
2 import static org.junit.Assert.assertEquals;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.client.Client;
8 import javax.ws.rs.client.ClientBuilder;
9
10 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
11 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
12 import org.jboss.resteasy.client.jaxrs.internal.proxy.ResteasyClientProxy;
13 import org.jboss.resteasy.core.Dispatcher;
14 import org.jboss.resteasy.spi.ResteasyDeployment;
15 import org.jboss.resteasy.test.EmbeddedContainer;
16 import org.junit.AfterClass;
17 import org.junit.BeforeClass;
18 import org.junit.Test;
19
20 /**
21 * RESTEASY-1332 / RESTEASY-1250
22 *
23 * @author <a href="mailto:ron.sigal@jboss.com">Ron Sigal</a>
24 * @date
25 */
26 public class TestProxyCasting
27 {
28 private static ResteasyDeployment deployment;
29 private static Dispatcher dispatcher;
30 private static ResteasyWebTarget target;
31
32 public static interface Nothing
33 {
34 }
35
36 public static interface InterfaceA
37 {
38 @GET
39 @Path("foo")
40 @Produces("text/plain")
41 String getFoo();
42 }
43
44 public static interface InterfaceB
45 {
46 @GET
47 @Path("bar")
48 @Produces("text/plain")
49 String getBar();
50 }
51
52 @Path("/foobar")
53 public static class FooBarImpl implements InterfaceA, InterfaceB, Nothing
54 {
55 @Override
56 public String getFoo()
57 {
58 return "FOO";
59 }
60
61 @Override
62 public String getBar()
63 {
64 return "BAR";
65 }
66 }
67
68 @BeforeClass
69 public static void before() throws Exception
70 {
71 deployment = EmbeddedContainer.start();
72 dispatcher = deployment.getDispatcher();
73 dispatcher.getRegistry().addPerRequestResource(FooBarImpl.class);
74 Client client = ClientBuilder.newClient();
75 target = (ResteasyWebTarget) client.target("http://localhost:8081/foobar");
76 }
77
78 @AfterClass
79 public static void after() throws Exception
80 {
81 EmbeddedContainer.stop();
82 dispatcher = null;
83 deployment = null;
84 Thread.sleep(100);
85 }
86
87 @Test
88 public void testResourceProxy() throws Exception
89 {
90 InterfaceA a = ProxyBuilder.builder(InterfaceA.class, target).build();
91 assertEquals("FOO", a.getFoo());
92 InterfaceB b = ((ResteasyClientProxy) a).as(InterfaceB.class);
93 assertEquals("BAR", b.getBar());
94 }
95 }
0 package org.jboss.resteasy.test.nextgen.security;
1
2 import org.apache.http.HttpHost;
3 import org.apache.http.HttpResponse;
4 import org.apache.http.auth.AuthScope;
5 import org.apache.http.auth.UsernamePasswordCredentials;
6 import org.apache.http.client.AuthCache;
7 import org.apache.http.client.methods.HttpGet;
8 import org.apache.http.client.protocol.ClientContext;
9 import org.apache.http.impl.auth.BasicScheme;
10 import org.apache.http.impl.client.BasicAuthCache;
11 import org.apache.http.impl.client.DefaultHttpClient;
12 import org.apache.http.protocol.BasicHttpContext;
13 import org.apache.http.util.EntityUtils;
14 import org.jboss.resteasy.client.ClientExecutor;
15 import org.jboss.resteasy.client.ClientRequest;
16 import org.jboss.resteasy.client.ClientResponse;
17 import org.jboss.resteasy.client.ClientResponseFailure;
18 import org.jboss.resteasy.client.ProxyFactory;
19 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
20 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
21 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
22 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
23 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
24 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
25 import org.jboss.resteasy.core.Dispatcher;
26 import org.jboss.resteasy.plugins.server.embedded.SimpleSecurityDomain;
27 import org.jboss.resteasy.test.EmbeddedContainer;
28 import org.jboss.resteasy.util.HttpResponseCodes;
29 import org.junit.AfterClass;
30 import org.junit.Assert;
31 import org.junit.BeforeClass;
32 import org.junit.Test;
33
34 import javax.annotation.security.DenyAll;
35 import javax.annotation.security.PermitAll;
36 import javax.annotation.security.RolesAllowed;
37 import javax.ws.rs.ClientErrorException;
38 import javax.ws.rs.GET;
39 import javax.ws.rs.Path;
40 import javax.ws.rs.WebApplicationException;
41 import javax.ws.rs.client.Client;
42 import javax.ws.rs.client.ClientBuilder;
43 import javax.ws.rs.client.WebTarget;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.Response;
46 import javax.ws.rs.core.SecurityContext;
47
48 import java.util.List;
49
50 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
51
52 /**
53 * Based on org.jboss.resteasy.test.security.BasicAuthTest, but with JAX-RS 2.0
54 * client framework.
55 *
56 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
57 * @author <a href="mailto:rsigal@redhat.com">Ron Sigal</a>
58 * @version $Revision: 1 $
59 */
60 public class BasicAuthTest
61 {
62 private static Dispatcher dispatcher;
63 private static final String ACCESS_FORBIDDEN_MESSAGE = "Access forbidden: role not allowed";
64
65 @Path("/secured")
66 public static interface BaseProxy
67 {
68 @GET
69 String get();
70
71 @GET
72 @Path("/authorized")
73 String getAuthorized();
74
75 @GET
76 @Path("/deny")
77 String deny();
78
79 @GET
80 @Path("/failure")
81 List<String> getFailure();
82 }
83
84 @Path("/secured")
85 public static class BaseResource
86 {
87 @GET
88 @Path("/failure")
89 @RolesAllowed("admin")
90 public List<String> getFailure()
91 {
92 return null;
93 }
94
95 @GET
96 public String get(@Context SecurityContext ctx)
97 {
98 System.out.println("********* IN SECURE CLIENT");
99 if (!ctx.isUserInRole("admin"))
100 {
101 System.out.println("NOT IN ROLE!!!!");
102 throw new WebApplicationException(403);
103 }
104 return "hello";
105 }
106
107 @GET
108 @Path("/authorized")
109 @RolesAllowed("admin")
110 public String getAuthorized()
111 {
112 return "authorized";
113 }
114
115 @GET
116 @Path("/deny")
117 @DenyAll
118 public String deny()
119 {
120 return "SHOULD NOT BE REACHED";
121 }
122 }
123
124 @Path("/secured2")
125 public static class BaseResource2
126 {
127 public String get(@Context SecurityContext ctx)
128 {
129 System.out.println("********* IN SECURE CLIENT");
130 if (!ctx.isUserInRole("admin"))
131 {
132 System.out.println("NOT IN ROLE!!!!");
133 throw new WebApplicationException(403);
134 }
135 return "hello";
136 }
137
138 @GET
139 @Path("/authorized")
140 @RolesAllowed("admin")
141 public String getAuthorized()
142 {
143 return "authorized";
144 }
145
146 }
147
148 @Path("/secured3")
149 @RolesAllowed("admin")
150 public static class BaseResource3
151 {
152 @GET
153 @Path("/authorized")
154 public String getAuthorized()
155 {
156 return "authorized";
157 }
158
159 @GET
160 @Path("/anybody")
161 @PermitAll
162 public String getAnybody()
163 {
164 return "anybody";
165 }
166 }
167
168 @BeforeClass
169 public static void before() throws Exception
170 {
171 SimpleSecurityDomain domain = new SimpleSecurityDomain();
172 String[] roles =
173 {"admin"};
174 String[] basic =
175 {"user"};
176 domain.addUser("bill", "password", roles);
177 domain.addUser("mo", "password", basic);
178 dispatcher = EmbeddedContainer.start("", domain).getDispatcher();
179 dispatcher.getRegistry().addPerRequestResource(BaseResource.class);
180 dispatcher.getRegistry().addPerRequestResource(BaseResource2.class);
181 dispatcher.getRegistry().addPerRequestResource(BaseResource3.class);
182 }
183
184 @AfterClass
185 public static void after() throws Exception
186 {
187 EmbeddedContainer.stop();
188 }
189
190 @Test
191 public void testProxy() throws Exception
192 {
193 DefaultHttpClient client = new DefaultHttpClient();
194 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("bill", "password");
195 client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
196 ClientExecutor executor = createAuthenticatingExecutor(client);
197 BaseProxy proxy = ProxyFactory.create(BaseProxy.class, generateURL(""), executor);
198 String val = proxy.get();
199 Assert.assertEquals(val, "hello");
200 val = proxy.getAuthorized();
201 Assert.assertEquals(val, "authorized");
202 }
203
204 @Test
205 public void testProxyFailure() throws Exception
206 {
207 ResteasyClient client = new ResteasyClientBuilder().build();
208 ResteasyWebTarget target = client.target(generateURL(""));
209 BaseProxy proxy = target.proxy(BaseProxy.class);
210
211 try
212 {
213 proxy.getFailure();
214 Assert.fail("Expected ClientErrorException");
215 }
216 catch (ClientErrorException e)
217 {
218 Assert.assertEquals(e.getResponse().getStatus(), 403);
219 try
220 {
221 Assert.assertEquals(ACCESS_FORBIDDEN_MESSAGE, e.getResponse().readEntity(String.class));
222 }
223 catch (IllegalStateException e2)
224 {
225 // OK - response is closed.
226 }
227 }
228 }
229
230 @Test
231 public void testSecurity() throws Exception
232 {
233 DefaultHttpClient httpClient = new DefaultHttpClient();
234 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("bill", "password");
235 httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
236 ClientHttpEngine engine = createAuthenticatingEngine(httpClient);
237 ResteasyClient authorizedClient = new ResteasyClientBuilder().httpEngine(engine).build();
238 ResteasyClient unauthorizedClient = new ResteasyClientBuilder().build();
239
240 {
241 WebTarget target = authorizedClient.target(generateURL("/secured"));
242 Response response = target.request().get();
243 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
244 Assert.assertEquals("hello", response.readEntity(String.class));
245 }
246 {
247 WebTarget target = authorizedClient.target(generateURL("/secured/authorized"));
248 Response response = target.request().get();
249 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
250 Assert.assertEquals("authorized", response.readEntity(String.class));
251 }
252 {
253 WebTarget target = authorizedClient.target(generateURL("/secured/deny"));
254 Response response = target.request().get();
255 Assert.assertEquals(HttpResponseCodes.SC_FORBIDDEN, response.getStatus());
256 Assert.assertEquals(ACCESS_FORBIDDEN_MESSAGE, response.readEntity(String.class));
257 }
258 {
259 WebTarget target = authorizedClient.target(generateURL("/secured3/authorized"));
260 Response response = target.request().get();
261 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
262 Assert.assertEquals("authorized", response.readEntity(String.class));
263 }
264 {
265 WebTarget target = unauthorizedClient.target(generateURL("/secured3/authorized"));
266 Response response = target.request().get();
267 Assert.assertEquals(403, response.getStatus());
268 Assert.assertEquals(ACCESS_FORBIDDEN_MESSAGE, response.readEntity(String.class));
269 }
270 {
271 WebTarget target = unauthorizedClient.target(generateURL("/secured3/anybody"));
272 Response response = target.request().get();
273 Assert.assertEquals(200, response.getStatus());
274 }
275 }
276
277 /**
278 * RESTEASY-579
279 *
280 * Found 579 bug when doing 575 so the test is here out of laziness
281 *
282 * @throws Exception
283 */
284 @Test
285 public void test579() throws Exception
286 {
287 DefaultHttpClient client = new DefaultHttpClient();
288 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("bill", "password");
289 client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
290 ClientHttpEngine engine = createAuthenticatingEngine(client);
291 ResteasyClient authorizedClient = new ResteasyClientBuilder().httpEngine(engine).build();
292 WebTarget target = authorizedClient.target(generateURL("/secured2"));
293 Response response = target.request().get();
294 Assert.assertEquals(404, response.getStatus());
295 }
296
297 @Test
298 public void testSecurityFailure() throws Exception
299 {
300 DefaultHttpClient client = new DefaultHttpClient();
301
302 {
303 HttpGet method = new HttpGet(generateURL("/secured"));
304 HttpResponse response = client.execute(method);
305 Assert.assertEquals(403, response.getStatusLine().getStatusCode());
306 EntityUtils.consume(response.getEntity());
307 }
308
309 {
310 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("bill", "password");
311 client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
312 ClientHttpEngine engine = createAuthenticatingEngine(client);
313 ResteasyClient authorizedClient = new ResteasyClientBuilder().httpEngine(engine).build();
314 WebTarget target = authorizedClient.target(generateURL("/secured/authorized"));
315 Response response = target.request().get();
316 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
317 Assert.assertEquals("authorized", response.readEntity(String.class));
318 }
319
320 {
321 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("mo", "password");
322 client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
323 ClientHttpEngine engine = createAuthenticatingEngine(client);
324 ResteasyClient authorizedClient = new ResteasyClientBuilder().httpEngine(engine).build();
325 WebTarget target = authorizedClient.target(generateURL("/secured/authorized"));
326 Response response = target.request().get();
327 Assert.assertEquals(HttpResponseCodes.SC_FORBIDDEN, response.getStatus());
328 Assert.assertEquals(ACCESS_FORBIDDEN_MESSAGE, response.readEntity(String.class));
329 }
330 }
331
332 /**
333 * Create a ClientExecutor which does preemptive authentication.
334 */
335
336 static private ClientExecutor createAuthenticatingExecutor(DefaultHttpClient client)
337 {
338 // Create AuthCache instance
339 AuthCache authCache = new BasicAuthCache();
340
341 // Generate BASIC scheme object and add it to the local auth cache
342 BasicScheme basicAuth = new BasicScheme();
343 HttpHost targetHost = new HttpHost("localhost", 8081);
344 authCache.put(targetHost, basicAuth);
345
346 // Add AuthCache to the execution context
347 BasicHttpContext localContext = new BasicHttpContext();
348 localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
349
350 // Create ClientExecutor.
351 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);
352 return executor;
353 }
354
355 static private ClientHttpEngine createAuthenticatingEngine(DefaultHttpClient client)
356 {
357 // Create AuthCache instance
358 AuthCache authCache = new BasicAuthCache();
359
360 // Generate BASIC scheme object and add it to the local auth cache
361 BasicScheme basicAuth = new BasicScheme();
362 HttpHost targetHost = new HttpHost("localhost", 8081);
363 authCache.put(targetHost, basicAuth);
364
365 // Add AuthCache to the execution context
366 BasicHttpContext localContext = new BasicHttpContext();
367 localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
368
369 // Create ClientHttpEngine
370 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(client, localContext);
371 return engine;
372 }
373 }
0 package org.jboss.resteasy.test.regression;
1
2 import org.jboss.resteasy.core.Dispatcher;
3 import org.junit.AfterClass;
4 import org.junit.BeforeClass;
5 import org.junit.Test;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 */
11 public class TJWSChunkTest
12 {
13 private static Dispatcher dispatcher;
14
15 @BeforeClass
16 public static void before() throws Exception
17 {
18 //dispatcher = TJWSServletContainer.start();
19 }
20
21 @AfterClass
22 public static void after() throws Exception
23 {
24 //TJWSServletContainer.stop();
25 }
26
27 @Test
28 public void testNoDefaultsResource() throws Exception
29 {
30 /*
31 dispatcher.getRegistry().addPerRequestResource(BookStore.class);
32
33 HttpClient httpClient = new HttpClient();
34 BookStoreClient client = ProxyFactory.create(BookStoreClient.class, generateBaseUrl(), httpClient);
35
36 Book book = client.getBookByISBN("596529260");
37 Assert.assertNotNull(book);
38 Assert.assertEquals("RESTful Web Services", book.getTitle());
39
40 // TJWS does not support chunk encodings well so I need to kill kept alive connections
41 // this is a test for it, the test is fail with a put or post, then try with another invocation. Origginally
42 // the server would hang.
43 //httpClient.getHttpConnectionManager().closeIdleConnections(0);
44
45 book = new Book("Bill Burke", "666", "EJB 3.0");
46 client.addBook(book);
47 {
48 PutMethod method = createPutMethod("/basic");
49 method.setRequestEntity(new StringRequestEntity("basic", "text/plain", null));
50 httpClient.executeMethod(method);
51 }
52 // TJWS does not support chunk encodings so I need to kill kept alive connections
53 //httpClient.getHttpConnectionManager().closeIdleConnections(0);
54 book = client.getBookByISBN("666");
55 Assert.assertEquals("Bill Burke", book.getAuthor());
56 //httpClient.getHttpConnectionManager().closeIdleConnections(0);
57 */
58 }
59 }
0 package org.jboss.resteasy.test.resource.generic;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.PUT;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.PathParam;
6
7 /**
8 * This is a sample of a CRUD resource template which can be reused for different entities.
9 *
10 * @param <ENTITY_TYPE> Type of the entity which CRUD operations are performed on.
11 * @param <ENTITY_IDENTIFIER_TYPE> Type of the entity identified i.e. java.lang.Long
12 * @author Jozef Hartinger
13 */
14 public abstract class CrudResource<ENTITY_TYPE, ENTITY_IDENTIFIER_TYPE>
15 {
16 abstract ENTITY_TYPE getEntity(ENTITY_IDENTIFIER_TYPE id);
17
18 abstract void setEntity(ENTITY_IDENTIFIER_TYPE id, ENTITY_TYPE entity);
19
20 @GET
21 @Path("/{id}")
22 public ENTITY_TYPE get(@PathParam("id") ENTITY_IDENTIFIER_TYPE id)
23 {
24 return getEntity(id);
25 }
26
27 @PUT
28 @Path("/{id}")
29 public void put(@PathParam("id") ENTITY_IDENTIFIER_TYPE id, ENTITY_TYPE entity)
30 {
31 setEntity(id, entity);
32 }
33 }
0 package org.jboss.resteasy.test.resource.generic;
1
2 import org.jboss.resteasy.client.ProxyFactory;
3 import org.jboss.resteasy.test.BaseResourceTest;
4 import org.junit.Before;
5 import org.junit.Test;
6
7 import static junit.framework.Assert.assertTrue;
8 import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;
9
10 public class GenericResourceTest extends BaseResourceTest
11 {
12 StudentInterface proxy;
13
14 @Before
15 public void setUp()
16 {
17 addPerRequestResource(StudentCrudResource.class);
18 getProviderFactory().registerProvider(StudentReader.class);
19 getProviderFactory().registerProvider(StudentWriter.class);
20
21 proxy = ProxyFactory.create(StudentInterface.class, generateBaseUrl());
22 }
23
24 @Test
25 public void testGet()
26 {
27 assertTrue(proxy.get(1).getName().equals("Jozef Hartinger"));
28 }
29
30 @Test
31 public void testPut()
32 {
33 proxy.put(2, new Student("John Doe"));
34 assertTrue(proxy.get(2).getName().equals("John Doe"));
35 }
36 }
0 package org.jboss.resteasy.test.resource.generic;
1
2 public class Student
3 {
4 private String name;
5
6 public Student()
7 {
8 }
9
10 public Student(String name)
11 {
12 this.name = name;
13 }
14
15 public String getName()
16 {
17 return name;
18 }
19
20 public void setName(String name)
21 {
22 this.name = name;
23 }
24
25 @Override
26 public String toString()
27 {
28 return "Student: " + name;
29 }
30 }
0 package org.jboss.resteasy.test.resource.generic;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 /**
9 * RESTEasy should be able to use type parameter values (Student, Integer) for (de)marshalling parameters/entity body.
10 *
11 * @author Jozef Hartinger
12 */
13 @Path("/student")
14 @Produces("application/student")
15 @Consumes("application/student")
16 public class StudentCrudResource extends CrudResource<Student, Integer>
17 {
18
19 private static Map<Integer, Student> students = new HashMap<Integer, Student>();
20
21 public StudentCrudResource()
22 {
23 students.put(1, new Student("Jozef Hartinger"));
24 }
25
26 @Override
27 Student getEntity(Integer id)
28 {
29 return students.get(id);
30 }
31
32 @Override
33 void setEntity(Integer id, Student entity)
34 {
35 students.put(id, entity);
36 }
37 }
0 package org.jboss.resteasy.test.resource.generic;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.PUT;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8
9 /**
10 * This interface is used on the client side only.
11 *
12 * @author Jozef Hartinger
13 */
14
15 @Path("/student/{id}")
16 @Produces("application/student")
17 @Consumes("application/student")
18 public interface StudentInterface
19 {
20 @GET
21 Student get(@PathParam("id") Integer id);
22
23 @PUT
24 void put(@PathParam("id") Integer id, Student entity);
25 }
0 package org.jboss.resteasy.test.resource.generic;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyReader;
7 import javax.ws.rs.ext.Provider;
8 import java.io.BufferedReader;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14
15 @Provider
16 @Consumes("application/student")
17 public class StudentReader implements MessageBodyReader<Student>
18 {
19
20 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
21 {
22 return true;
23 }
24
25 public Student readFrom(Class<Student> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
26 {
27 BufferedReader br = null;
28 try
29 {
30 br = new BufferedReader(new InputStreamReader(entityStream));
31 return new Student(br.readLine());
32 }
33 catch (Exception e)
34 {
35 throw new RuntimeException("Unable to parse student.", e);
36 }
37 }
38 }
0 package org.jboss.resteasy.test.resource.generic;
1
2 import javax.ws.rs.Produces;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import javax.ws.rs.ext.Provider;
8 import java.io.IOException;
9 import java.io.OutputStream;
10 import java.io.OutputStreamWriter;
11 import java.lang.annotation.Annotation;
12 import java.lang.reflect.Type;
13
14 @Provider
15 @Produces("application/student")
16 public class StudentWriter implements MessageBodyWriter<Student>
17 {
18
19 public long getSize(Student t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
20 {
21 return t.getName().length();
22 }
23
24 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
25 {
26 return true;
27 }
28
29 public void writeTo(Student t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
30 {
31 OutputStreamWriter writer = new OutputStreamWriter(entityStream);
32 writer.write(t.getName());
33 writer.flush();
34 }
35 }
0 package org.jboss.resteasy.test.resource.proxy;
1
2 import javax.ws.rs.GET;
3
4 /**
5 * Objects of this class are used as subresources.
6 *
7 * @author Jozef Hartinger
8 */
9 public class Car
10 {
11
12 private String id;
13
14 public Car()
15 {
16 }
17
18 public Car(String id)
19 {
20 this.id = id;
21 }
22
23 @GET
24 public String getId()
25 {
26 return id;
27 }
28 }
0 package org.jboss.resteasy.test.resource.proxy;
1
2 import javassist.util.proxy.MethodHandler;
3
4 import java.lang.reflect.Method;
5
6 /**
7 * Trivial proxy that forwards method calls to underlying Car instance.
8 * In Seam, similar proxies are used for nontrivial purposes.
9 *
10 * @author Jozef Hartinger
11 */
12 public class CarProxy implements MethodHandler
13 {
14 private Car car;
15
16 public CarProxy(Car car)
17 {
18 this.car = car;
19 }
20
21 public Object invoke(Object object, Method method, Method proceed, Object[] args) throws Throwable
22 {
23 return method.invoke(car, args);
24 }
25 }
0 package org.jboss.resteasy.test.resource.proxy;
1
2 import javassist.util.proxy.ProxyFactory;
3 import javassist.util.proxy.ProxyObject;
4
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7
8 @Path("/garage")
9 @Produces("text/plain")
10 public class Garage
11 {
12 @Path("/car")
13 public Car getCar()
14 {
15 return lookupSeamComponent();
16 }
17
18 /**
19 * This method simulates obtaining a bean from Seam and returning it. - Components.getInstance(Car.class)
20 * Seam is not used in this test. Car instance is wrapped with a javassist proxy.
21 *
22 * @return Proxied Car instance
23 */
24 private Car lookupSeamComponent()
25 {
26 Car car = new Car("MT-123AB");
27 CarProxy interceptor = new CarProxy(car);
28
29 ProxyFactory factory = new ProxyFactory();
30 factory.setSuperclass(Car.class);
31
32 ProxyObject component = null;
33 try
34 {
35 component = (ProxyObject) factory.createClass().newInstance();
36 }
37 catch (Exception e)
38 {
39 throw new RuntimeException(e);
40 }
41
42 component.setHandler(interceptor);
43
44 return (Car) component;
45 }
46 }
0 package org.jboss.resteasy.test.resource.proxy;
1
2
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.core.executors.InMemoryClientExecutor;
6 import org.jboss.resteasy.spi.ResteasyProviderFactory;
7 import org.junit.Test;
8
9 import static junit.framework.Assert.assertEquals;
10
11 public class ProxiedSubresourceTest
12 {
13
14 /**
15 * This method tests RESTEASY-356
16 */
17 @Test
18 public void testProxiedSubresource() throws Exception
19 {
20 ResteasyProviderFactory.setInstance(null);
21 InMemoryClientExecutor executor = new InMemoryClientExecutor();
22 executor.getRegistry().addPerRequestResource(Garage.class);
23 ClientResponse<String> result = new ClientRequest("/garage/car", executor).get(String.class);
24
25 assertEquals(200, result.getStatus());
26 assertEquals("MT-123AB", result.getEntity());
27 }
28 }
0 package org.jboss.resteasy.test.smoke;
1
2 import javax.ws.rs.Path;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 */
8 @Path("/")
9 public class LocatingResource
10 {
11 @Path("locating")
12 public SimpleResource getLocating()
13 {
14 System.out.println("LOCATING...");
15 return new SimpleResource();
16 }
17
18
19 @Path("subresource")
20 public SimpleSubresource getSubresource()
21 {
22 System.out.println("Subresource");
23 return new SimpleSubresource();
24 }
25
26
27 @Path("notlocating")
28 public SimpleResource getNotLocating()
29 {
30 System.out.println("NOT LOCATING... i.e. returning null");
31 return null;
32 }
33
34 }
0 package org.jboss.resteasy.test.smoke;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.MatrixParam;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10 import javax.ws.rs.core.Response;
11
12 /**
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 */
16 @Path("/")
17 public class SimpleResource
18 {
19 @GET
20 @Path("basic")
21 @Produces("text/plain")
22 public String getBasic()
23 {
24 System.out.println("getBasic()");
25 return "basic";
26 }
27
28 @PUT
29 @Path("basic")
30 @Consumes("text/plain")
31 public void putBasic(String body)
32 {
33 System.out.println(body);
34 }
35
36 @GET
37 @Path("queryParam")
38 @Produces("text/plain")
39 public String getQueryParam(@QueryParam("param") String param)
40 {
41 System.out.println("query param: " + param);
42 return param;
43 }
44
45 @GET
46 @Path("matrixParam")
47 @Produces("text/plain")
48 public String getMatrixParam(@MatrixParam("param") String param)
49 {
50 return param;
51 }
52
53 @GET
54 @Path("uriParam/{param}")
55 @Produces("text/plain")
56 public int getUriParam(@PathParam("param") int param)
57 {
58 return param;
59 }
60
61 @GET
62 @Path("header")
63 public Response getHeader()
64 {
65 return Response.ok().header("header", "headervalue").build();
66 }
67 }
0 package org.jboss.resteasy.test.smoke;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Context;
6 import javax.ws.rs.core.UriInfo;
7
8 /**
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @version $Revision: 1 $
11 */
12 public class SimpleSubresource
13 {
14
15 @SuppressWarnings("unused")
16 private String foo;
17
18 @Context
19 private UriInfo uriInfo;
20
21 @GET
22 @Path("basic")
23 @Produces("text/plain")
24 public String getBasic()
25 {
26 return "basic";
27 }
28
29 @Path("subresource")
30 public SimpleSubresource getSubresource()
31 {
32 System.out.println("Subsubresource");
33 return new SimpleSubresource();
34 }
35
36 @GET
37 @Path("testContextParam")
38 public void testContextParam()
39 {
40 if (uriInfo != null)
41 throw new IllegalStateException("uriInfo is supposed to be null");
42 }
43
44 }
0 package org.jboss.resteasy.test.smoke;
1
2 import org.jboss.resteasy.core.Dispatcher;
3 import org.jboss.resteasy.mock.MockDispatcherFactory;
4 import org.jboss.resteasy.mock.MockHttpRequest;
5 import org.jboss.resteasy.mock.MockHttpResponse;
6 import org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory;
7 import org.junit.Assert;
8 import org.junit.Test;
9
10 import javax.servlet.http.HttpServletResponse;
11 import java.net.URLEncoder;
12
13 /**
14 * Simple smoke test
15 *
16 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
17 * @version $Revision: 1 $
18 */
19 public class TestSmoke
20 {
21
22
23 @Test
24 public void testNoDefaultsResource() throws Exception
25 {
26 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
27
28 POJOResourceFactory noDefaults = new POJOResourceFactory(SimpleResource.class);
29 dispatcher.getRegistry().addResourceFactory(noDefaults);
30
31 {
32 MockHttpRequest request = MockHttpRequest.get("/basic/");
33 MockHttpResponse response = new MockHttpResponse();
34
35 dispatcher.invoke(request, response);
36
37
38 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
39 Assert.assertEquals("basic", response.getContentAsString());
40 }
41 {
42 MockHttpRequest request = MockHttpRequest.put("/basic");
43 request.content("basic".getBytes());
44 request.contentType("text/plain");
45 MockHttpResponse response = new MockHttpResponse();
46
47 dispatcher.invoke(request, response);
48
49
50 Assert.assertEquals(204, response.getStatus());
51 }
52 {
53 MockHttpRequest request = MockHttpRequest.get("/queryParam?" + "param=" + URLEncoder.encode("hello world", "UTF-8"));
54 MockHttpResponse response = new MockHttpResponse();
55
56 dispatcher.invoke(request, response);
57
58
59 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
60 Assert.assertEquals("hello world", response.getContentAsString());
61 }
62 {
63 MockHttpRequest request = MockHttpRequest.get("/uriParam/1234");
64 MockHttpResponse response = new MockHttpResponse();
65
66 dispatcher.invoke(request, response);
67
68
69 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
70 Assert.assertEquals("1234", response.getContentAsString());
71 }
72 }
73
74 @Test
75 public void testLocatingResource() throws Exception
76 {
77 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
78
79 POJOResourceFactory noDefaults = new POJOResourceFactory(LocatingResource.class);
80 dispatcher.getRegistry().addResourceFactory(noDefaults);
81
82 {
83 MockHttpRequest request = MockHttpRequest.get("/locating/basic");
84 MockHttpResponse response = new MockHttpResponse();
85
86 dispatcher.invoke(request, response);
87
88
89 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
90 Assert.assertEquals("basic", response.getContentAsString());
91 }
92 {
93 MockHttpRequest request = MockHttpRequest.put("/locating/basic");
94 request.content("basic".getBytes());
95 request.contentType("text/plain");
96 MockHttpResponse response = new MockHttpResponse();
97
98 dispatcher.invoke(request, response);
99
100
101 Assert.assertEquals(204, response.getStatus());
102 }
103 {
104 MockHttpRequest request = MockHttpRequest.get("/locating/queryParam?" + "param=" + URLEncoder.encode("hello world", "UTF-8"));
105 MockHttpResponse response = new MockHttpResponse();
106
107 dispatcher.invoke(request, response);
108
109
110 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
111 Assert.assertEquals("hello world", response.getContentAsString());
112 }
113 {
114 MockHttpRequest request = MockHttpRequest.get("/locating/uriParam/1234");
115 MockHttpResponse response = new MockHttpResponse();
116
117 dispatcher.invoke(request, response);
118
119
120 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
121 Assert.assertEquals("1234", response.getContentAsString());
122 }
123 }
124
125
126 @Test
127 public void testBadNumericMatch() throws Exception
128 {
129 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
130
131 POJOResourceFactory noDefaults = new POJOResourceFactory(LocatingResource.class);
132 dispatcher.getRegistry().addResourceFactory(noDefaults);
133
134 {
135 MockHttpRequest request = MockHttpRequest.get("/locating/uriParam/x123");
136 MockHttpResponse response = new MockHttpResponse();
137
138 dispatcher.invoke(request, response);
139
140 Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
141 }
142
143 }
144
145
146 @Test
147 public void testNotLocating() throws Exception
148 {
149 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
150
151 POJOResourceFactory noDefaults = new POJOResourceFactory(LocatingResource.class);
152 dispatcher.getRegistry().addResourceFactory(noDefaults);
153
154 {
155 MockHttpRequest request = MockHttpRequest.get("/notlocating");
156 MockHttpResponse response = new MockHttpResponse();
157
158 dispatcher.invoke(request, response);
159
160 Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
161 }
162
163 }
164
165
166 @Test
167 public void testNotMappedInSubresource() throws Exception
168 {
169 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
170
171 POJOResourceFactory noDefaults = new POJOResourceFactory(LocatingResource.class);
172 dispatcher.getRegistry().addResourceFactory(noDefaults);
173
174 {
175 MockHttpRequest request = MockHttpRequest.get("/locating/notmatching");
176 MockHttpResponse response = new MockHttpResponse();
177
178 dispatcher.invoke(request, response);
179
180 Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
181 }
182
183 }
184
185
186 @Test
187 public void testSubSubresource() throws Exception
188 {
189 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
190
191 POJOResourceFactory noDefaults = new POJOResourceFactory(LocatingResource.class);
192 dispatcher.getRegistry().addResourceFactory(noDefaults);
193
194 {
195 MockHttpRequest request = MockHttpRequest.get("/subresource/subresource/subresource/basic");
196 MockHttpResponse response = new MockHttpResponse();
197
198 dispatcher.invoke(request, response);
199
200 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
201 Assert.assertEquals("basic", response.getContentAsString());
202 }
203
204 }
205
206
207 @Test
208 public void testContextParam() throws Exception
209 {
210 Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
211
212 POJOResourceFactory noDefaults = new POJOResourceFactory(LocatingResource.class);
213 dispatcher.getRegistry().addResourceFactory(noDefaults);
214
215 {
216
217 System.out.println("Expect to see WARN about not injecting in subresources");
218
219 MockHttpRequest request = MockHttpRequest.get("/subresource/testContextParam");
220 MockHttpResponse response = new MockHttpResponse();
221
222 dispatcher.invoke(request, response);
223
224 Assert.assertEquals(204, response.getStatus());
225 }
226
227 }
228
229
230 }
0 package org.jboss.resteasy.test.smoke;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.client.core.executors.InMemoryClientExecutor;
5 import org.jboss.resteasy.core.Dispatcher;
6 import org.jboss.resteasy.core.SynchronousDispatcher;
7 import org.jboss.resteasy.plugins.providers.DefaultTextPlain;
8 import org.jboss.resteasy.plugins.providers.StringTextStar;
9 import org.jboss.resteasy.spi.Registry;
10 import org.jboss.resteasy.spi.ResteasyProviderFactory;
11 import org.junit.Assert;
12 import org.junit.Test;
13
14 import javax.servlet.http.HttpServletResponse;
15
16 /**
17 * Simple smoke test
18 *
19 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
20 * @version $Revision: 1 $
21 */
22 public class TestWireInMemorySmoke
23 {
24
25 @Test
26 public void testNoDefaultsResource() throws Exception
27 {
28 InMemoryClientExecutor executor = new InMemoryClientExecutor(createDispatcher());
29 Registry registry = executor.getRegistry();
30 int oldSize = registry.getSize();
31 registry.addPerRequestResource(SimpleResource.class);
32 Assert.assertTrue(oldSize < registry.getSize());
33
34 {
35 ClientResponse<String> response = new ClientRequest("/basic", executor).get(String.class);
36 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
37 Assert.assertEquals("basic", response.getEntity());
38 }
39 {
40 ClientResponse response = new ClientRequest("/basic", executor).body("text/plain", "basic").put();
41 Assert.assertEquals(204, response.getStatus());
42 }
43 {
44 ClientResponse<String> response = new ClientRequest("/queryParam", executor).queryParameter("param",
45 "hello world").get(String.class);
46 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
47 Assert.assertEquals("hello world", response.getEntity());
48 }
49 {
50 ClientResponse<String> response = new ClientRequest("/uriParam/1234", executor).get(String.class);
51 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
52 Assert.assertEquals("1234", response.getEntity());
53 }
54 registry.removeRegistrations(SimpleResource.class);
55 Assert.assertEquals(oldSize, registry.getSize());
56 }
57
58 private Dispatcher createDispatcher()
59 {
60 ResteasyProviderFactory factory = new ResteasyProviderFactory();
61 factory.registerProvider(StringTextStar.class);
62 factory.registerProvider(DefaultTextPlain.class);
63 return new SynchronousDispatcher(factory);
64 }
65
66 @Test
67 public void testLocatingResource() throws Exception
68 {
69 InMemoryClientExecutor executor = new InMemoryClientExecutor(createDispatcher());
70 Registry registry = executor.getRegistry();
71 int oldSize = registry.getSize();
72 registry.addPerRequestResource(LocatingResource.class);
73 Assert.assertTrue(oldSize < registry.getSize());
74
75 {
76 ClientResponse<String> response = new ClientRequest("/locating/basic", executor).get(String.class);
77 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
78 Assert.assertEquals("basic", response.getEntity());
79 }
80 {
81 ClientResponse response = new ClientRequest("/locating/basic", executor).body("text/plain", "basic").put();
82 Assert.assertEquals(204, response.getStatus());
83 }
84 {
85 ClientResponse<String> response = new ClientRequest("/locating/queryParam", executor).queryParameter("param",
86 "hello world").get(String.class);
87 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
88 Assert.assertEquals("hello world", response.getEntity());
89 }
90 {
91 ClientResponse<String> response = new ClientRequest("/locating/uriParam/1234", executor).body("text/plain",
92 "basic").get(String.class);
93 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
94 Assert.assertEquals("1234", response.getEntity());
95 }
96 registry.removeRegistrations(LocatingResource.class);
97 Assert.assertEquals(oldSize, registry.getSize());
98 }
99 }
0 package org.jboss.resteasy.test.tjws;
1
2 import org.jboss.resteasy.core.Dispatcher;
3 import org.jboss.resteasy.test.EmbeddedContainer;
4 import org.junit.AfterClass;
5 import org.junit.BeforeClass;
6 import org.junit.Test;
7
8 import javax.ws.rs.Consumes;
9 import javax.ws.rs.GET;
10 import javax.ws.rs.HEAD;
11 import javax.ws.rs.PUT;
12 import javax.ws.rs.Path;
13 import javax.ws.rs.core.Response;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.OutputStream;
17 import java.net.Socket;
18
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertTrue;
21
22 /**
23 * Unit test for RESTEASY-602.
24 *
25 * @author <a href="mailto:ron.sigal@jboss.com">Ron Sigal</a>
26 * @version $Revision: $
27 */
28 public class ChunkedEmptyEntityTest
29 {
30 private static Dispatcher dispatcher;
31
32 @BeforeClass
33 public static void before() throws Exception
34 {
35 dispatcher = EmbeddedContainer.start().getDispatcher();
36 dispatcher.getRegistry().addPerRequestResource(SimpleResource.class);
37 }
38
39 @AfterClass
40 public static void after() throws Exception
41 {
42 EmbeddedContainer.stop();
43 }
44
45 @Test
46 public void testContinue() throws Exception
47 {
48 _run_test("PUT", "/continue", "100");
49 }
50
51 @Test
52 public void testHead() throws Exception
53 {
54 _run_test("HEAD", "/head", "204");
55 }
56
57 @Test
58 public void testNoContent() throws Exception
59 {
60 _run_test("PUT", "/nocontent", "204");
61 }
62
63 @Test
64 public void testNotModified() throws Exception
65 {
66 _run_test("GET", "/notmodified", "304");
67 }
68
69 void _run_test(String method, String path, String status) throws Exception
70 {
71 // Solicit a reply with response code 204.
72 Socket s = new Socket("localhost", 8081);
73 OutputStream os = s.getOutputStream();
74 writeString(os, method + " " + path + " HTTP/1.1");
75 writeString(os, "Content-Length: 11");
76 writeString(os, "Content-Type: text/plain");
77 writeString(os, "Host: localhost:8081");
78 writeString(os, "");
79 os.write("hello world".getBytes());
80 os.flush();
81
82 // Verify response code is correct and that the message
83 // 1. has no "transfer-encoding" header, and
84 // 2. consists of status line and headers but no chunks.
85 InputStream is = s.getInputStream();
86 String line = readLine(is);
87 System.out.println("<<" + line);
88 assertTrue(line.contains(status));
89 line = readLine(is);
90 while (line != null && is.available() > 0)
91 {
92 System.out.println("<<" + line);
93 int i = line.indexOf(':');
94 assertTrue(i > 0);
95 assertFalse("transfer-encoding".equalsIgnoreCase(line.substring(0, i)));
96 line = readLine(is);
97 }
98 }
99
100 private void writeString(OutputStream os, String s) throws IOException
101 {
102 System.out.println(">>" + s);
103 os.write((s + "\r\n").getBytes());
104 }
105
106 /**
107 * Lifted from Acme.Serve.Serve
108 */
109 private String readLine(InputStream in) throws IOException
110 {
111 int maxLen = 1024;
112 StringBuffer buf = new StringBuffer(Math.min(1024, maxLen));
113
114 int c;
115 boolean cr = false;
116 int i = 0;
117 while ((c = in.read()) != -1)
118 {
119 if (c == 10)
120 { // LF
121 if (cr)
122 break;
123 break;
124 //throw new IOException ("LF without CR");
125 }
126 else if (c == 13) // CR
127 cr = true;
128 else
129 {
130 //if (cr)
131 //throw new IOException ("CR without LF");
132 // see http://www.w3.org/Protocols/HTTP/1.1/rfc2616bis/draft-lafon-rfc2616bis-03.html#tolerant.applications
133 cr = false;
134 if (i >= maxLen)
135 throw new IOException("Line length exceeds " + maxLen);
136 buf.append((char) c);
137 i++;
138 }
139 }
140 if (c == -1 && buf.length() == 0)
141 return null;
142
143 return buf.toString();
144 }
145
146 @Path("/")
147 static public class SimpleResource
148 {
149 @HEAD
150 @Path("/head")
151 @Consumes("text/plain")
152 public Response head()
153 {
154 return Response.noContent().build();
155 }
156
157 @PUT
158 @Path("/continue")
159 @Consumes("text/plain")
160 public Response putContinue()
161 {
162 return Response.status(100).build();
163 }
164
165 @PUT
166 @Path("/nocontent")
167 @Consumes("text/plain")
168 public void putNoContent(String body)
169 {
170 System.out.println(body);
171 }
172
173 @GET
174 @Path("/notmodified")
175 @Consumes("text/plain")
176 public Response getNotModified() throws Exception
177 {
178 return Response.notModified().build();
179 }
180 }
181 }
0 package org.jboss.resteasy.test.xxe;
1
2 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
3
4 import java.util.Hashtable;
5
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.core.Response;
10 import javax.ws.rs.ext.ExceptionMapper;
11 import javax.xml.parsers.DocumentBuilderFactory;
12
13 import org.junit.Assert;
14
15 import org.jboss.resteasy.client.ClientRequest;
16 import org.jboss.resteasy.client.ClientResponse;
17 import org.jboss.resteasy.core.Dispatcher;
18 import org.jboss.resteasy.spi.ResteasyDeployment;
19 import org.jboss.resteasy.spi.ReaderException;
20 import org.jboss.resteasy.test.EmbeddedContainer;
21 import org.junit.After;
22 import org.junit.Test;
23 import org.w3c.dom.Document;
24 import org.w3c.dom.Node;
25 import org.w3c.dom.NodeList;
26
27 /**
28 * Unit tests for RESTEASY-1103.
29 *
30 * @author <a href="mailto:ron.sigal@jboss.com">Ron Sigal</a>
31 * @date September 1, 2014
32 */
33 public class TestSecureProcessing
34 {
35 protected static ResteasyDeployment deployment;
36 protected static Dispatcher dispatcher;
37 protected static enum MapInclusion {DEFAULT, FALSE, TRUE};
38
39 ///////////////////////////////////////////////////////////////////////////////////////////////
40 protected static String bigExpansionDoc =
41 "<!DOCTYPE foodocument [" +
42 "<!ENTITY foo 'foo'>" +
43 "<!ENTITY foo1 '&foo;&foo;&foo;&foo;&foo;&foo;&foo;&foo;&foo;&foo;'>" +
44 "<!ENTITY foo2 '&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;'>" +
45 "<!ENTITY foo3 '&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;'>" +
46 "<!ENTITY foo4 '&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;'>" +
47 "<!ENTITY foo5 '&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;'>" +
48 "<!ENTITY foo6 '&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;'>" +
49 "]>" +
50 "<element>&foo5;</element>";
51
52 protected static String bigAttributeDoc;
53 static
54 {
55 StringBuffer sb = new StringBuffer();
56 sb.append("<element ");
57 for (int i = 0; i < 12000; i++)
58 {
59 sb.append("attr" + i + "=\"x\" ");
60 }
61 sb.append(">bar</element>");
62 bigAttributeDoc = sb.toString();
63 }
64
65 String smallDtd = "<!DOCTYPE bardocument [<!ELEMENT bar (ALL)>]><bar>bar</bar>";
66
67 protected static String filename = "src/test/java/org/jboss/resteasy/test/xxe/testpasswd";
68 protected static String externalEntityDoc =
69 "<?xml version=\"1.0\"?>\r" +
70 "<!DOCTYPE foo\r" +
71 "[<!ENTITY xxe SYSTEM \"" + filename + "\">\r" +
72 "]>\r" +
73 "<element>&xxe;</element>";
74
75 public static class TestExceptionMapper implements ExceptionMapper<ReaderException>
76 {
77 @Override
78 public Response toResponse(ReaderException exception)
79 {
80 return Response.status(400).entity(exception.getMessage()).build();
81 }
82 }
83
84 ///////////////////////////////////////////////////////////////////////////////////////////////
85 @Path("/")
86 public static class TestResource
87 {
88 @Consumes("application/xml")
89 @POST
90 @Path("test")
91 public String doPost(Document doc)
92 {
93 Node node = doc.getDocumentElement();
94 //System.out.println("name: " + node.getNodeName());
95 NodeList children = doc.getDocumentElement().getChildNodes();
96 node = children.item(0);
97 //System.out.println("name: " + node.getNodeName());
98 String text = node.getTextContent();
99 int len = Math.min(text.length(), 30);
100 //System.out.println("text: " + text.substring(0, len));
101 return text;
102 }
103 }
104
105 ///////////////////////////////////////////////////////////////////////////////////////////////
106 public static void before(Hashtable<String, String> contextParams) throws Exception
107 {
108 Hashtable<String,String> initParams = new Hashtable<String,String>();
109 deployment = EmbeddedContainer.start(initParams, contextParams);
110 dispatcher = deployment.getDispatcher();
111 deployment.getRegistry().addPerRequestResource(TestResource.class);
112 deployment.getProviderFactory().register(TestExceptionMapper.class);
113 }
114
115 @After
116 public void after() throws Exception
117 {
118 EmbeddedContainer.stop();
119 Thread.sleep(1000);
120 dispatcher = null;
121 deployment = null;
122 }
123
124 ///////////////////////////////////////////////////////////////////////////////////////////////
125 @Test
126 public void testSecurityDefaultDTDsDefaultExpansionDefault() throws Exception
127 {
128 before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.DEFAULT, MapInclusion.DEFAULT));
129 doTestSkipFailsFailsSkip();
130 }
131
132 @Test
133 public void testSecurityDefaultDTDsDefaultExpansionFalse() throws Exception
134 {
135 before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.DEFAULT, MapInclusion.FALSE));
136 doTestSkipFailsFailsSkip();
137 }
138
139 @Test
140 public void testSecurityDefaultDTDsDefaultExpansionTrue() throws Exception
141 {
142 before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.DEFAULT, MapInclusion.TRUE));
143 doTestSkipFailsFailsSkip();
144 }
145
146 @Test
147 public void testSecurityDefaultDTDsFalseExpansionDefault() throws Exception
148 {
149 before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.FALSE, MapInclusion.DEFAULT));
150 doTestFailsFailsPassesFails();
151 }
152
153 @Test
154 public void testSecurityDefaultDTDsFalseExpansionFalse() throws Exception
155 {
156 before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.FALSE, MapInclusion.FALSE));
157 doTestFailsFailsPassesFails();
158 }
159
160 @Test
161 public void testSecurityDefaultDTDsFalseExpansionTrue() throws Exception
162 {
163 before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.FALSE, MapInclusion.TRUE));
164 doTestFailsFailsPassesPasses();
165 }
166
167 @Test
168 public void testSecurityDefaultDTDsTrueExpansionDefault() throws Exception
169 {
170 before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.TRUE, MapInclusion.DEFAULT));
171 doTestSkipFailsFailsSkip();
172 }
173
174 @Test
175 public void testSecurityDefaultDTDsTrueExpansionFalse() throws Exception
176 {
177 before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.TRUE, MapInclusion.FALSE));
178 doTestSkipFailsFailsSkip();
179 }
180
181 @Test
182 public void testSecurityDefaultDTDsTrueExpansionTrue() throws Exception
183 {
184 before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.TRUE, MapInclusion.TRUE));
185 doTestSkipFailsFailsSkip();
186 }
187
188 @Test
189 public void testSecurityFalseDTDsDefaultExpansionDefault() throws Exception
190 {
191 before(getParameterMap(MapInclusion.FALSE, MapInclusion.DEFAULT, MapInclusion.DEFAULT));
192 doTestSkipPassesFailsSkip();
193 }
194
195 @Test
196 public void testSecurityFalseDTDsDefaultExpansionFalse() throws Exception
197 {
198 before(getParameterMap(MapInclusion.FALSE, MapInclusion.DEFAULT, MapInclusion.FALSE));
199 doTestSkipPassesFailsSkip();
200 }
201
202 @Test
203 public void testSecurityFalseDTDsDefaultExpansionTrue() throws Exception
204 {
205 before(getParameterMap(MapInclusion.FALSE, MapInclusion.DEFAULT, MapInclusion.TRUE));
206 doTestSkipPassesFailsSkip();
207 }
208
209 @Test
210 public void testSecurityFalseDTDsFalseExpansionDefault() throws Exception
211 {
212 before(getParameterMap(MapInclusion.FALSE, MapInclusion.FALSE, MapInclusion.DEFAULT));
213 doTestPassesPassesPassesFails();
214 }
215
216 @Test
217 public void testSecurityFalseDTDsFalseExpansionFalse() throws Exception
218 {
219 before(getParameterMap(MapInclusion.FALSE, MapInclusion.FALSE, MapInclusion.FALSE));
220 doTestPassesPassesPassesFails();
221 }
222
223 @Test
224 public void testSecurityFalseDTDsFalseExpansionTrue() throws Exception
225 {
226 before(getParameterMap(MapInclusion.FALSE, MapInclusion.FALSE, MapInclusion.TRUE));
227 doTestPassesPassesPassesPasses();
228 }
229
230 @Test
231 public void testSecurityFalseDTDsTrueExpansionDefault() throws Exception
232 {
233 before(getParameterMap(MapInclusion.FALSE, MapInclusion.TRUE, MapInclusion.DEFAULT));
234 doTestSkipPassesFailsSkip();
235 }
236
237 @Test
238 public void testSecurityFalseDTDsTrueExpansionFalse() throws Exception
239 {
240 before(getParameterMap(MapInclusion.FALSE, MapInclusion.TRUE, MapInclusion.FALSE));
241 doTestSkipPassesFailsSkip();
242 }
243
244 @Test
245 public void testSecurityFalseDTDsTrueExpansionTrue() throws Exception
246 {
247 before(getParameterMap(MapInclusion.FALSE, MapInclusion.TRUE, MapInclusion.TRUE));
248 doTestSkipPassesFailsSkip();
249 }
250
251 @Test
252 public void testSecurityTrueDTDsDefaultExpansionDefault() throws Exception
253 {
254 before(getParameterMap(MapInclusion.TRUE, MapInclusion.DEFAULT, MapInclusion.DEFAULT));
255 doTestSkipFailsFailsSkip();
256 }
257
258 @Test
259 public void testSecurityTrueDTDsDefaultExpansionFalse() throws Exception
260 {
261 before(getParameterMap(MapInclusion.TRUE, MapInclusion.DEFAULT, MapInclusion.FALSE));
262 doTestSkipFailsFailsSkip();
263 }
264
265 @Test
266 public void testSecurityTrueDTDsDefaultExpansionTrue() throws Exception
267 {
268 before(getParameterMap(MapInclusion.TRUE, MapInclusion.DEFAULT, MapInclusion.TRUE));
269 doTestSkipFailsFailsSkip();
270 }
271
272 @Test
273 public void testSecurityTrueDTDsFalseExpansionDefault() throws Exception
274 {
275 before(getParameterMap(MapInclusion.TRUE, MapInclusion.FALSE, MapInclusion.DEFAULT));
276 doTestFailsFailsPassesFails();
277 }
278
279 @Test
280 public void testSecurityTrueDTDsFalseExpansionFalse() throws Exception
281 {
282 before(getParameterMap(MapInclusion.TRUE, MapInclusion.FALSE, MapInclusion.FALSE));
283 doTestFailsFailsPassesFails();
284 }
285
286 @Test
287 public void testSecurityTrueDTDsFalseExpansionTrue() throws Exception
288 {
289 before(getParameterMap(MapInclusion.TRUE, MapInclusion.FALSE, MapInclusion.TRUE));
290 doTestFailsFailsPassesPasses();
291 }
292
293 @Test
294 public void testSecurityTrueDTDsTrueExpansionDefault() throws Exception
295 {
296 before(getParameterMap(MapInclusion.TRUE, MapInclusion.TRUE, MapInclusion.DEFAULT));
297 doTestSkipFailsFailsSkip();
298 }
299
300 @Test
301 public void testSecurityTrueDTDsTrueExpansionFalse() throws Exception
302 {
303 before(getParameterMap(MapInclusion.TRUE, MapInclusion.TRUE, MapInclusion.FALSE));
304 doTestSkipFailsFailsSkip();
305 }
306
307 @Test
308 public void testSecurityTrueDTDsTrueExpansionTrue() throws Exception
309 {
310 before(getParameterMap(MapInclusion.TRUE, MapInclusion.TRUE, MapInclusion.TRUE));
311 doTestSkipFailsFailsSkip();
312 }
313
314 ///////////////////////////////////////////////////////////////////////////////////////////////
315 void doTestSkipFailsFailsSkip() throws Exception
316 {
317 doMaxAttributesFails();
318 doDTDFails();
319 }
320
321 void doTestSkipPassesFailsSkip() throws Exception
322 {
323 doMaxAttributesPasses();
324 doDTDFails();
325 }
326
327 void doTestFailsFailsPassesFails() throws Exception
328 {
329 doEntityExpansionFails();
330 doMaxAttributesFails();
331 doDTDPasses();
332 doExternalEntityExpansionFails();
333 }
334
335 void doTestFailsFailsPassesPasses() throws Exception
336 {
337 doEntityExpansionFails();
338 doMaxAttributesFails();
339 doDTDPasses();
340 doExternalEntityExpansionPasses();
341 }
342
343 void doTestPassesPassesPassesFails() throws Exception
344 {
345 doEntityExpansionPasses();
346 doMaxAttributesPasses();
347 doDTDPasses();
348 doExternalEntityExpansionFails();
349 }
350
351 void doTestPassesPassesPassesPasses() throws Exception
352 {
353 doEntityExpansionPasses();
354 doMaxAttributesPasses();
355 doDTDPasses();
356 doExternalEntityExpansionPasses();
357 }
358
359 void doEntityExpansionFails() throws Exception
360 {
361 //System.out.println("entering doEntityExpansionFails()");
362 ClientRequest request = new ClientRequest(generateURL("/test"));
363 request.body("application/xml", bigExpansionDoc);
364 ClientResponse<?> response = request.post();
365 //System.out.println("status: " + response.getStatus());
366 String entity = response.getEntity(String.class);
367 //System.out.println("doEntityExpansionFails() result: " + entity);
368 Assert.assertEquals(400, response.getStatus());
369 Assert.assertTrue(entity.contains("org.xml.sax.SAXParseException"));
370 }
371
372 void doEntityExpansionPasses() throws Exception
373 {
374 //System.out.println("entering doEntityExpansionFails()");
375 ClientRequest request = new ClientRequest(generateURL("/test"));
376 request.body("application/xml", bigExpansionDoc);
377 ClientResponse<?> response = request.post();
378 //System.out.println("status: " + response.getStatus());
379 String entity = response.getEntity(String.class);
380 int len = Math.min(entity.length(), 30);
381 //System.out.println("doEntityExpansionPasses() result: " + entity.substring(0, len) + "...");
382 Assert.assertEquals(200, response.getStatus());
383 Assert.assertTrue(countFoos(entity) > 64000);
384 }
385
386 void doMaxAttributesFails() throws Exception
387 {
388 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
389 //System.out.println("dbf.getClass(): " + dbf.getClass());
390 if ("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl".equals(dbf.getClass().getName()))
391 {
392 //System.out.println("Testing with Red Hat version of Xerces, skipping max attributes test");
393 return;
394 }
395 //System.out.println("entering doMaxAttributesFails()");
396 ClientRequest request = new ClientRequest(generateURL("/test"));
397 request.body("application/xml", bigAttributeDoc);
398 ClientResponse<?> response = request.post();
399 //System.out.println("doMaxAttributesFails() status: " + response.getStatus());
400 String entity = response.getEntity(String.class);
401 //System.out.println("doMaxAttributesFails() result: " + entity);
402 Assert.assertEquals(400, response.getStatus());
403 Assert.assertTrue(entity.contains("org.xml.sax.SAXParseException"));
404 Assert.assertTrue(entity.contains("JAXP00010002:"));
405 if ("en".equals(System.getProperty("user.language"))) {
406 Assert.assertTrue(entity.contains("has more than \"10,00"));
407 int pos = entity.indexOf("has more than \"10,00");
408 Assert.assertTrue(entity.substring(pos).contains("attributes"));
409 }
410 }
411
412 void doMaxAttributesPasses() throws Exception
413 {
414 //System.out.println("entering doMaxAttributesPasses()");
415 ClientRequest request = new ClientRequest(generateURL("/test"));
416 request.body("application/xml", bigAttributeDoc);
417 ClientResponse<?> response = request.post();
418 //System.out.println("doMaxAttributesPasses() status: " + response.getStatus());
419 String entity = response.getEntity(String.class);
420 //System.out.println("doMaxAttributesPasses() result: " + entity);
421 Assert.assertEquals(200, response.getStatus());
422 Assert.assertEquals("bar", entity);
423 }
424
425 void doDTDFails() throws Exception
426 {
427 //System.out.println("entering doDTDFails()");
428 ClientRequest request = new ClientRequest(generateURL("/test"));
429 request.body("application/xml", smallDtd);
430 ClientResponse<?> response = request.post();
431 //System.out.println("status: " + response.getStatus());
432 String entity = response.getEntity(String.class);
433 //System.out.println("doDTDFails(): result: " + entity);
434 Assert.assertEquals(400, response.getStatus());
435 Assert.assertTrue(entity.contains("org.xml.sax.SAXParseException"));
436 Assert.assertTrue(entity.contains("DOCTYPE"));
437 Assert.assertTrue(entity.contains("http://apache.org/xml/features/disallow-doctype-decl"));
438 Assert.assertTrue(entity.contains("true"));
439 }
440
441 void doDTDPasses() throws Exception
442 {
443 //System.out.println("entering doDTDPasses()");
444 ClientRequest request = new ClientRequest(generateURL("/test"));
445 request.body("application/xml", smallDtd);
446 ClientResponse<?> response = request.post();
447 //System.out.println("status: " + response.getStatus());
448 String entity = response.getEntity(String.class);
449 //System.out.println("doDTDPasses() result: " + entity);
450 Assert.assertEquals(200, response.getStatus());
451 Assert.assertEquals("bar", entity);
452 }
453
454 void doExternalEntityExpansionFails() throws Exception
455 {
456 //System.out.println("entering doExternalEntityExpansionFails()");
457 ClientRequest request = new ClientRequest(generateURL("/test"));
458 request.body("application/xml", externalEntityDoc);
459 ClientResponse<?> response = request.post();
460 //System.out.println("status: " + response.getStatus());
461 String entity = response.getEntity(String.class);
462 //System.out.println("doExternalEntityExpansionFails() result: " + entity);
463 Assert.assertEquals(200, response.getStatus());
464 Assert.assertEquals("", entity);
465 }
466
467 void doExternalEntityExpansionPasses() throws Exception
468 {
469 //System.out.println("entering doExternalEntityExpansionPasses()");
470 ClientRequest request = new ClientRequest(generateURL("/test"));
471 request.body("application/xml", externalEntityDoc);
472 ClientResponse<?> response = request.post();
473 //System.out.println("status: " + response.getStatus());
474 String entity = response.getEntity(String.class);
475 int len = Math.min(entity.length(), 30);
476 //System.out.println("doExternalEntityExpansionPasses() result: " + entity.substring(0, len) + "...");
477 Assert.assertEquals(200, response.getStatus());
478 Assert.assertEquals("xx:xx:xx:xx:xx:xx:xx", entity);
479 }
480
481 ///////////////////////////////////////////////////////////////////////////////////////////////
482 private static Hashtable<String, String> getParameterMap(MapInclusion securityFeature, MapInclusion disableDTDs, MapInclusion expandEntities)
483 {
484 Hashtable<String, String> map = new Hashtable<String, String>();
485 switch (securityFeature)
486 {
487 case DEFAULT:
488 break;
489
490 case FALSE:
491 map.put("resteasy.document.secure.processing.feature", "false");
492 break;
493
494 case TRUE:
495 map.put("resteasy.document.secure.processing.feature", "true");
496 break;
497 }
498 switch (disableDTDs)
499 {
500 case DEFAULT:
501 break;
502
503 case FALSE:
504 map.put("resteasy.document.secure.disableDTDs", "false");
505 break;
506
507 case TRUE:
508 map.put("resteasy.document.secure.disableDTDs", "true");
509 break;
510 }
511 switch (expandEntities)
512 {
513 case DEFAULT:
514 break;
515
516 case FALSE:
517 map.put("resteasy.document.expand.entity.references", "false");
518 break;
519
520 case TRUE:
521 map.put("resteasy.document.expand.entity.references", "true");
522 break;
523 }
524 return map;
525 }
526
527 private static int countFoos(String s)
528 {
529 int count = 0;
530 int pos = 0;
531
532 while (pos >= 0)
533 {
534 pos = s.indexOf("foo", pos);
535 if (pos >= 0)
536 {
537 count++;
538 pos += 3;
539 }
540 }
541 return count;
542 }
543 }
0 org.jboss.resteasy.plugins.providers.SerializableProvider
1
0 keytool -genkey -v -alias server -keyalg RSA -keystore ./server_ks -dname "CN=localhost,OU=cn,O=cn,L=cn,ST=cn,C=cn" -storepass 123123 -keypass 123123
1 keytool -genkey -v -alias client -keyalg RSA -keystore ./client_ks -dname "CN=localhost,OU=cn,O=cn,L=cn,ST=cn,C=cn" -storepass 123123 -keypass 123123
2 keytool -export -alias server -keystore ./server_ks -file server_key.cer
3 keytool -import -trustcacerts -alias server -file ./server_key.cer -keystore ./client_ks
55 <parent>
66 <artifactId>resteasy-jaxrs-all</artifactId>
77 <groupId>org.jboss.resteasy</groupId>
8 <version>3.1.4.Final</version>
8 <version>3.5.0.Final</version>
99 </parent>
1010
1111 <artifactId>resteasy-jsapi</artifactId>
2020 </dependency>
2121 <dependency>
2222 <groupId>org.jboss.spec.javax.ws.rs</groupId>
23 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
23 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
2424 </dependency>
2525 <dependency>
2626 <groupId>org.jboss.spec.javax.servlet</groupId>
107107 }else if(this.entity instanceof Document){
108108 if(!contentTypeSet || REST._isXMLMIME(contentTypeSet))
109109 data = this.entity;
110 }else if(this.entity instanceof Object){
110 }else if(this.entity instanceof Object && !(this.entity instanceof FormData)){
111111 if(!contentTypeSet || REST._isJSONMIME(contentTypeSet))
112112 data = JSON.stringify(this.entity);
113113 }
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../pom.xml</relativePath>
88 </parent>
99
+0
-185
resteasy-legacy/pom.xml less more
0 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
2 <modelVersion>4.0.0</modelVersion>
3 <parent>
4 <groupId>org.jboss.resteasy</groupId>
5 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
7 <relativePath>../pom.xml</relativePath>
8 </parent>
9 <artifactId>resteasy-legacy</artifactId>
10 <name>RESTEasy Legacy</name>
11 <description/>
12 <packaging>jar</packaging>
13
14 <dependencies>
15 <dependency>
16 <groupId>org.jboss.resteasy</groupId>
17 <artifactId>resteasy-jaxrs</artifactId>
18 <version>${project.version}</version>
19 </dependency>
20 <dependency>
21 <groupId>org.jboss.resteasy</groupId>
22 <artifactId>resteasy-client</artifactId>
23 <version>${project.version}</version>
24 </dependency>
25
26 <dependency>
27 <groupId>junit</groupId>
28 <artifactId>junit</artifactId>
29 <scope>provided</scope>
30 </dependency>
31
32 <dependency>
33 <groupId>log4j</groupId>
34 <artifactId>log4j</artifactId>
35 <scope>provided</scope>
36 </dependency>
37 <dependency>
38 <groupId>org.slf4j</groupId>
39 <artifactId>slf4j-api</artifactId>
40 <scope>provided</scope>
41 </dependency>
42
43
44 <dependency>
45 <groupId>org.jboss.spec.javax.ws.rs</groupId>
46 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
47 </dependency>
48
49 <dependency>
50 <groupId>org.jboss.spec.javax.servlet</groupId>
51 <artifactId>jboss-servlet-api_3.1_spec</artifactId>
52 </dependency>
53
54 <!--
55 Needed for javax.annotation.security.* which is part of javaee 6 XXX
56 should this dependency be <scope>provided</scope> and only used if
57 detected runtime?
58 -->
59 <dependency>
60 <groupId>org.jboss.spec.javax.annotation</groupId>
61 <artifactId>jboss-annotations-api_1.2_spec</artifactId>
62 <scope>compile</scope>
63 </dependency>
64
65 <!-- javax.activation.DataSource provider is required by spec -->
66 <dependency>
67 <groupId>javax.activation</groupId>
68 <artifactId>activation</artifactId>
69 </dependency>
70
71 <!-- 4.0 refactor of apache httpclient -->
72 <dependency>
73 <groupId>org.apache.httpcomponents</groupId>
74 <artifactId>httpclient</artifactId>
75 </dependency>
76
77 <dependency>
78 <groupId>commons-io</groupId>
79 <artifactId>commons-io</artifactId>
80 </dependency>
81
82 <dependency>
83 <groupId>net.jcip</groupId>
84 <artifactId>jcip-annotations</artifactId>
85 </dependency>
86
87 <!-- Required by Hibernate Validator 5.x for testing -->
88 <dependency>
89 <groupId>org.jboss.spec.javax.el</groupId>
90 <artifactId>jboss-el-api_3.0_spec</artifactId>
91 <scope>test</scope>
92 </dependency>
93 <dependency>
94 <groupId>org.glassfish</groupId>
95 <artifactId>javax.el</artifactId>
96 <scope>test</scope>
97 </dependency>
98
99 <dependency>
100 <groupId>org.jboss.logging</groupId>
101 <artifactId>jboss-logging</artifactId>
102 </dependency>
103 <dependency>
104 <groupId>org.jboss.logging</groupId>
105 <artifactId>jboss-logging-annotations</artifactId>
106 </dependency>
107 <dependency>
108 <groupId>org.jboss.logging</groupId>
109 <artifactId>jboss-logging-processor</artifactId>
110 </dependency>
111
112
113
114 </dependencies>
115
116 <build>
117 <plugins>
118 <plugin>
119 <groupId>com.atlassian.maven.plugins</groupId>
120 <artifactId>maven-clover2-plugin</artifactId>
121 </plugin>
122 </plugins>
123 </build>
124 <profiles>
125 <profile>
126 <id>i18n</id>
127 <activation>
128 <property>
129 <name>i18n</name>
130 </property>
131 </activation>
132 <build>
133 <plugins>
134 <plugin>
135 <groupId>org.apache.maven.plugins</groupId>
136 <artifactId>maven-resources-plugin</artifactId>
137 <executions>
138 <execution>
139 <id>copy-resources</id>
140 <phase>initialize</phase>
141 <goals>
142 <goal>copy-resources</goal>
143 </goals>
144 <configuration>
145 <outputDirectory>${basedir}/src/main/resources/org/jboss/resteasy/resteasy_jaxrs/i18n</outputDirectory>
146 <resources>
147 <resource>
148 <directory>${basedir}/src/test/resources/i18n</directory>
149 <includes>
150 <include>*</include>
151 </includes>
152 </resource>
153 </resources>
154 <overwrite>true</overwrite>
155 </configuration>
156 </execution>
157 </executions>
158 </plugin>
159 <plugin>
160 <groupId>org.apache.maven.plugins</groupId>
161 <artifactId>maven-surefire-plugin</artifactId>
162 <executions>
163 <execution>
164 <id>i18</id>
165 <phase>test</phase>
166 <goals>
167 <goal>test</goal>
168 </goals>
169 <configuration>
170 <skip>false</skip>
171 <reuseForks>false</reuseForks>
172 <includes>
173 <include>**/I18nTestMessages_*.java</include>
174 </includes>
175 </configuration>
176 </execution>
177 </executions>
178 </plugin>
179 </plugins>
180 </build>
181 </profile>
182 </profiles>
183
184 </project>
+0
-18
resteasy-legacy/src/main/java/org/jboss/resteasy/annotations/interception/ClientInterceptor.java less more
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Identifies an interceptor as a client-side interceptor
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 @Target({ElementType.TYPE})
14 @Retention(RetentionPolicy.RUNTIME)
15 public @interface ClientInterceptor
16 {
17 }
+0
-20
resteasy-legacy/src/main/java/org/jboss/resteasy/annotations/interception/DecoderPrecedence.java less more
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * This interceptor is an Content-Encoding decoder. It is used with MessageBodyWriter interceptors.
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 @Target({ElementType.TYPE})
14 @Retention(RetentionPolicy.RUNTIME)
15 @Precedence("DECODER")
16 public @interface DecoderPrecedence
17 {
18 public static final String PRECEDENCE_STRING = "DECODER";
19 }
+0
-20
resteasy-legacy/src/main/java/org/jboss/resteasy/annotations/interception/EncoderPrecedence.java less more
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * This interceptor is an Content-Encoding encoder. It is used with MessageBodyWriter interceptors.
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 @Target({ElementType.TYPE})
14 @Retention(RetentionPolicy.RUNTIME)
15 @Precedence("ENCODER")
16 public @interface EncoderPrecedence
17 {
18 public static final String PRECEDENCE_STRING = "ENCODER";
19 }
+0
-21
resteasy-legacy/src/main/java/org/jboss/resteasy/annotations/interception/HeaderDecoratorPrecedence.java less more
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * HeaderDecoratorPrecedence interceptors should always come first as they decorate a response (on the server), or an
9 * outgoing request (on the client) with special, user-defined, headers. These headers may trigger behavior in other interceptors.
10 *
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @version $Revision: 1 $
13 */
14 @Target({ElementType.TYPE})
15 @Retention(RetentionPolicy.RUNTIME)
16 @Precedence("HEADER_DECORATOR")
17 public @interface HeaderDecoratorPrecedence
18 {
19 public static final String PRECEDENCE_STRING = "HEADER_DECORATOR";
20 }
+0
-17
resteasy-legacy/src/main/java/org/jboss/resteasy/annotations/interception/Precedence.java less more
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 */
11 @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
12 @Retention(RetentionPolicy.RUNTIME)
13 public @interface Precedence
14 {
15 String value();
16 }
+0
-22
resteasy-legacy/src/main/java/org/jboss/resteasy/annotations/interception/RedirectPrecedence.java less more
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Should be placed on a PreProcessInterceptor.
9 * This annotation specifies ordering of interceptors.
10 * Will run after SecurityPrecedence. These types of interceptors may redirect the request.
11 *
12 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
13 * @version $Revision: 1 $
14 */
15 @Target({ElementType.TYPE, ElementType.METHOD})
16 @Retention(RetentionPolicy.RUNTIME)
17 @Precedence("REDIRECT")
18 public @interface RedirectPrecedence
19 {
20 public static final String PRECEDENCE_STRING = "REDIRECT";
21 }
+0
-23
resteasy-legacy/src/main/java/org/jboss/resteasy/annotations/interception/SecurityPrecedence.java less more
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Should be placed on a PreProcessInterceptor.
9 * This annotation specifies ordering of interceptors.
10 * Security-based interceptors should always come first. They may look at headers, but they don't read the input
11 * stream.
12 *
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 */
16 @Target({ElementType.TYPE})
17 @Retention(RetentionPolicy.RUNTIME)
18 @Precedence("SECURITY")
19 public @interface SecurityPrecedence
20 {
21 public static final String PRECEDENCE_STRING = "SECURITY";
22 }
+0
-18
resteasy-legacy/src/main/java/org/jboss/resteasy/annotations/interception/ServerInterceptor.java less more
0 package org.jboss.resteasy.annotations.interception;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Identifies an interceptor as a server-side interceptor
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 @Target({ElementType.TYPE})
14 @Retention(RetentionPolicy.RUNTIME)
15 public @interface ServerInterceptor
16 {
17 }
+0
-41
resteasy-legacy/src/main/java/org/jboss/resteasy/annotations/legacy/ClientResponseType.java less more
0 package org.jboss.resteasy.annotations.legacy;
1
2 import org.jboss.resteasy.client.EntityTypeFactory;
3 import org.jboss.resteasy.client.core.VoidEntityTypeFactory;
4
5 import java.lang.annotation.ElementType;
6 import java.lang.annotation.Retention;
7 import java.lang.annotation.RetentionPolicy;
8 import java.lang.annotation.Target;
9
10 /**
11 * This is an annotation that you can add to a RESTEasy client interface that
12 * has a return type of Response.
13 * <p/>
14 * <p/>
15 * You have two options:
16 * <ol>
17 * <li>use the entityType property to set a Class that will always be returned
18 * <li>use the entityTypeFactory to determine which Class to use based on a
19 * factory that determines which class to use based on logic that uses the
20 * headers and status of the result.
21 * </ol>
22 * <p/>
23 * Note: if you want to use generic types, you can't use this annotation. You'll
24 * have to either use ClientResponse as part of your interface, or cast the
25 * resulting Response object as a ClientResponse.
26 *
27 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
28 * @version $Revision: 1 $
29 */
30
31 @Target({ElementType.METHOD})
32 @Retention(RetentionPolicy.RUNTIME)
33 @SuppressWarnings("unchecked")
34 @Deprecated
35 public @interface ClientResponseType
36 {
37 Class entityType() default Void.class;
38
39 Class<? extends EntityTypeFactory> entityTypeFactory() default VoidEntityTypeFactory.class;
40 }
+0
-22
resteasy-legacy/src/main/java/org/jboss/resteasy/client/ClientExecutor.java less more
0 package org.jboss.resteasy.client;
1
2 import javax.ws.rs.core.UriBuilder;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
8 *
9 * @see org.jboss.resteasy.client.jaxrs.ClientHttpEngine
10 */
11 @Deprecated
12 public interface ClientExecutor
13 {
14 ClientRequest createRequest(String uriTemplate);
15
16 ClientRequest createRequest(UriBuilder uriBuilder);
17
18 ClientResponse execute(ClientRequest request) throws Exception;
19
20 void close() throws Exception;
21 }
+0
-791
resteasy-legacy/src/main/java/org/jboss/resteasy/client/ClientRequest.java less more
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.Link;
3 import org.jboss.resteasy.client.LinkHeader;
4 import org.jboss.resteasy.client.core.BaseClientResponse;
5 import org.jboss.resteasy.client.core.ClientInterceptorRepositoryImpl;
6 import org.jboss.resteasy.core.interception.ClientExecutionContextImpl;
7 import org.jboss.resteasy.core.interception.ClientWriterInterceptorContext;
8 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
9 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
10 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
11 import org.jboss.resteasy.spi.ProviderFactoryDelegate;
12 import org.jboss.resteasy.spi.ResteasyProviderFactory;
13 import org.jboss.resteasy.spi.StringConverter;
14 import org.jboss.resteasy.util.Encode;
15 import org.jboss.resteasy.util.GenericType;
16
17 import javax.ws.rs.core.Cookie;
18 import javax.ws.rs.core.HttpHeaders;
19 import javax.ws.rs.core.MediaType;
20 import javax.ws.rs.core.MultivaluedMap;
21 import javax.ws.rs.core.UriBuilder;
22 import javax.ws.rs.ext.MessageBodyWriter;
23 import javax.ws.rs.ext.Providers;
24 import javax.ws.rs.ext.RuntimeDelegate;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.lang.annotation.Annotation;
29 import java.lang.reflect.Type;
30 import java.net.URI;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35
36 import static org.jboss.resteasy.util.HttpHeaderNames.ACCEPT;
37
38 /**
39 * Create a hand coded request to send to the server. You call methods like accept(), body(), pathParameter()
40 * etc. to create the state of the request. Then you call a get(), post(), etc. method to execute the request.
41 * After an execution of a request, the internal state remains the same. You can invoke the request again.
42 * You can clear the request with the clear() method.
43 *
44 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
45 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
46 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
47 * @version $Revision: 1 $
48 *
49 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
50 * @see javax.ws.rs.client.Invocation
51 */
52 @Deprecated
53 @SuppressWarnings("unchecked")
54 public class ClientRequest extends ClientInterceptorRepositoryImpl implements Cloneable
55 {
56 protected org.jboss.resteasy.spi.old.ResteasyProviderFactory providerFactory;
57 protected ResteasyUriBuilder uri;
58 protected ClientExecutor executor;
59 protected MultivaluedMap<String, Object> headers;
60 protected MultivaluedMap<String, String> queryParameters;
61 protected MultivaluedMap<String, String> formParameters;
62 protected MultivaluedMap<String, String> pathParameters;
63 protected MultivaluedMap<String, String> matrixParameters;
64 protected Object body;
65 protected Class bodyType;
66 protected Type bodyGenericType;
67 protected Annotation[] bodyAnnotations;
68 protected MediaType bodyContentType;
69 protected boolean followRedirects;
70 protected String httpMethod;
71 protected String finalUri;
72 protected List<String> pathParameterList;
73 protected LinkHeader linkHeader;
74 protected Map<String, Object> attributes = new HashMap<String, Object>();
75
76 private static String defaultExecutorClasss = "org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor";
77
78 /**
79 * Set the default executor class name.
80 *
81 * @param classname
82 */
83 public static void setDefaultExecutorClass(String classname)
84 {
85 defaultExecutorClasss = classname;
86 }
87
88 public static ClientExecutor getDefaultExecutor()
89 {
90 try
91 {
92 Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(defaultExecutorClasss);
93 return (ClientExecutor) clazz.newInstance();
94 }
95 catch (Exception e)
96 {
97 throw new RuntimeException(e);
98 }
99 }
100
101 public ClientRequest(String uriTemplate)
102 {
103 this(uriTemplate, getDefaultExecutor());
104 }
105
106 public ClientRequest(String uriTemplate, ClientExecutor executor)
107 {
108 this(getBuilder(uriTemplate), executor);
109 }
110
111 public ClientRequest(UriBuilder uri, ClientExecutor executor)
112 {
113 this(uri, executor, ResteasyProviderFactory.getInstance());
114 }
115
116 public ClientRequest(UriBuilder uri, ClientExecutor executor,
117 ResteasyProviderFactory providerFactory)
118 {
119 this.uri = (ResteasyUriBuilder) uri;
120 this.executor = executor;
121 if (providerFactory instanceof ProviderFactoryDelegate)
122 {
123 this.providerFactory = (org.jboss.resteasy.spi.old.ResteasyProviderFactory) ((ProviderFactoryDelegate) providerFactory)
124 .getDelegate();
125 }
126 else
127 {
128 this.providerFactory = (org.jboss.resteasy.spi.old.ResteasyProviderFactory) providerFactory;
129 }
130 }
131
132 /**
133 * Clear this request's state so that it can be re-used
134 */
135 public void clear()
136 {
137 headers = null;
138 queryParameters = null;
139 formParameters = null;
140 pathParameters = null;
141 matrixParameters = null;
142 body = null;
143 bodyType = null;
144 bodyGenericType = null;
145 bodyAnnotations = null;
146 bodyContentType = null;
147 httpMethod = null;
148 finalUri = null;
149 pathParameterList = null;
150 linkHeader = null;
151
152 }
153
154
155 private static UriBuilder getBuilder(String uriTemplate)
156 {
157 return new ResteasyUriBuilder().uriTemplate(uriTemplate);
158 }
159
160 public boolean followRedirects()
161 {
162 return followRedirects;
163 }
164
165 public Map<String, Object> getAttributes()
166 {
167 return attributes;
168 }
169
170 public ClientRequest followRedirects(boolean followRedirects)
171 {
172 this.followRedirects = followRedirects;
173 return this;
174 }
175
176 public ClientRequest accept(MediaType accepts)
177 {
178 return header(ACCEPT, accepts.toString());
179 }
180
181 public ClientRequest accept(String accept)
182 {
183 String curr = (String) getHeadersAsObjects().getFirst(ACCEPT);
184 if (curr != null)
185 curr += "," + accept;
186 else
187 curr = accept;
188 getHeadersAsObjects().putSingle(ACCEPT, curr);
189 return this;
190 }
191
192 protected String toString(Object object)
193 {
194 if (object instanceof String)
195 return (String) object;
196 StringConverter converter = providerFactory.getStringConverter(object
197 .getClass());
198 if (converter != null)
199 return converter.toString(object);
200 else
201 return object.toString();
202
203 }
204
205 protected String toHeaderString(Object object)
206 {
207 return providerFactory.toHeaderString(object);
208
209 }
210
211 public ClientRequest addLink(Link link)
212 {
213 if (linkHeader == null)
214 {
215 linkHeader = new LinkHeader();
216 }
217 linkHeader.getLinks().add(link);
218 return this;
219 }
220
221 public ClientRequest addLink(String title, String rel, String href, String type)
222 {
223 Link link = new Link(title, rel, href, type, null);
224 return addLink(link);
225 }
226
227 public ClientRequest formParameter(String parameterName, Object value)
228 {
229 getFormParameters().add(parameterName, toString(value));
230 return this;
231 }
232
233 public ClientRequest queryParameter(String parameterName, Object value)
234 {
235 getQueryParameters().add(parameterName, toString(value));
236 return this;
237 }
238
239 public ClientRequest matrixParameter(String parameterName, Object value)
240 {
241 getMatrixParameters().add(parameterName, toString(value));
242 return this;
243 }
244
245 public ClientRequest header(String headerName, Object value)
246 {
247 getHeadersAsObjects().add(headerName, value);
248 return this;
249 }
250
251 public ClientRequest cookie(String cookieName, Object value)
252 {
253 return cookie(new Cookie(cookieName, toString(value)));
254 }
255
256 public ClientRequest cookie(Cookie cookie)
257 {
258 return header(HttpHeaders.COOKIE, cookie);
259 }
260
261 public ClientRequest pathParameter(String parameterName, Object value)
262 {
263 getPathParameters().add(parameterName, toString(value));
264 return this;
265 }
266
267 public ClientRequest pathParameters(Object... values)
268 {
269 for (Object value : values)
270 {
271 getPathParameterList().add(toString(value));
272 }
273 return this;
274 }
275
276 public ClientRequest body(String contentType, Object data)
277 {
278 return body(MediaType.valueOf(contentType), data, data.getClass(), null,
279 null);
280 }
281
282 public ClientRequest body(MediaType contentType, Object data)
283 {
284 return body(contentType, data, data.getClass(), null, null);
285 }
286
287 public ClientRequest body(MediaType contentType, Object data,
288 GenericType genericType)
289 {
290 return body(contentType, data, genericType.getType(), genericType
291 .getGenericType(), null);
292 }
293
294 public ClientRequest body(MediaType contentType, Object data,
295 Type genericType)
296 {
297 return body(contentType, data, data.getClass(), genericType, null);
298 }
299
300 public ClientRequest body(MediaType contentType, Object data, Class type,
301 Type genericType, Annotation[] annotations)
302 {
303 this.body = data;
304 this.bodyContentType = contentType;
305 this.bodyGenericType = genericType;
306 this.bodyType = type;
307 this.bodyAnnotations = annotations;
308 return this;
309 }
310
311 public ResteasyProviderFactory getProviderFactory()
312 {
313 return providerFactory;
314 }
315
316 public ClientExecutor getExecutor()
317 {
318 return executor;
319 }
320
321 /**
322 * @return a copy of all header objects converted to a string
323 */
324 public MultivaluedMap<String, String> getHeaders()
325 {
326 MultivaluedMap<String, String> rtn = new MultivaluedMapImpl<String, String>();
327 if (headers == null) return rtn;
328 for (Map.Entry<String, List<Object>> entry : headers.entrySet())
329 {
330 for (Object obj : entry.getValue())
331 {
332 rtn.add(entry.getKey(), toHeaderString(obj));
333 }
334 }
335 return rtn;
336 }
337
338 public MultivaluedMap<String, Object> getHeadersAsObjects()
339 {
340 if (headers == null)
341 headers = new MultivaluedMapImpl<String, Object>();
342 return headers;
343 }
344
345 public MultivaluedMap<String, String> getQueryParameters()
346 {
347 if (queryParameters == null)
348 queryParameters = new MultivaluedMapImpl<String, String>();
349 return queryParameters;
350 }
351
352 public MultivaluedMap<String, String> getFormParameters()
353 {
354 if (formParameters == null)
355 formParameters = new MultivaluedMapImpl<String, String>();
356 return formParameters;
357 }
358
359 public MultivaluedMap<String, String> getPathParameters()
360 {
361 if (pathParameters == null)
362 pathParameters = new MultivaluedMapImpl<String, String>();
363 return pathParameters;
364 }
365
366 public List<String> getPathParameterList()
367 {
368 if (pathParameterList == null)
369 pathParameterList = new ArrayList<String>();
370 return pathParameterList;
371 }
372
373 public MultivaluedMap<String, String> getMatrixParameters()
374 {
375 if (matrixParameters == null)
376 matrixParameters = new MultivaluedMapImpl<String, String>();
377 return matrixParameters;
378 }
379
380 public Object getBody()
381 {
382 return body;
383 }
384
385 public Class getBodyType()
386 {
387 return bodyType;
388 }
389
390 public Type getBodyGenericType()
391 {
392 return bodyGenericType;
393 }
394
395 public Annotation[] getBodyAnnotations()
396 {
397 return bodyAnnotations;
398 }
399
400 public MediaType getBodyContentType()
401 {
402 return bodyContentType;
403 }
404
405 public String getHttpMethod()
406 {
407 return httpMethod;
408 }
409
410 public void setHttpMethod(String httpMethod)
411 {
412 this.httpMethod = httpMethod;
413 }
414
415 public ClientResponse execute() throws Exception
416 {
417 Providers current = ResteasyProviderFactory.getContextData(Providers.class);
418 ResteasyProviderFactory.pushContext(Providers.class, providerFactory);
419 try
420 {
421
422 if (linkHeader != null) header("Link", linkHeader);
423
424 if (getReaderInterceptorList().isEmpty())
425 {
426 setReaderInterceptors(providerFactory.getClientReaderInterceptorRegistry().postMatch(null, null));
427 }
428
429 if (getExecutionInterceptorList().isEmpty())
430 {
431 setExecutionInterceptors(providerFactory
432 .getClientExecutionInterceptorRegistry().bindForList(null, null));
433 }
434
435 BaseClientResponse response = null;
436 if (getExecutionInterceptorList().isEmpty())
437 {
438 response = (BaseClientResponse) executor.execute(this);
439 }
440 else
441 {
442 ClientExecutionContextImpl ctx = new ClientExecutionContextImpl(
443 getExecutionInterceptorList(), executor, this);
444 response = (BaseClientResponse) ctx.proceed();
445 }
446 response.setAttributes(attributes);
447 response.setReaderInterceptors(getReaderInterceptors());
448 return response;
449 }
450 finally
451 {
452 ResteasyProviderFactory.popContextData(Providers.class);
453 if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
454
455 }
456 }
457
458 public void writeRequestBody(MultivaluedMap<String, Object> headers,
459 OutputStream outputStream) throws IOException
460 {
461 if (body == null)
462 {
463 return;
464 }
465
466 if (getWriterInterceptorList().isEmpty())
467 {
468 setWriterInterceptors(providerFactory.getClientWriterInterceptorRegistry().postMatch(null, null));
469 }
470 new ClientWriterInterceptorContext(getWriterInterceptors(), providerFactory, body,
471 bodyType, bodyGenericType, bodyAnnotations, bodyContentType,
472 headers, outputStream, attributes).proceed();
473 }
474
475 public ClientResponse get() throws Exception
476 {
477 return httpMethod("GET");
478 }
479
480 /**
481 * Tries to automatically unmarshal to target type.
482 *
483 * @param returnType
484 * @param <T>
485 * @return
486 * @throws Exception
487 */
488 public <T> T getTarget(Class<T> returnType) throws Exception
489 {
490 BaseClientResponse<T> response = (BaseClientResponse<T>) get(returnType);
491 if (response.getStatus() == 204) return null;
492 if (response.getStatus() != 200) throw new ClientResponseFailure(response);
493 T obj = response.getEntity();
494 if (obj instanceof InputStream)
495 {
496 response.setWasReleased(true);
497 }
498 return obj;
499 }
500
501 /**
502 * Templates the returned ClientResponse for easy access to returned entity
503 *
504 * @param returnType
505 * @param <T>
506 * @return
507 * @throws Exception
508 */
509 public <T> ClientResponse<T> get(Class<T> returnType) throws Exception
510 {
511 BaseClientResponse response = (BaseClientResponse) get();
512 response.setReturnType(returnType);
513 return response;
514 }
515
516 public <T> ClientResponse<T> get(Class<T> returnType, Type genericType)
517 throws Exception
518 {
519 BaseClientResponse response = (BaseClientResponse) get();
520 response.setReturnType(returnType);
521 response.setGenericReturnType(genericType);
522 return response;
523 }
524
525 public <T> ClientResponse<T> get(GenericType type) throws Exception
526 {
527 BaseClientResponse response = (BaseClientResponse) get();
528 response.setReturnType(type.getType());
529 response.setGenericReturnType(type.getGenericType());
530 return response;
531 }
532
533 public ClientResponse head() throws Exception
534 {
535 return httpMethod("HEAD");
536 }
537
538 public ClientResponse put() throws Exception
539 {
540 return httpMethod("PUT");
541 }
542
543 public <T> ClientResponse<T> put(Class<T> returnType) throws Exception
544 {
545 BaseClientResponse response = (BaseClientResponse) put();
546 response.setReturnType(returnType);
547 return response;
548 }
549
550 public <T> ClientResponse<T> put(Class<T> returnType, Type genericType)
551 throws Exception
552 {
553 BaseClientResponse response = (BaseClientResponse) put();
554 response.setReturnType(returnType);
555 response.setGenericReturnType(genericType);
556 return response;
557 }
558
559 public <T> ClientResponse<T> put(GenericType type) throws Exception
560 {
561 BaseClientResponse response = (BaseClientResponse) put();
562 response.setReturnType(type.getType());
563 response.setGenericReturnType(type.getGenericType());
564 return response;
565 }
566
567 public ClientResponse post() throws Exception
568 {
569 return httpMethod("POST");
570 }
571
572 public <T> ClientResponse<T> post(Class<T> returnType) throws Exception
573 {
574 BaseClientResponse response = (BaseClientResponse) post();
575 response.setReturnType(returnType);
576 return response;
577 }
578
579 public <T> T postTarget(Class<T> returnType) throws Exception
580 {
581 BaseClientResponse<T> response = (BaseClientResponse<T>) post(returnType);
582 if (response.getStatus() == 204) return null;
583 if (response.getStatus() != 200) throw new ClientResponseFailure(response);
584 T obj = response.getEntity();
585 if (obj instanceof InputStream)
586 {
587 response.setWasReleased(true);
588 }
589 return obj;
590 }
591
592 public <T> ClientResponse<T> post(Class<T> returnType, Type genericType)
593 throws Exception
594 {
595 BaseClientResponse response = (BaseClientResponse) post();
596 response.setReturnType(returnType);
597 response.setGenericReturnType(genericType);
598 return response;
599 }
600
601 public <T> ClientResponse<T> post(GenericType type) throws Exception
602 {
603 BaseClientResponse response = (BaseClientResponse) post();
604 response.setReturnType(type.getType());
605 response.setGenericReturnType(type.getGenericType());
606 return response;
607 }
608
609 /**
610 * Automatically does POST/Create pattern. Will throw a ClientResponseFailure
611 * if status is something other than 201
612 *
613 * @return Link to created resource
614 * @throws Exception, ClientResponseFailure
615 */
616 public Link create() throws Exception, ClientResponseFailure
617 {
618 BaseClientResponse response = (BaseClientResponse) post();
619 if (response.getStatus() != 201) throw new ClientResponseFailure(response);
620 return response.getLocationLink();
621 }
622
623
624 public ClientResponse delete() throws Exception
625 {
626 return httpMethod("DELETE");
627 }
628
629 public <T> ClientResponse<T> delete(Class<T> returnType) throws Exception
630 {
631 BaseClientResponse response = (BaseClientResponse) delete();
632 response.setReturnType(returnType);
633 return response;
634 }
635
636 public <T> ClientResponse<T> delete(Class<T> returnType, Type genericType)
637 throws Exception
638 {
639 BaseClientResponse response = (BaseClientResponse) delete();
640 response.setReturnType(returnType);
641 response.setGenericReturnType(genericType);
642 return response;
643 }
644
645 public <T> ClientResponse<T> delete(GenericType type) throws Exception
646 {
647 BaseClientResponse response = (BaseClientResponse) delete();
648 response.setReturnType(type.getType());
649 response.setGenericReturnType(type.getGenericType());
650 return response;
651 }
652
653 public ClientResponse options() throws Exception
654 {
655 return httpMethod("OPTIONS");
656 }
657
658 public <T> ClientResponse<T> options(Class<T> returnType) throws Exception
659 {
660 BaseClientResponse response = (BaseClientResponse) options();
661 response.setReturnType(returnType);
662 return response;
663 }
664
665 public <T> ClientResponse<T> options(Class<T> returnType, Type genericType)
666 throws Exception
667 {
668 BaseClientResponse response = (BaseClientResponse) options();
669 response.setReturnType(returnType);
670 response.setGenericReturnType(genericType);
671 return response;
672 }
673
674 public <T> ClientResponse<T> options(GenericType type) throws Exception
675 {
676 BaseClientResponse response = (BaseClientResponse) options();
677 response.setReturnType(type.getType());
678 response.setGenericReturnType(type.getGenericType());
679 return response;
680 }
681
682 public ClientResponse httpMethod(String httpMethod) throws Exception
683 {
684 this.httpMethod = httpMethod;
685 return execute();
686 }
687
688 public <T> ClientResponse<T> httpMethod(String method, Class<T> returnType)
689 throws Exception
690 {
691 BaseClientResponse response = (BaseClientResponse) httpMethod(method);
692 response.setReturnType(returnType);
693 return response;
694 }
695
696 public <T> ClientResponse<T> httpMethod(String method, Class<T> returnType,
697 Type genericType) throws Exception
698 {
699 BaseClientResponse response = (BaseClientResponse) httpMethod(method);
700 response.setReturnType(returnType);
701 response.setGenericReturnType(genericType);
702 return response;
703 }
704
705 public <T> ClientResponse<T> httpMethod(String method, GenericType type)
706 throws Exception
707 {
708 BaseClientResponse response = (BaseClientResponse) httpMethod(method);
709 response.setReturnType(type.getType());
710 response.setGenericReturnType(type.getGenericType());
711 return response;
712 }
713
714 public void overrideUri(URI uri)
715 {
716 this.uri.uri(uri);
717 }
718
719 /**
720 * This method populates all path, matrix, and query parameters and saves it
721 * internally. Once its called once it returns the cached value.
722 *
723 * @return
724 * @throws Exception
725 */
726 public String getUri() throws Exception
727
728 {
729 if (finalUri != null)
730 return finalUri;
731
732 ResteasyUriBuilder builder = (ResteasyUriBuilder) uri.clone();
733 if (matrixParameters != null)
734 {
735 for (Map.Entry<String, List<String>> entry : matrixParameters
736 .entrySet())
737 {
738 List<String> values = entry.getValue();
739 for (String value : values)
740 builder.matrixParam(entry.getKey(), value);
741 }
742 }
743 if (queryParameters != null)
744 {
745 for (Map.Entry<String, List<String>> entry : queryParameters
746 .entrySet())
747 {
748 List<String> values = entry.getValue();
749 for (String value : values)
750 builder.clientQueryParam(entry.getKey(), value);
751 }
752 }
753 if (pathParameterList != null && !pathParameterList.isEmpty())
754 {
755 finalUri = builder.build(pathParameterList.toArray()).toString();
756 }
757 else if (pathParameters != null && !pathParameters.isEmpty())
758 {
759 for (Map.Entry<String, List<String>> entry : pathParameters.entrySet())
760 {
761 List<String> values = entry.getValue();
762 for (String value : values)
763 {
764 value = Encode.encodePathAsIs(value);
765 builder.substitutePathParam(entry.getKey(), value, true);
766 }
767 }
768 }
769 if (finalUri == null)
770 finalUri = builder.build().toString();
771 return finalUri;
772 }
773
774 public ClientRequest createSubsequentRequest(URI uri)
775 {
776 try
777 {
778 ClientRequest clone = (ClientRequest) this.clone();
779 clone.clear();
780 clone.uri = new ResteasyUriBuilder();
781 clone.uri.uri(uri);
782 return clone;
783 }
784 catch (CloneNotSupportedException e)
785 {
786 // this shouldn't happen
787 throw new RuntimeException(Messages.MESSAGES.clientRequestDoesntSupportClonable());
788 }
789 }
790 }
+0
-197
resteasy-legacy/src/main/java/org/jboss/resteasy/client/ClientRequestFactory.java less more
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.ClientInterceptorRepository;
3 import org.jboss.resteasy.client.core.ClientInterceptorRepositoryImpl;
4 import org.jboss.resteasy.client.core.ClientInvoker;
5 import org.jboss.resteasy.client.core.ClientInvokerInterceptorFactory;
6 import org.jboss.resteasy.client.core.ClientInvokerModifier;
7 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
8 import org.jboss.resteasy.client.core.marshallers.ResteasyClientProxy;
9 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
10 import org.jboss.resteasy.spi.ResteasyProviderFactory;
11
12 import java.net.URI;
13
14 /**
15 * Helper class that allows you to pre-initialize an Executor, preset some ClientRequest attributes (like follow redirects)
16 * and define some client-side interceptors you want applied
17 *
18 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
19 * @author Solomon Duskis
20 * @version $Revision: 1 $
21 *
22 * @see org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder
23 * @see org.jboss.resteasy.client.jaxrs.ResteasyWebTarget
24 */
25 @Deprecated
26 public class ClientRequestFactory
27 {
28 private ResteasyProviderFactory providerFactory;
29 private ClientExecutor executor;
30 private URI base = null;
31 private boolean applyDefaultInterceptors = false;
32 private boolean followRedirects = false;
33 private ClientInterceptorRepositoryImpl prefixInterceptors = new ClientInterceptorRepositoryImpl();
34 private ClientInterceptorRepositoryImpl suffixInterceptors = new ClientInterceptorRepositoryImpl();
35
36 public ClientRequestFactory()
37 {
38 init(null, null, null);
39 }
40
41 public ClientRequestFactory(URI base)
42 {
43 init(null, null, base);
44 }
45
46 public ClientRequestFactory(ClientExecutor executor, URI base)
47 {
48 init(executor, null, base);
49 }
50
51 public ClientRequestFactory(ClientExecutor executor,
52 ResteasyProviderFactory providerFactory)
53 {
54 init(executor, providerFactory, null);
55 }
56
57 public ClientRequestFactory(ClientExecutor executor,
58 ResteasyProviderFactory providerFactory, URI base)
59 {
60 init(executor, providerFactory, base);
61 }
62
63 private void init(ClientExecutor executor,
64 ResteasyProviderFactory providerFactory, URI base)
65 {
66 if (providerFactory == null)
67 this.providerFactory = ResteasyProviderFactory.getInstance();
68 else
69 this.providerFactory = providerFactory;
70 if (executor == null)
71 this.executor = new ApacheHttpClient4Executor();
72 else
73 this.executor = executor;
74 this.base = base;
75 }
76
77 public ClientRequestFactory(ClientRequestFactory other)
78 {
79 this.providerFactory = other.providerFactory;
80 this.executor = other.executor;
81 this.setBase(other.getBase());
82 this.applyDefaultInterceptors = other.applyDefaultInterceptors;
83 this.followRedirects = other.followRedirects;
84 other.prefixInterceptors
85 .copyClientInterceptorsTo(this.prefixInterceptors);
86 other.suffixInterceptors
87 .copyClientInterceptorsTo(this.suffixInterceptors);
88 }
89
90 public URI getBase()
91 {
92 return base;
93 }
94
95 public void setBase(URI base)
96 {
97 this.base = base;
98 }
99
100 public void enableDefaultInterceptors()
101 {
102 applyDefaultInterceptors = true;
103 }
104
105 public ClientInterceptorRepository getPrefixInterceptors()
106 {
107 return prefixInterceptors;
108 }
109
110 public ClientInterceptorRepository getSuffixInterceptors()
111 {
112 return suffixInterceptors;
113 }
114
115 public boolean isFollowRedirects()
116 {
117 return followRedirects;
118 }
119
120 public void setFollowRedirects(boolean followRedirects)
121 {
122 this.followRedirects = followRedirects;
123 }
124
125 private void applyInterceptors(ClientInterceptorRepositoryImpl repository)
126 {
127 prefixInterceptors.prefixClientInterceptorsTo(repository);
128 suffixInterceptors.copyClientInterceptorsTo(repository);
129 }
130
131 public ClientRequestFactory clone()
132 {
133 return new ClientRequestFactory(this);
134 }
135
136 public ClientRequest createRelativeRequest(String uriTemplate)
137 {
138 return createRequest(base.toString() + uriTemplate);
139 }
140
141 public ClientRequest createRequest(String uriTemplate)
142 {
143 ClientRequest clientRequest = new ClientRequest(new ResteasyUriBuilder()
144 .uriTemplate(uriTemplate), executor, providerFactory);
145 if (applyDefaultInterceptors)
146 {
147 ClientInvokerInterceptorFactory.applyDefaultInterceptors(
148 clientRequest, providerFactory);
149 }
150 if (followRedirects)
151 {
152 clientRequest.followRedirects();
153 }
154 applyInterceptors(clientRequest);
155 return clientRequest;
156 }
157
158 public <T> T getRelative(String uriTemplate, Class<T> type, Object... params)
159 throws Exception
160 {
161 return get(base.toString() + uriTemplate, type, params);
162 }
163
164 public <T> T get(String uriTemplate, Class<T> type, Object... params)
165 throws Exception
166 {
167 return createRequest(uriTemplate).followRedirects(true).pathParameters(
168 params).get(type).getEntity();
169 }
170
171 public <T> T createProxy(Class<T> clazz)
172 {
173 assert base != null;
174 return createProxy(clazz, base);
175 }
176
177 public <T> T createProxy(Class<T> clazz, String baseUri)
178 {
179 return createProxy(clazz, URI.create(baseUri));
180 }
181
182 public <T> T createProxy(Class<T> clazz, URI baseUri)
183 {
184 // right now all proxies get the default interceptors
185 T proxy = ProxyFactory.create(clazz, baseUri, executor, providerFactory);
186 ResteasyClientProxy clientProxy = (ResteasyClientProxy) proxy;
187 clientProxy.applyClientInvokerModifier(new ClientInvokerModifier()
188 {
189 public void modify(ClientInvoker invoker)
190 {
191 applyInterceptors(invoker);
192 }
193 });
194 return proxy;
195 }
196 }
+0
-150
resteasy-legacy/src/main/java/org/jboss/resteasy/client/ClientResponse.java less more
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.Link;
3 import org.jboss.resteasy.client.LinkHeader;
4 import org.jboss.resteasy.util.GenericType;
5
6 import javax.ws.rs.core.MultivaluedMap;
7 import javax.ws.rs.core.Response;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Type;
10 import java.util.Map;
11
12 /**
13 * Response extension for the RESTEasy client framework. Use this, or Response
14 * in your client proxy interface method return type declarations if you want
15 * access to the response entity as well as status and header information.
16 *
17 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 *
21 * @see javax.ws.rs.core.Response
22 * @see org.jboss.resteasy.client.jaxrs.internal.ClientResponse
23 */
24 @Deprecated
25 public abstract class ClientResponse<T> extends Response
26 {
27 /**
28 * This method returns the same exact map as Response.getMetadata() except as a map of strings rather than objects
29 *
30 * @return
31 */
32 public abstract MultivaluedMap<String, String> getResponseHeaders();
33
34 public abstract Response.Status getResponseStatus();
35
36 /**
37 * Unmarshal the target entity from the response OutputStream. You must have type information set via <T>
38 * otherwise, this will not work.
39 * <p/>
40 * This method actually does the reading on the OutputStream. It will only do the read once. Afterwards, it will
41 * cache the result and return the cached result.
42 *
43 * @return
44 */
45 public abstract T getEntity();
46
47 /**
48 * Extract the response body with the provided type information
49 * <p/>
50 * This method actually does the reading on the OutputStream. It will only do the read once. Afterwards, it will
51 * cache the result and return the cached result.
52 *
53 * @param type
54 * @param genericType
55 * @param <T2>
56 * @return
57 */
58 public abstract <T2> T2 getEntity(Class<T2> type);
59
60 /**
61 * Extract the response body with the provided type information
62 * <p/>
63 * This method actually does the reading on the OutputStream. It will only do the read once. Afterwards, it will
64 * cache the result and return the cached result.
65 *
66 * @param type
67 * @param genericType
68 * @param <T2>
69 * @return
70 */
71 public abstract <T2> T2 getEntity(Class<T2> type, Type genericType);
72
73 /**
74 * @param type
75 * @param genericType
76 * @param annotations
77 * @param <T2>
78 * @return
79 */
80 public abstract <T2> T2 getEntity(Class<T2> type, Type genericType, Annotation[] annotations);
81
82 /**
83 * Extract the response body with the provided type information. GenericType is a trick used to
84 * pass in generic type information to the resteasy runtime.
85 * <p/>
86 * For example:
87 * <pre>
88 * List<String> list = response.getEntity(new GenericType<List<String>() {});
89 *
90 *
91 * This method actually does the reading on the OutputStream. It will only do the read once. Afterwards, it will
92 * cache the result and return the cached result.
93 *
94 * @param type
95 * @param <T2>
96 * @return
97 */
98 public abstract <T2> T2 getEntity(GenericType<T2> type);
99
100 /**
101 * @param type
102 * @param annotations
103 * @param <T2>
104 * @return
105 */
106 public abstract <T2> T2 getEntity(GenericType<T2> type, Annotation[] annotations);
107
108 /**
109 * Get the <a href="http://tools.ietf.org/html/draft-nottingham-http-link-header-10">link headers</a> of the response.
110 * All Link objects returned will automatically have the same ClientExecutor as the request.
111 *
112 * @return non-null
113 */
114 public abstract LinkHeader getLinkHeader();
115
116 /**
117 * Get the Location header as a Link so you can easily execute on it.
118 * All Link objects returned will automatically have the same ClientExecutor as the request.
119 *
120 * @return
121 */
122 public abstract Link getLocationLink();
123
124 /**
125 * Header is assumed to be a URL, a Link object is created from it if it exists. Also, the type field of the
126 * link with be initialized if there is another header appended with -Type. i.e. if the header was "custom"
127 * it will also look for a header of custom-type and expect that this is a media type.
128 * <p/>
129 * All Link objects returned will automatically have the same ClientExecutor as the request.
130 *
131 * @param headerName
132 * @return null if it doesn't exist
133 */
134 public abstract Link getHeaderAsLink(String headerName);
135
136 /**
137 * Attempts to reset the InputStream of the response. Useful for refetching an entity after a marshalling failure
138 */
139 public abstract void resetStream();
140
141 public abstract void releaseConnection();
142
143 /**
144 * Used to pass information to and between interceptors.
145 *
146 * @return
147 */
148 public abstract Map<String, Object> getAttributes();
149 }
+0
-57
resteasy-legacy/src/main/java/org/jboss/resteasy/client/ClientResponseFailure.java less more
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.BaseClientResponse;
3
4 /**
5 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
6 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7 * @version $Revision: 1 $
8 *
9 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
10 * @see javax.ws.rs.client.ResponseProcessingException
11 * @see javax.ws.rs.client.ProcessingException
12 * @see javax.ws.rs.client.WebApplicationException
13 */
14 @Deprecated
15 public class ClientResponseFailure extends RuntimeException
16 {
17 private static final long serialVersionUID = 7491381058971118249L;
18 private ClientResponse response;
19
20 public ClientResponseFailure(ClientResponse response)
21 {
22 super("Failed with status: " + response.getStatus());
23 this.response = BaseClientResponse.copyFromError(response);
24 // release connection just in case it doesn't get garbage collected or manually released
25 response.releaseConnection();
26 }
27
28 public ClientResponseFailure(String s, ClientResponse response)
29 {
30 super(s);
31 this.response = BaseClientResponse.copyFromError(response);
32 // release the connection because we don't trust users to catch and clean up
33 response.releaseConnection();
34 }
35
36 public ClientResponseFailure(String s, Throwable throwable, ClientResponse response)
37 {
38 super(s, throwable);
39 this.response = BaseClientResponse.copyFromError(response);
40 // release the connection because we don't trust users to catch and clean up
41 response.releaseConnection();
42 }
43
44 public ClientResponseFailure(Throwable throwable, ClientResponse response)
45 {
46 super(throwable);
47 this.response = BaseClientResponse.copyFromError(response);
48 // release the connection because we don't trust users to catch and clean up
49 response.releaseConnection();
50 }
51
52 public ClientResponse getResponse()
53 {
54 return response;
55 }
56 }
+0
-26
resteasy-legacy/src/main/java/org/jboss/resteasy/client/ClientURI.java less more
0 package org.jboss.resteasy.client;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 /**
8 * Used to annotate a predefined URL (as opposed to a @PAthParam /@QueryParam)
9 * in a Proxied client.<br>
10 * <p/>
11 * For Example:
12 * <p/>
13 *
14 * @author <a href="mailto:sduskis@gmail.com">Solomon</a>
15 * @version $Revision: 1 $
16 * @GET MyDTO getDTO(@ClientURI String uri);
17 * @deprecated Use org.jboss.resteasy.annotations.ClientURI instead.
18 */
19 @Target({ElementType.PARAMETER})
20 @Retention(RetentionPolicy.RUNTIME)
21 @Deprecated
22 public @interface ClientURI
23 {
24
25 }
+0
-21
resteasy-legacy/src/main/java/org/jboss/resteasy/client/EntityTypeFactory.java less more
0 package org.jboss.resteasy.client;
1
2 import javax.ws.rs.core.MultivaluedMap;
3
4 /**
5 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
6 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7 * @version $Revision: 1 $
8 *
9 * <p>
10 * <b>Note.</b> org.jboss.resteasy.client.ClientResponse<T> is a generic type in the Resteasy client framework,
11 * but org.jboss.resteasy.client.jaxrs.internal.ClientResponse in the resteasy-client module is not, so
12 * EntityTypeFactory is no longer useful.
13 *
14 */
15 @Deprecated
16 public interface EntityTypeFactory
17 {
18 @SuppressWarnings("unchecked")
19 Class getEntityType(int status, MultivaluedMap<String, Object> metadata);
20 }
+0
-162
resteasy-legacy/src/main/java/org/jboss/resteasy/client/Link.java less more
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.specimpl.LinkBuilderImpl;
5 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
6
7 import javax.ws.rs.core.MultivaluedMap;
8 import java.util.List;
9 import java.util.Map;
10
11 /**
12 * Implementation of <a href="http://tools.ietf.org/html/draft-nottingham-http-link-header-06">Link Headers v6</a>
13 *
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 *
17 * @deprecated Replaced by javax.ws.rs.core.Link in jaxrs-api module.
18 *
19 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
20 * @see javax.ws.rs.core.Link
21 */
22 @Deprecated
23 public class Link
24 {
25 protected String title;
26 protected String relationship;
27 protected String href;
28 protected String type;
29 protected MultivaluedMap<String, String> extensions = new MultivaluedMapImpl<String, String>();
30 protected ClientExecutor executor;
31
32 public Link()
33 {
34 }
35
36 public Link(String title, String relationship, String href, String type, MultivaluedMap<String, String> extensions)
37 {
38 this.relationship = relationship;
39 this.href = href;
40 this.type = type;
41 this.title = title;
42 if (extensions != null) this.extensions = extensions;
43 }
44
45 public javax.ws.rs.core.Link toJaxrsLink()
46 {
47 javax.ws.rs.core.Link.Builder builder = new LinkBuilderImpl();
48 builder.rel(getRelationship());
49 builder.title(getTitle());
50 builder.type(getType());
51 builder.uri(getHref());
52 for (Map.Entry<String, List<String>> entry : getExtensions().entrySet())
53 {
54 for (String val : entry.getValue())
55 {
56 builder.param(entry.getKey(), val);
57 }
58 }
59 return builder.build();
60 }
61
62 public String getRelationship()
63 {
64 return relationship;
65 }
66
67 public void setRelationship(String relationship)
68 {
69 this.relationship = relationship;
70 }
71
72 public String getHref()
73 {
74 return href;
75 }
76
77 public void setHref(String href)
78 {
79 this.href = href;
80 }
81
82 public String getType()
83 {
84 return type;
85 }
86
87 public void setType(String type)
88 {
89 this.type = type;
90 }
91
92 public String getTitle()
93 {
94 return title;
95 }
96
97 public void setTitle(String title)
98 {
99 this.title = title;
100 }
101
102 public MultivaluedMap<String, String> getExtensions()
103 {
104 return extensions;
105 }
106
107 public ClientExecutor getExecutor()
108 {
109 return executor;
110 }
111
112 public void setExecutor(ClientExecutor executor)
113 {
114 this.executor = executor;
115 }
116
117 public ClientRequest request()
118 {
119 if (executor != null)
120 {
121 return new ClientRequest(href, executor);
122 }
123 else
124 {
125 return new ClientRequest(href);
126 }
127 }
128
129 public ClientRequest request(ClientExecutor executor)
130 {
131 return new ClientRequest(href, executor);
132 }
133
134 public String toString()
135 {
136 StringBuffer buf = new StringBuffer("<");
137 buf.append(href).append(">");
138 if (relationship != null)
139 {
140 buf.append("; rel=\"").append(relationship).append("\"");
141 }
142 if (type != null)
143 {
144 buf.append("; type=\"").append(type).append("\"");
145 }
146 if (title != null)
147 {
148 buf.append("; title=\"").append(title).append("\"");
149 }
150 for (String key : getExtensions().keySet())
151 {
152 List<String> values = getExtensions().get(key);
153 for (String val : values)
154 {
155 buf.append("; ").append(key).append("=\"").append(val).append("\"");
156 }
157 }
158 return buf.toString();
159 }
160
161 }
+0
-88
resteasy-legacy/src/main/java/org/jboss/resteasy/client/LinkHeader.java less more
0 package org.jboss.resteasy.client;
1
2 import java.util.ArrayList;
3 import java.util.HashMap;
4 import java.util.List;
5 import java.util.Map;
6
7 import org.jboss.resteasy.client.LinkHeaderDelegate;
8
9 /**
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 @Deprecated
14 public class LinkHeader
15 {
16 private Map<String, Link> linksByRelationship = new HashMap<String, Link>();
17 private Map<String, Link> linksByTitle = new HashMap<String, Link>();
18 private List<Link> links = new ArrayList<Link>();
19
20 public LinkHeader addLink(final Link link)
21 {
22 links.add(link);
23 return this;
24 }
25
26 public LinkHeader addLink(final String title, final String rel, final String href, final String type)
27 {
28 final Link link = new Link(title, rel, href, type, null);
29 return addLink(link);
30 }
31
32 public Link getLinkByTitle(String title)
33 {
34 return linksByTitle.get(title);
35 }
36
37 public Link getLinkByRelationship(String rel)
38 {
39 return linksByRelationship.get(rel);
40 }
41
42 /**
43 * Index of links by relationship "rel" or "rev"
44 *
45 * @return
46 */
47 public Map<String, Link> getLinksByRelationship()
48 {
49 return linksByRelationship;
50 }
51
52 /**
53 * Index of links by title
54 *
55 * @return
56 */
57 public Map<String, Link> getLinksByTitle()
58 {
59 return linksByTitle;
60 }
61
62 /**
63 * All the links defined
64 *
65 * @return
66 */
67 public List<Link> getLinks()
68 {
69 return links;
70 }
71
72 public static LinkHeader valueOf(String val)
73 {
74 return LinkHeaderDelegate.from(val);
75 }
76
77 public String toString()
78 {
79 StringBuffer buf = new StringBuffer();
80 for (Link link : getLinks())
81 {
82 if (buf.length() > 0) buf.append(", ");
83 buf.append(link.toString());
84 }
85 return buf.toString();
86 }
87 }
+0
-197
resteasy-legacy/src/main/java/org/jboss/resteasy/client/LinkHeaderDelegate.java less more
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
3 import org.jboss.resteasy.client.Link;
4 import org.jboss.resteasy.client.LinkHeader;
5 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
6
7
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.RuntimeDelegate;
10
11 import java.util.HashSet;
12 import java.util.List;
13 import java.util.Set;
14 import java.util.StringTokenizer;
15
16 /**
17 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
18 * @version $Revision: 1 $
19 */
20 @Deprecated
21 public class LinkHeaderDelegate implements RuntimeDelegate.HeaderDelegate<LinkHeader>
22 {
23 private static class Parser
24 {
25 private int curr;
26 private String value;
27 private LinkHeader header = new LinkHeader();
28
29 public Parser(String value)
30 {
31 this.value = value;
32 }
33
34 public LinkHeader getHeader()
35 {
36 return header;
37 }
38
39 public void parse()
40 {
41 String href = null;
42 MultivaluedMap<String, String> attributes = new MultivaluedMapImpl<String, String>();
43 while (curr < value.length())
44 {
45
46 char c = value.charAt(curr);
47 if (c == '<')
48 {
49 if (href != null)
50 throw new IllegalArgumentException(Messages.MESSAGES.unableToParseLinkHeaderTooManyLinks(value));
51 href = parseLink();
52 }
53 else if (c == ';' || c == ' ')
54 {
55 curr++;
56 continue;
57 }
58 else if (c == ',')
59 {
60 populateLink(href, attributes);
61 href = null;
62 attributes = new MultivaluedMapImpl<String, String>();
63 curr++;
64 }
65 else
66 {
67 parseAttribute(attributes);
68 }
69 }
70 populateLink(href, attributes);
71
72
73 }
74
75 protected void populateLink(String href, MultivaluedMap<String, String> attributes)
76 {
77 List<String> rels = attributes.get("rel");
78 List<String> revs = attributes.get("rev");
79 String title = attributes.getFirst("title");
80 if (title != null) attributes.remove("title");
81 String type = attributes.getFirst("type");
82 if (type != null) attributes.remove("type");
83
84 Set<String> relationships = new HashSet<String>();
85 if (rels != null)
86 {
87 relationships.addAll(rels);
88 attributes.remove("rel");
89 }
90 if (revs != null)
91 {
92 relationships.addAll(revs);
93 attributes.remove("rev");
94 }
95
96 for (String relationship : relationships)
97 {
98 StringTokenizer tokenizer = new StringTokenizer(relationship);
99 while (tokenizer.hasMoreTokens())
100 {
101 String rel = tokenizer.nextToken();
102 Link link = new Link(title, rel, href, type, attributes);
103 header.getLinksByRelationship().put(rel, link);
104 header.getLinksByTitle().put(title, link);
105 header.getLinks().add(link);
106 }
107
108 }
109 }
110
111 public String parseLink()
112 {
113 int end = value.indexOf('>', curr);
114 if (end == -1) throw new IllegalArgumentException(Messages.MESSAGES.unableToParseLinkHeaderNoEndToLink(value));
115 String href = value.substring(curr + 1, end);
116 curr = end + 1;
117 return href;
118 }
119
120 public void parseAttribute(MultivaluedMap<String, String> attributes)
121 {
122 int end = value.indexOf('=', curr);
123 if (end == -1 || end + 1 >= value.length())
124 throw new IllegalArgumentException(Messages.MESSAGES.unableToParseLinkHeaderNoEndToParameter(value));
125 String name = value.substring(curr, end);
126 name = name.trim();
127 curr = end + 1;
128 String val = null;
129 if (curr >= value.length())
130 {
131 val = "";
132 }
133 else
134 {
135
136 if (value.charAt(curr) == '"')
137 {
138 if (curr + 1 >= value.length())
139 throw new IllegalArgumentException(Messages.MESSAGES.unableToParseLinkHeaderNoEndToParameter(value));
140 curr++;
141 end = value.indexOf('"', curr);
142 if (end == -1)
143 throw new IllegalArgumentException(Messages.MESSAGES.unableToParseLinkHeaderNoEndToParameter(value));
144 val = value.substring(curr, end);
145 curr = end + 1;
146 }
147 else
148 {
149 StringBuffer buf = new StringBuffer();
150 while (curr < value.length())
151 {
152 char c = value.charAt(curr);
153 if (c == ',' || c == ';') break;
154 buf.append(value.charAt(curr));
155 curr++;
156 }
157 val = buf.toString();
158 }
159 }
160 attributes.add(name, val);
161
162 }
163
164 }
165
166 public LinkHeader fromString(String value) throws IllegalArgumentException
167 {
168 return from(value);
169 }
170
171 public static LinkHeader from(String value) throws IllegalArgumentException
172 {
173 if (value == null) throw new IllegalArgumentException(Messages.MESSAGES.paramNull());
174 Parser parser = new Parser(value);
175 parser.parse();
176 return parser.getHeader();
177
178 }
179
180 public String toString(LinkHeader value)
181 {
182 if (value == null) throw new IllegalArgumentException(Messages.MESSAGES.paramNull());
183 return getString(value);
184 }
185
186 public static String getString(LinkHeader value)
187 {
188 StringBuffer buf = new StringBuffer();
189 for (Link link : value.getLinks())
190 {
191 if (buf.length() > 0) buf.append(", ");
192 buf.append(link.toString());
193 }
194 return buf.toString();
195 }
196 }
+0
-173
resteasy-legacy/src/main/java/org/jboss/resteasy/client/ProxyBuilder.java less more
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.ClientProxy;
3 import org.jboss.resteasy.client.core.MethodInvoker;
4 import org.jboss.resteasy.client.core.SubResourceInvoker;
5 import org.jboss.resteasy.client.core.extractors.DefaultEntityExtractorFactory;
6 import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory;
7 import org.jboss.resteasy.client.core.marshallers.ResteasyClientProxy;
8 import org.jboss.resteasy.spi.ProviderFactoryDelegate;
9 import org.jboss.resteasy.spi.ResteasyProviderFactory;
10 import org.jboss.resteasy.util.IsHttpMethod;
11
12 import javax.ws.rs.Path;
13 import javax.ws.rs.core.MediaType;
14 import java.lang.reflect.Method;
15 import java.lang.reflect.Proxy;
16 import java.net.URI;
17 import java.util.Arrays;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Set;
22
23 /**
24 *
25 * @param <T>
26 * @deprecated The Resteasy proxy facility in the client framework in resteasy-jaxrs is replaced by the
27 * proxy facility extension in the JAX-RS 2.0 compliant resteasy-client module.
28 *
29 * @see resteasy-client
30 * @see org.jboss.resteasy.client.jaxrs.ProxyBuilder
31 * @see org.jboss.resteasy.client.jaxrs.ResteasyWebTarget
32 */
33 @Deprecated
34 public class ProxyBuilder<T>
35 {
36 public static <T> ProxyBuilder<T> build(Class<T> iface, URI base)
37 {
38 return new ProxyBuilder<T>(iface, base);
39 }
40
41 public static <T> ProxyBuilder<T> build(Class<T> iface, String base)
42 {
43 return new ProxyBuilder<T>(iface, ProxyFactory.createUri(base));
44 }
45
46 private final Class<T> iface;
47 private final URI baseUri;
48 private ClassLoader loader;
49 private ClientExecutor executor;
50 private ResteasyProviderFactory providerFactory;
51 private EntityExtractorFactory extractorFactory;
52 private Map<String, Object> requestAttributes;
53 private MediaType serverConsumes;
54 private MediaType serverProduces;
55
56 private ProxyBuilder(Class<T> iface, URI base)
57 {
58 this.iface = iface;
59 this.baseUri = base;
60 this.loader = iface.getClassLoader();
61 }
62
63 public ProxyBuilder<T> classloader(ClassLoader cl)
64 {
65 this.loader = cl;
66 return this;
67 }
68
69 public ProxyBuilder<T> executor(ClientExecutor exec)
70 {
71 this.executor = exec;
72 return this;
73 }
74
75 public ProxyBuilder<T> providerFactory(ResteasyProviderFactory fact)
76 {
77 this.providerFactory = fact;
78 return this;
79 }
80
81 public ProxyBuilder<T> extractorFactory(EntityExtractorFactory fact)
82 {
83 this.extractorFactory = fact;
84 return this;
85 }
86
87 /** shortcut for serverProduces(type).serverConsumes(type) */
88 public ProxyBuilder<T> serverMediaType(MediaType type)
89 {
90 this.serverProduces = type;
91 this.serverConsumes = type;
92 return this;
93 }
94
95 public ProxyBuilder<T> serverProduces(MediaType type)
96 {
97 this.serverProduces = type;
98 return this;
99 }
100
101 public ProxyBuilder<T> serverConsumes(MediaType type)
102 {
103 this.serverConsumes = type;
104 return this;
105 }
106
107 public ProxyBuilder<T> requestAttributes(Map<String, Object> attrs)
108 {
109 this.requestAttributes = attrs;
110 return this;
111 }
112
113 private static final Class<?>[] cClassArgArray =
114 {
115 Class.class
116 };
117
118 public T now()
119 {
120 if (providerFactory instanceof ProviderFactoryDelegate)
121 providerFactory = ((ProviderFactoryDelegate) providerFactory).getDelegate();
122
123 if (executor == null)
124 executor = ClientRequest.getDefaultExecutor();
125 if (providerFactory == null)
126 providerFactory = ResteasyProviderFactory.getInstance();
127 if (extractorFactory == null)
128 extractorFactory = new DefaultEntityExtractorFactory();
129 if (requestAttributes == null)
130 requestAttributes = Collections.emptyMap();
131
132 final ProxyConfig config = new ProxyConfig(loader, executor, providerFactory, extractorFactory, requestAttributes, serverConsumes, serverProduces);
133 return createProxy(iface, baseUri, config);
134 }
135
136 @SuppressWarnings("unchecked")
137 public static <T> T createProxy(final Class<T> iface, URI baseUri, final ProxyConfig config)
138 {
139 HashMap<Method, MethodInvoker> methodMap = new HashMap<Method, MethodInvoker>();
140 for (Method method : iface.getMethods())
141 {
142 // ignore the as method to allow declaration in client interfaces
143 if (!("as".equals(method.getName()) && Arrays.equals(method.getParameterTypes(), cClassArgArray)))
144 {
145 MethodInvoker invoker;
146 Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
147 if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface())
148 {
149 invoker = new SubResourceInvoker(baseUri, method, config);
150 }
151 else
152 {
153 invoker = ProxyFactory.createClientInvoker(iface, method, baseUri, config);
154 }
155 methodMap.put(method, invoker);
156 }
157 }
158
159 Class<?>[] intfs =
160 {
161 iface, ResteasyClientProxy.class
162 };
163
164 ClientProxy clientProxy = new ClientProxy(methodMap, baseUri, config);
165 // this is done so that equals and hashCode work ok. Adding the proxy to a
166 // Collection will cause equals and hashCode to be invoked. The Spring
167 // infrastructure had some problems without this.
168 clientProxy.setClazz(iface);
169
170 return (T) Proxy.newProxyInstance(config.getLoader(), intfs, clientProxy);
171 }
172 }
+0
-73
resteasy-legacy/src/main/java/org/jboss/resteasy/client/ProxyConfig.java less more
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.core.MediaType;
6 import java.util.Map;
7
8 /**
9 * @deprecated The Resteasy proxy facility in the client framework in resteasy-jaxrs is replaced by the
10 * proxy facility extension in the JAX-RS 2.0 compliant resteasy-client module.
11 *
12 * @see resteasy-client
13 * @see org.jboss.resteasy.client.jaxrs.ProxyConfig
14 */
15 @Deprecated
16 public class ProxyConfig
17 {
18 private final ClassLoader loader;
19 private final ClientExecutor executor;
20 private final ResteasyProviderFactory providerFactory;
21 private final EntityExtractorFactory extractorFactory;
22 private final Map<String, Object> requestAttributes;
23 private final MediaType serverConsumes;
24 private final MediaType serverProduces;
25
26 public ProxyConfig(ClassLoader loader, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map<String, Object> requestAttributes, MediaType serverConsumes, MediaType serverProduces)
27 {
28 super();
29 this.loader = loader;
30 this.executor = executor;
31 this.providerFactory = providerFactory;
32 this.extractorFactory = extractorFactory;
33 this.requestAttributes = requestAttributes;
34 this.serverConsumes = serverConsumes;
35 this.serverProduces = serverProduces;
36 }
37
38 public ClassLoader getLoader()
39 {
40 return loader;
41 }
42
43 public ClientExecutor getExecutor()
44 {
45 return executor;
46 }
47
48 public ResteasyProviderFactory getProviderFactory()
49 {
50 return providerFactory;
51 }
52
53 public EntityExtractorFactory getExtractorFactory()
54 {
55 return extractorFactory;
56 }
57
58 public Map<String, Object> getRequestAttributes()
59 {
60 return requestAttributes;
61 }
62
63 public MediaType getServerConsumes()
64 {
65 return serverConsumes;
66 }
67
68 public MediaType getServerProduces()
69 {
70 return serverProduces;
71 }
72 }
+0
-103
resteasy-legacy/src/main/java/org/jboss/resteasy/client/ProxyFactory.java less more
0 package org.jboss.resteasy.client;
1
2 import org.jboss.resteasy.client.core.ClientInvoker;
3 import org.jboss.resteasy.client.core.ClientInvokerInterceptorFactory;
4 import org.jboss.resteasy.client.core.extractors.DefaultEntityExtractorFactory;
5 import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory;
6 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
7 import org.jboss.resteasy.spi.ResteasyProviderFactory;
8 import org.jboss.resteasy.util.IsHttpMethod;
9
10 import java.lang.reflect.Method;
11 import java.net.URI;
12 import java.net.URISyntaxException;
13 import java.util.HashMap;
14 import java.util.Map;
15 import java.util.Set;
16
17 /**
18 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
19 * @version $Revision: 1 $
20 *
21 * @deprecated The Resteasy proxy facility in the client framework in resteasy-jaxrs is replaced by the
22 * proxy facility extension in the JAX-RS 2.0 compliant resteasy-client module.
23 *
24 * @see resteasy-client
25 * @see org.jboss.resteasy.client.jaxrs.ProxyBuilder
26 * @see org.jboss.resteasy.client.jaxrs.ResteasyWebTarget
27 */
28 @Deprecated
29 public class ProxyFactory
30 {
31
32 public static <T> T create(Class<T> clazz, String base)
33 {
34 return create(clazz, base, ClientRequest.getDefaultExecutor());
35 }
36
37 public static <T> T create(Class<T> clazz, String base, Map<String, Object> requestAttributes)
38 {
39 return create(clazz, createUri(base), ClientRequest.getDefaultExecutor(), ResteasyProviderFactory.getInstance(), new DefaultEntityExtractorFactory(), requestAttributes);
40 }
41
42 public static <T> T create(Class<T> clazz, String base, ResteasyProviderFactory providerFactory, Map<String, Object> requestAttributes)
43 {
44 return create(clazz, createUri(base), ClientRequest.getDefaultExecutor(), providerFactory, new DefaultEntityExtractorFactory(), requestAttributes);
45 }
46
47 public static <T> T create(Class<T> clazz, String base, ClientExecutor client)
48 {
49 return create(clazz, createUri(base), client, ResteasyProviderFactory.getInstance());
50 }
51
52 public static URI createUri(String base)
53 {
54 try
55 {
56 return new URI(base);
57 }
58 catch (URISyntaxException e)
59 {
60 throw new RuntimeException(e);
61 }
62 }
63
64 public static <T> T create(Class<T> clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory)
65 {
66 return create(clazz, baseUri, executor, providerFactory, new DefaultEntityExtractorFactory());
67 }
68
69 public static <T> T create(Class<T> clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory)
70 {
71 return create(clazz, baseUri, executor, providerFactory, extractorFactory, new HashMap<String, Object>());
72 }
73
74 public static <T> T create(Class<T> clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map<String, Object> requestAttributes)
75 {
76 return ProxyBuilder.build(clazz, baseUri).executor(executor).providerFactory(providerFactory).extractorFactory(extractorFactory).requestAttributes(requestAttributes).now();
77 }
78
79 public static <T> ClientInvoker createClientInvoker(Class<T> clazz, Method method, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory)
80 {
81 return createClientInvoker(clazz, method, baseUri, executor, providerFactory, extractorFactory, new HashMap<String, Object>());
82 }
83
84 public static <T> ClientInvoker createClientInvoker(Class<T> clazz, Method method, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map<String, Object> requestAttributes)
85 {
86 return createClientInvoker(clazz, method, baseUri, new ProxyConfig(null, executor, providerFactory, extractorFactory, requestAttributes, null, null));
87 }
88
89 public static <T> ClientInvoker createClientInvoker(Class<T> clazz, Method method, URI baseUri, ProxyConfig config)
90 {
91 Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
92 if (httpMethods == null || httpMethods.size() != 1)
93 {
94 throw new RuntimeException(Messages.MESSAGES.mustUseOneHttpMethod(method.toString()));
95 }
96 ClientInvoker invoker = new ClientInvoker(baseUri, clazz, method, config);
97 invoker.getAttributes().putAll(config.getRequestAttributes());
98 ClientInvokerInterceptorFactory.applyDefaultInterceptors(invoker, config.getProviderFactory(), clazz, method);
99 invoker.setHttpMethod(httpMethods.iterator().next());
100 return invoker;
101 }
102 }
+0
-67
resteasy-legacy/src/main/java/org/jboss/resteasy/client/cache/BrowserCache.java less more
0 package org.jboss.resteasy.client.cache;
1
2 import javax.ws.rs.core.MediaType;
3 import javax.ws.rs.core.MultivaluedMap;
4 import java.io.Serializable;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 *
10 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
11 * caching in the JAX-RS 2.0 compliant resteasy-client module.
12 *
13 * @see resteasy-client
14 * @see org.jboss.resteasy.client.jaxrs.cache.BrowserCache
15 */
16 @Deprecated
17 public interface BrowserCache
18 {
19 public static class Header implements Serializable
20 {
21 private static final long serialVersionUID = 4145981086454860081L;
22
23 private String name;
24 private String value;
25
26 public Header(String name, String value)
27 {
28 this.name = name;
29 this.value = value;
30 }
31
32 public String getName()
33 {
34 return name;
35 }
36
37 public String getValue()
38 {
39 return value;
40 }
41 }
42
43 public static interface Entry
44 {
45 MultivaluedMap<String, String> getHeaders();
46
47 boolean expired();
48
49 Header[] getValidationHeaders();
50
51 byte[] getCached();
52
53 MediaType getMediaType();
54 }
55
56 Entry getAny(String key);
57
58 Entry get(String key, MediaType accept);
59
60 Entry put(String key, MediaType mediaType, MultivaluedMap<String, String> headers, byte[] cached, int expires, String etag, String lastModified);
61
62 Entry remove(String key, MediaType type);
63
64 void clear();
65
66 }
+0
-101
resteasy-legacy/src/main/java/org/jboss/resteasy/client/cache/CacheEntry.java less more
0 package org.jboss.resteasy.client.cache;
1
2 import org.jboss.resteasy.client.cache.BrowserCache.Entry;
3 import org.jboss.resteasy.client.cache.BrowserCache.Header;
4
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.MultivaluedMap;
7 import java.io.Serializable;
8 import java.util.Map;
9 import java.util.concurrent.ConcurrentHashMap;
10
11 /**
12 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
13 * caching in the JAX-RS 2.0 compliant resteasy-client module.
14 *
15 * @see resteasy-client
16 * @see org.jboss.resteasy.client.jaxrs.cache.CacheEntry
17 */
18 @Deprecated
19 public class CacheEntry implements Entry, Serializable
20 {
21 private static final long serialVersionUID = -1922521972113619372L;
22 private final String mediaType;
23 private final byte[] cached;
24 private final int expires;
25 private final long timestamp = System.currentTimeMillis();
26 private final MultivaluedMap<String, String> headers;
27 private Header[] validationHeaders = {};
28 private final String key;
29 private Map extendedProperties = new ConcurrentHashMap();
30
31 public CacheEntry(String key, MultivaluedMap<String, String> headers, byte[] cached, int expires, String etag, String lastModified, MediaType mediaType)
32 {
33 this.key = key;
34 this.cached = cached;
35 this.expires = expires;
36 this.mediaType = mediaType.toString();
37 this.headers = headers;
38
39 if (etag != null || lastModified != null)
40 {
41 if (etag != null && lastModified != null)
42 {
43 validationHeaders = new Header[2];
44 validationHeaders[0] = new Header("If-Modified-Since", lastModified);
45 validationHeaders[1] = new Header("If-None-Match", etag);
46 }
47 else if (etag != null)
48 {
49 validationHeaders = new Header[1];
50 validationHeaders[0] = new Header("If-None-Match", etag);
51 }
52 else if (lastModified != null)
53 {
54 validationHeaders = new Header[1];
55 validationHeaders[0] = new Header("If-Modified-Since", lastModified);
56 }
57
58 }
59 }
60
61 public String getKey()
62 {
63 return key;
64 }
65
66 public MultivaluedMap<String, String> getHeaders()
67 {
68 return headers;
69 }
70
71 public boolean expired()
72 {
73 return System.currentTimeMillis() - timestamp >= expires * 1000L;
74 }
75
76 public Header[] getValidationHeaders()
77 {
78 return validationHeaders;
79 }
80
81 public byte[] getCached()
82 {
83 return cached;
84 }
85
86 public MediaType getMediaType()
87 {
88 return MediaType.valueOf(mediaType);
89 }
90
91 public void addExtendedProperty(Serializable key, Serializable value)
92 {
93 extendedProperties.put(key, value);
94 }
95
96 public Object getExtendedProperty(Serializable key)
97 {
98 return extendedProperties.get(key);
99 }
100 }
+0
-69
resteasy-legacy/src/main/java/org/jboss/resteasy/client/cache/CacheFactory.java less more
0 package org.jboss.resteasy.client.cache;
1
2 import org.jboss.resteasy.client.core.ClientInterceptorRepository;
3 import org.jboss.resteasy.client.core.ClientInvoker;
4 import org.jboss.resteasy.client.core.ClientInvokerModifier;
5 import org.jboss.resteasy.client.core.marshallers.ResteasyClientProxy;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 *
11 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
12 * caching in the JAX-RS 2.0 compliant resteasy-client module.
13 *
14 * @see resteasy-client
15 */
16 @Deprecated
17 public class CacheFactory
18 {
19 /**
20 * Makes the client proxy cacheable. Returns the cache that will hold
21 * returned values from the server.
22 *
23 * @param clientProxy
24 * @return
25 */
26 public static LightweightBrowserCache makeCacheable(Object clientProxy)
27 {
28 LightweightBrowserCache cache = new LightweightBrowserCache();
29 makeCacheable(clientProxy, cache);
30 return cache;
31 }
32
33 /**
34 * Makes the client proxy cacheable. This method allows you to pass in a
35 * shared cache that the proxy should use
36 *
37 * @param clientProxy
38 * @param cache
39 */
40 public static void makeCacheable(Object clientProxy, BrowserCache cache)
41 {
42 final CacheInterceptor interceptor = new CacheInterceptor(cache);
43 ResteasyClientProxy proxy = (ResteasyClientProxy) clientProxy;
44 proxy.applyClientInvokerModifier(new ClientInvokerModifier()
45 {
46 public void modify(ClientInvoker invoker)
47 {
48 if (invoker.getHttpMethod().equalsIgnoreCase("GET"))
49 {
50 invoker.getExecutionInterceptorList().addFirst(interceptor);
51 }
52 }
53 });
54 }
55
56 /**
57 * Make a raw ClientRequest cache results in the provided cache.
58 *
59 * @param request
60 * @param cache
61 */
62 public static void makeCacheable(
63 ClientInterceptorRepository interceptorRepository, BrowserCache cache)
64 {
65 interceptorRepository.getExecutionInterceptorList().addFirst(
66 new CacheInterceptor(cache));
67 }
68 }
+0
-254
resteasy-legacy/src/main/java/org/jboss/resteasy/client/cache/CacheInterceptor.java less more
0 package org.jboss.resteasy.client.cache;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.client.core.BaseClientResponse;
5 import org.jboss.resteasy.client.core.BaseClientResponse.BaseClientResponseStreamFactory;
6 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
7 import org.jboss.resteasy.spi.interception.ClientExecutionContext;
8 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
9 import org.jboss.resteasy.util.DateUtil;
10 import org.jboss.resteasy.util.ReadFromStream;
11 import org.jboss.resteasy.util.WeightedMediaType;
12
13 import javax.ws.rs.GET;
14 import javax.ws.rs.core.CacheControl;
15 import javax.ws.rs.core.HttpHeaders;
16 import javax.ws.rs.core.MediaType;
17 import javax.ws.rs.core.Response;
18 import java.io.ByteArrayInputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.lang.reflect.Method;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.Date;
25 import java.util.List;
26
27 /**
28 *
29 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
30 * @version $Revision: 1 $
31 *
32 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
33 * caching in the JAX-RS 2.0 compliant resteasy-client module.
34 *
35 * @see resteasy-client
36 * @see org.jboss.resteasy.client.jaxrs.cache.CacheInterceptor
37 */
38 @Deprecated
39 @SuppressWarnings("unchecked")
40 public class CacheInterceptor implements ClientExecutionInterceptor, AcceptedByMethod
41 {
42 protected BrowserCache cache;
43
44 static class CachedStreamFactory implements BaseClientResponseStreamFactory
45 {
46 BrowserCache.Entry entry;
47
48 public CachedStreamFactory(BrowserCache.Entry entry)
49 {
50 this.entry = entry;
51 }
52
53 public InputStream getInputStream() throws IOException
54 {
55 return new ByteArrayInputStream(entry.getCached());
56 }
57
58 public void performReleaseConnection()
59 {
60 }
61 }
62
63 public CacheInterceptor(BrowserCache cache)
64 {
65 this.cache = cache;
66 }
67
68 public boolean accept(Class declaring, Method method)
69 {
70 if (declaring == null || method == null) return true;
71 return method.isAnnotationPresent(GET.class);
72 }
73
74 public ClientResponse execute(ClientExecutionContext ctx) throws Exception
75 {
76 ClientRequest request = ctx.getRequest();
77 if (!request.getHttpMethod().equals("GET"))
78 {
79 return ctx.proceed();
80 }
81
82 BrowserCache.Entry entry = getEntry(request);
83 if (entry == null)
84 {
85 return cache(request, ctx.proceed());
86 }
87
88 if (entry.expired())
89 {
90 cache.remove(request.getUri(), entry.getMediaType());
91 BrowserCache.Header[] headers = entry.getValidationHeaders();
92 for (BrowserCache.Header header : headers)
93 {
94 request.header(header.getName(), header.getValue());
95 }
96 return handleExpired(ctx, request, entry);
97 }
98
99 return createClientResponse(request, entry);
100 }
101
102 protected ClientResponse handleExpired(ClientExecutionContext ctx,
103 ClientRequest request, BrowserCache.Entry entry) throws Exception
104 {
105 ClientResponse response = ctx.proceed();
106 if (response.getStatus() == Response.Status.NOT_MODIFIED.getStatusCode())
107 {
108 return updateOnNotModified(request, entry, (BaseClientResponse) response);
109 }
110 return cache(request, response);
111 }
112
113 private ClientResponse cache(ClientRequest request, ClientResponse response)
114 throws Exception
115 {
116 if (response.getStatus() != 200) return response;
117 return cacheIfPossible(request, (BaseClientResponse) response);
118 }
119
120 public ClientResponse updateOnNotModified(ClientRequest request, BrowserCache.Entry old, BaseClientResponse response) throws Exception
121 {
122 old.getHeaders().remove(HttpHeaders.CACHE_CONTROL);
123 old.getHeaders().remove(HttpHeaders.EXPIRES);
124 old.getHeaders().remove(HttpHeaders.LAST_MODIFIED);
125 String cc = (String) response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
126 String exp = (String) response.getResponseHeaders().getFirst(HttpHeaders.EXPIRES);
127 int expires = -1;
128
129 if (cc != null)
130 {
131 CacheControl cacheControl = CacheControl.valueOf(cc);
132 if (cacheControl.isNoCache())
133 {
134 return createClientResponse(request, old);
135 }
136 expires = cacheControl.getMaxAge();
137 }
138 else if (exp != null)
139 {
140 Date date = DateUtil.parseDate(exp);
141 expires = (int) ((date.getTime() - System.currentTimeMillis()) / 1000);
142 }
143
144 if (cc != null)
145 {
146 old.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cc);
147 }
148 if (exp != null)
149 {
150 old.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, exp);
151 }
152
153 String lastModified = (String) response.getResponseHeaders().getFirst(HttpHeaders.LAST_MODIFIED);
154 String etag = (String) response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
155
156 if (etag == null) etag = old.getHeaders().getFirst(HttpHeaders.ETAG);
157 else old.getHeaders().putSingle(HttpHeaders.ETAG, etag);
158
159 if (lastModified != null)
160 {
161 old.getHeaders().putSingle(HttpHeaders.LAST_MODIFIED, lastModified);
162 }
163
164 if (etag == null && lastModified == null && cc == null && exp == null) // don't cache
165 {
166 return createClientResponse(request, old);
167 }
168
169
170 BrowserCache.Entry entry = cache.put(request.getUri(), old.getMediaType(), old.getHeaders(), old.getCached(), expires, etag, lastModified);
171 return createClientResponse(request, entry);
172
173 }
174
175 private BaseClientResponse createClientResponse(ClientRequest request, BrowserCache.Entry entry)
176 {
177 BaseClientResponse response = new BaseClientResponse(new CachedStreamFactory(entry));
178 response.setStatus(200);
179 response.setHeaders(entry.getHeaders());
180 response.setProviderFactory(request.getProviderFactory());
181 return response;
182 }
183
184
185 public ClientResponse cacheIfPossible(ClientRequest request, BaseClientResponse response) throws Exception
186 {
187 String cc = (String) response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
188 String exp = (String) response.getResponseHeaders().getFirst(HttpHeaders.EXPIRES);
189 int expires = -1;
190
191 if (cc != null)
192 {
193 CacheControl cacheControl = CacheControl.valueOf(cc);
194 if (cacheControl.isNoCache()) return response;
195 expires = cacheControl.getMaxAge();
196 }
197 else if (exp != null)
198 {
199 Date date = DateUtil.parseDate(exp);
200 expires = (int) ((date.getTime() - System.currentTimeMillis()) / 1000);
201 }
202
203 String lastModified = (String) response.getResponseHeaders().getFirst(HttpHeaders.LAST_MODIFIED);
204 String etag = (String) response.getResponseHeaders().getFirst(HttpHeaders.ETAG);
205
206 String contentType = (String) response.getResponseHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
207
208 byte[] cached = ReadFromStream.readFromStream(1024, response.getStreamFactory().getInputStream());
209 response.getStreamFactory().performReleaseConnection();
210
211 MediaType mediaType = MediaType.valueOf(contentType);
212 final BrowserCache.Entry entry = cache.put(request.getUri(), mediaType,
213 response.getResponseHeaders(), cached, expires, etag, lastModified);
214
215 response.setStreamFactory(new CachedStreamFactory(entry));
216
217 return response;
218 }
219
220 protected BrowserCache.Entry getEntry(ClientRequest request) throws Exception
221 {
222 String uri = request.getUri();
223
224 BrowserCache.Entry entry = null;
225 String acceptHeader = request.getHeaders().getFirst(HttpHeaders.ACCEPT);
226 if (acceptHeader != null)
227 {
228 List<WeightedMediaType> waccepts = new ArrayList<WeightedMediaType>();
229 String[] split = acceptHeader.split(",");
230 for (String accept : split)
231 {
232 waccepts.add(WeightedMediaType.valueOf(accept));
233 }
234 Collections.sort(waccepts);
235 List<MediaType> accepts = new ArrayList<MediaType>();
236 for (WeightedMediaType accept : waccepts)
237 {
238 accepts.add(new MediaType(accept.getType(), accept.getSubtype(), accept.getParameters()));
239 }
240 for (MediaType accept : accepts)
241 {
242 entry = cache.get(uri, accept);
243 if (entry != null) return entry;
244 }
245 }
246 else
247 {
248 return cache.getAny(uri);
249 }
250
251 return null;
252 }
253 }
+0
-112
resteasy-legacy/src/main/java/org/jboss/resteasy/client/cache/LightweightBrowserCache.java less more
0 package org.jboss.resteasy.client.cache;
1
2
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import java.util.concurrent.atomic.AtomicLong;
6
7 /**
8 * In-memory BrowserCache. Uses an underlying cache, with ConcurrentMapCache as
9 * the default. You specify maximum bytes you want the cache to have. The
10 * default is 2Megabytes. If the cache exceeds this amount, it is wiped clean.
11 * This rather draconian approach to cache reaping is to avoid synchronization
12 * that you would normally have to do in a sophisticated cache.
13 * <p/>
14 * With high concurrent access, because this is not a sophisticated cache,
15 * sometimes a cache entry may be lost. It is consistent though.
16 *
17 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
18 * @version $Revision: 1 $
19 *
20 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
21 * caching in the JAX-RS 2.0 compliant resteasy-client module.
22 *
23 * @see resteasy-client
24 * @see org.jboss.resteasy.client.jaxrs.cache.LightweightBrowserCache
25 */
26 @Deprecated
27 public class LightweightBrowserCache implements BrowserCache
28 {
29
30 protected long maxBytes = 2000000; // 2 meg default
31 protected BrowserCache internalCache = null;
32 protected AtomicLong bytes = new AtomicLong(0);
33
34 public LightweightBrowserCache()
35 {
36 this(new MapCache());
37 }
38
39 public LightweightBrowserCache(BrowserCache cache)
40 {
41 this.internalCache = cache;
42 }
43
44 public BrowserCache getInternalCache()
45 {
46 return internalCache;
47 }
48
49 public void setInternalCache(BrowserCache internalCache)
50 {
51 this.internalCache = internalCache;
52 }
53
54 public long getMaxBytes()
55 {
56 return maxBytes;
57 }
58
59 public void setMaxBytes(long maxBytes)
60 {
61 this.maxBytes = maxBytes;
62 }
63
64 public Entry getAny(String key)
65 {
66 return internalCache.getAny(key);
67 }
68
69 public Entry remove(String key, MediaType type)
70 {
71 Entry entry = internalCache.remove(key, type);
72 if (entry != null) bytes.addAndGet(-1 * entry.getCached().length);
73 return entry;
74 }
75
76 public long getByteCount()
77 {
78 return bytes.get();
79 }
80
81 public Entry get(String key, MediaType accept)
82 {
83 return internalCache.get(key, accept);
84 }
85
86 public Entry put(String key, MediaType mediaType,
87 MultivaluedMap<String, String> headers, byte[] cached, int expires,
88 String etag, String lastModified)
89 {
90 Entry previousValue = internalCache.get(key, mediaType);
91
92 int sizeDiff = -1;
93 if (previousValue == null)
94 sizeDiff = cached.length;
95 else
96 sizeDiff = cached.length - previousValue.getCached().length;
97
98 if (bytes.addAndGet(sizeDiff) > maxBytes)
99 {
100 clear();
101 bytes.addAndGet(sizeDiff);
102 }
103 return internalCache.put(key, mediaType, headers, cached, expires, etag, lastModified);
104 }
105
106 public void clear()
107 {
108 internalCache.clear();
109 bytes.set(0);
110 }
111 }
+0
-99
resteasy-legacy/src/main/java/org/jboss/resteasy/client/cache/MapCache.java less more
0 package org.jboss.resteasy.client.cache;
1
2 import javax.ws.rs.core.MediaType;
3 import javax.ws.rs.core.MultivaluedMap;
4 import java.util.Iterator;
5 import java.util.Map;
6 import java.util.concurrent.ConcurrentHashMap;
7
8 /**
9 * @deprecated Caching in the Resteasy client framework in resteasy-jaxrs is replaced by
10 * caching in the JAX-RS 2.0 compliant resteasy-client module.
11 *
12 * @see resteasy-client
13 * @see org.jboss.resteasy.client.jaxrs.cache.MapCache
14 */
15 @Deprecated
16 public class MapCache implements BrowserCache
17 {
18 protected Map<String, Map<String, Entry>> cache = null;
19
20 public MapCache()
21 {
22 this(new ConcurrentHashMap<String, Map<String, Entry>>());
23 }
24
25 public MapCache(Map<String, Map<String, Entry>> cache)
26 {
27 this.cache = cache;
28 }
29
30 protected Map<String, Map<String, Entry>> createCache()
31 {
32 return new ConcurrentHashMap<String, Map<String, Entry>>();
33 }
34
35 public Entry get(String key, MediaType accept)
36 {
37 Map<String, Entry> parent = cache.get(key);
38 if (parent == null) return null;
39 return parent.get(accept.toString());
40 }
41
42 public Entry getAny(String key)
43 {
44 Map<String, Entry> parent = cache.get(key);
45 if (parent == null) return null;
46 Iterator<Entry> iterator = parent.values().iterator();
47 if (iterator.hasNext()) return iterator.next();
48 return null;
49 }
50
51 public Entry getEntry(String key, MediaType accept)
52 {
53 Map<String, Entry> parent = cache.get(key);
54 if (parent == null) return null;
55 return parent.get(accept.toString());
56 }
57
58 public Entry remove(String key, MediaType type)
59 {
60 Map<String, Entry> data = cache.get(key);
61 if (data == null) return null;
62 Entry removed = data.remove(type.toString());
63 if (data.isEmpty())
64 {
65 cache.remove(key);
66 }
67 else
68 {
69 cache.put(key, data);
70 }
71 return removed;
72 }
73
74 public void clear()
75 {
76 cache.clear();
77 }
78
79 public Entry put(CacheEntry cacheEntry)
80 {
81 Map<String, Entry> map = cache.get(cacheEntry.getKey());
82 if (map == null)
83 {
84 map = new ConcurrentHashMap<String, Entry>();
85 }
86 map.put(cacheEntry.getMediaType().toString(), cacheEntry);
87 cache.put(cacheEntry.getKey(), map);
88 return cacheEntry;
89 }
90
91 public Entry put(String key, MediaType mediaType,
92 MultivaluedMap<String, String> headers, byte[] cached, int expires,
93 String etag, String lastModified)
94 {
95 return put(new CacheEntry(key, headers, cached, expires, etag, lastModified, mediaType));
96 }
97 }
98
+0
-5
resteasy-legacy/src/main/java/org/jboss/resteasy/client/cache/package-info.java less more
0 /**
1 * The client cache facility in Resteasy 2.x is deprecated in favor of the client cache
2 * facility in the resteasy-client module.
3 */
4 package org.jboss.resteasy.client.cache;
+0
-744
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/BaseClientResponse.java less more
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientResponse;
4 import org.jboss.resteasy.client.ClientResponseFailure;
5 import org.jboss.resteasy.client.Link;
6 import org.jboss.resteasy.client.LinkHeader;
7 import org.jboss.resteasy.client.LinkHeaderDelegate;
8 import org.jboss.resteasy.core.ProvidersContextRetainer;
9 import org.jboss.resteasy.core.interception.ClientReaderInterceptorContext;
10 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
11 import org.jboss.resteasy.spi.MarshalledEntity;
12 import org.jboss.resteasy.spi.NotImplementedYetException;
13 import org.jboss.resteasy.spi.ReaderException;
14 import org.jboss.resteasy.spi.ResteasyProviderFactory;
15 import org.jboss.resteasy.util.CaseInsensitiveMap;
16 import org.jboss.resteasy.util.GenericType;
17 import org.jboss.resteasy.util.HttpHeaderNames;
18 import org.jboss.resteasy.util.HttpResponseCodes;
19 import org.jboss.resteasy.util.InputStreamToByteArray;
20 import org.jboss.resteasy.util.ReadFromStream;
21 import org.jboss.resteasy.util.Types;
22
23 import javax.ws.rs.core.EntityTag;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.core.NewCookie;
27 import javax.ws.rs.ext.MessageBodyReader;
28 import javax.ws.rs.ext.Providers;
29 import javax.ws.rs.ext.ReaderInterceptor;
30
31 import java.io.ByteArrayInputStream;
32 import java.io.FilterInputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.lang.annotation.Annotation;
36 import java.lang.reflect.ParameterizedType;
37 import java.lang.reflect.Type;
38 import java.net.URI;
39 import java.util.Date;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.Map;
43 import java.util.Set;
44
45 import static java.lang.String.format;
46
47 /**
48 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
49 * @version $Revision: 1 $
50 */
51 @SuppressWarnings("unchecked")
52 public class BaseClientResponse<T> extends ClientResponse<T>
53 {
54 public static interface BaseClientResponseStreamFactory
55 {
56 InputStream getInputStream() throws IOException;
57
58 void performReleaseConnection();
59 }
60
61 protected ResteasyProviderFactory providerFactory;
62 protected String attributeExceptionsTo;
63 protected MultivaluedMap<String, String> headers;
64 protected String alternateMediaType;
65 protected Class<?> returnType;
66 protected Type genericReturnType;
67 protected Annotation[] annotations = {};
68 protected int status;
69 protected boolean wasReleased = false;
70 protected Object unmarshaledEntity;
71 protected ReaderInterceptor[] readerInterceptors;
72 protected Exception exception;// These can only be set by an interceptor
73 protected BaseClientResponseStreamFactory streamFactory;
74 protected LinkHeader linkHeader;
75 protected Link location;
76 protected ClientExecutor executor;
77 protected Map<String, Object> attributes;
78
79 public BaseClientResponse(BaseClientResponseStreamFactory streamFactory, ClientExecutor executor)
80 {
81 this.streamFactory = streamFactory;
82 this.executor = executor;
83 }
84
85 public BaseClientResponse(BaseClientResponseStreamFactory streamFactory)
86 {
87 this.streamFactory = streamFactory;
88 }
89
90 /**
91 * Store entity within a byte array input stream because we want to release the connection
92 * if a ClientResponseFailure is thrown. Copy status and headers, but ignore
93 * all type information stored in the ClientResponse.
94 *
95 * @param copy
96 * @return
97 */
98 public static ClientResponse copyFromError(ClientResponse copy)
99 {
100 if (copy instanceof BaseClientResponse)
101 {
102 BaseClientResponse base = (BaseClientResponse) copy;
103 InputStream is = null;
104 if (copy.getResponseHeaders().containsKey("Content-Type"))
105 {
106 try
107 {
108 is = base.streamFactory.getInputStream();
109 byte[] bytes = ReadFromStream.readFromStream(1024, is);
110 is = new ByteArrayInputStream(bytes);
111 }
112 catch (IOException e)
113 {
114 // ignored
115 }
116 }
117 final InputStream theIs = is;
118 BaseClientResponse tmp = new BaseClientResponse(new BaseClientResponse.BaseClientResponseStreamFactory()
119 {
120 InputStream stream;
121
122 public InputStream getInputStream() throws IOException
123 {
124 return theIs;
125 }
126
127 public void performReleaseConnection()
128 {
129 }
130 });
131 tmp.executor = base.executor;
132 tmp.status = base.status;
133 tmp.providerFactory = base.providerFactory;
134 tmp.headers = new CaseInsensitiveMap<String>();
135 tmp.headers.putAll(base.headers);
136 tmp.readerInterceptors = base.readerInterceptors;
137 return tmp;
138 }
139 else
140 {
141 // Not sure how this codepath could ever be reached.
142 InputStream is = null;
143 if (copy.getResponseHeaders().containsKey("Content-Type"))
144 {
145 GenericType<byte[]> gt = new GenericType<byte[]>()
146 {
147 };
148 try
149 {
150 byte[] bytes = (byte[]) copy.getEntity(gt);
151 is = new ByteArrayInputStream(bytes);
152 }
153 catch (Exception ignore)
154 {
155 }
156 }
157 final InputStream theIs = is;
158 BaseClientResponse tmp = new BaseClientResponse(new BaseClientResponse.BaseClientResponseStreamFactory()
159 {
160 InputStream stream;
161
162 public InputStream getInputStream() throws IOException
163 {
164 return theIs;
165 }
166
167 public void performReleaseConnection()
168 {
169 }
170 });
171 tmp.status = copy.getStatus();
172 tmp.providerFactory = ResteasyProviderFactory.getInstance();
173 tmp.headers = new CaseInsensitiveMap<String>();
174 tmp.headers.putAll(copy.getResponseHeaders());
175 tmp.headers.remove("Content-Encoding"); // remove encoding because we will have already extracted byte array
176 return tmp;
177 }
178 }
179
180 @Override
181 public Map<String, Object> getAttributes()
182 {
183 return attributes;
184 }
185
186 public void setAttributes(Map<String, Object> attributes)
187 {
188 this.attributes = attributes;
189 }
190
191 public void setReaderInterceptors(ReaderInterceptor[] readerInterceptors)
192 {
193 this.readerInterceptors = readerInterceptors;
194 }
195
196 public void setStatus(int status)
197 {
198 this.status = status;
199 }
200
201 public void setHeaders(MultivaluedMap<String, String> headers)
202 {
203 this.headers = headers;
204 }
205
206 public void setProviderFactory(ResteasyProviderFactory providerFactory)
207 {
208 this.providerFactory = providerFactory;
209 }
210
211 public void setReturnType(Class<T> returnType)
212 {
213 this.returnType = returnType;
214 }
215
216 public Class<?> getReturnType()
217 {
218 return returnType;
219 }
220
221 public void setGenericReturnType(Type genericReturnType)
222 {
223 this.genericReturnType = genericReturnType;
224 }
225
226 public void setAnnotations(Annotation[] annotations)
227 {
228 this.annotations = annotations;
229 }
230
231 public String getAttributeExceptionsTo()
232 {
233 return attributeExceptionsTo;
234 }
235
236 public void setAttributeExceptionsTo(String attributeExceptionsTo)
237 {
238 this.attributeExceptionsTo = attributeExceptionsTo;
239 }
240
241 public Exception getException()
242 {
243 return exception;
244 }
245
246 public void setException(Exception exception)
247 {
248 this.exception = exception;
249 }
250
251 public Annotation[] getAnnotations()
252 {
253 return this.annotations;
254 }
255
256 public String getResponseHeader(String headerKey)
257 {
258 if (headers == null) return null;
259 return headers.getFirst(headerKey);
260 }
261
262 public LinkHeader getLinkHeader()
263 {
264 if (linkHeader != null) return linkHeader;
265 linkHeader = new LinkHeader();
266 if (!headers.containsKey("Link"))
267 {
268 return linkHeader;
269 }
270 List<String> links = headers.get("Link");
271 LinkHeaderDelegate delegate = new LinkHeaderDelegate();
272 for (String link : links)
273 {
274 LinkHeader tmp = delegate.fromString(link);
275 linkHeader.getLinks().addAll(tmp.getLinks());
276 linkHeader.getLinksByRelationship().putAll(tmp.getLinksByRelationship());
277 linkHeader.getLinksByTitle().putAll(tmp.getLinksByTitle());
278
279 }
280 for (Link link : linkHeader.getLinks())
281 {
282 link.setExecutor(executor);
283 }
284 return linkHeader;
285 }
286
287 public Link getLocationLink()
288 {
289 if (location != null) return location;
290 if (!headers.containsKey("Location")) return null;
291 String header = headers.getFirst("Location");
292
293 location = new Link();
294 location.setHref(header);
295 location.setExecutor(executor);
296
297 return location;
298 }
299
300 @Override
301 public Link getHeaderAsLink(String headerName)
302 {
303 String value = headers.getFirst(headerName);
304 if (value == null) return null;
305 String type = headers.getFirst(headerName + "-type");
306 Link link = new Link();
307 link.setHref(value);
308 link.setType(type);
309 link.setExecutor(executor);
310 return link;
311 }
312
313 public void setAlternateMediaType(String alternateMediaType)
314 {
315 this.alternateMediaType = alternateMediaType;
316 }
317
318 public BaseClientResponseStreamFactory getStreamFactory()
319 {
320 return streamFactory;
321 }
322
323 public void setStreamFactory(BaseClientResponseStreamFactory streamFactory)
324 {
325 this.streamFactory = streamFactory;
326 }
327
328 @Override
329 public void resetStream()
330 {
331 try
332 {
333 if (this.streamFactory.getInputStream().markSupported())
334 {
335 this.streamFactory.getInputStream().reset();
336 }
337 }
338 catch (IOException e)
339 {
340 throw new RuntimeException(e);
341 }
342 }
343
344 @Override
345 public T getEntity()
346 {
347 if (returnType == null)
348 {
349 throw new RuntimeException(Messages.MESSAGES.noTypeInformationForEntity());
350 }
351 return (T) getEntity(returnType, genericReturnType, this.annotations);
352 }
353
354 @Override
355 public <T2> T2 getEntity(Class<T2> type)
356 {
357 return getEntity(type, null);
358 }
359
360 @Override
361 public <T2> T2 getEntity(Class<T2> type, Type genericType)
362 {
363 return getEntity(type, genericType, getAnnotations(type, genericType));
364 }
365
366 private <T2> Annotation[] getAnnotations(Class<T2> type, Type genericType)
367 {
368 if (this.annotations != null)
369 {
370 return this.annotations;
371 }
372 return (this.returnType == type && this.genericReturnType == genericType) ? this.annotations
373 : null;
374 }
375
376 @Override
377 public <T2> T2 getEntity(Class<T2> type, Type genericType, Annotation[] anns)
378 {
379 if (exception != null)
380 {
381 throw new RuntimeException(Messages.MESSAGES.unableToUnmarshalResponse(attributeExceptionsTo), exception);
382 }
383
384 if (unmarshaledEntity != null && !type.isInstance(this.unmarshaledEntity))
385 throw new RuntimeException(Messages.MESSAGES.entityAlreadyRead(unmarshaledEntity.getClass()));
386
387 if (unmarshaledEntity == null)
388 {
389 if (status == HttpResponseCodes.SC_NO_CONTENT)
390 return null;
391
392 unmarshaledEntity = readFrom(type, genericType, getMediaType(), anns);
393 // only release connection if we actually unmarshalled something and if the object is *NOT* an InputStream
394 // If it is an input stream, the user may be doing their own stream processing.
395 if (unmarshaledEntity != null && !InputStream.class.isInstance(unmarshaledEntity)) releaseConnection();
396 }
397 return (T2) unmarshaledEntity;
398 }
399
400 public MediaType getMediaType()
401 {
402 String mediaType = getResponseHeader(HttpHeaderNames.CONTENT_TYPE);
403 if (mediaType == null)
404 {
405 mediaType = alternateMediaType;
406 }
407
408 return mediaType == null ? MediaType.WILDCARD_TYPE : MediaType.valueOf(mediaType);
409 }
410
411 // this is synchronized in conjunction with finalize to protect against premature finalize called by the GC
412 protected synchronized <T2> Object readFrom(Class<T2> type, Type genericType,
413 MediaType media, Annotation[] annotations)
414 {
415 Type useGeneric = genericType == null ? type : genericType;
416 Class<?> useType = type;
417 boolean isMarshalledEntity = false;
418 if (type.equals(MarshalledEntity.class))
419 {
420 isMarshalledEntity = true;
421 ParameterizedType param = (ParameterizedType) useGeneric;
422 useGeneric = param.getActualTypeArguments()[0];
423 useType = Types.getRawType(useGeneric);
424 }
425
426 Providers current = ResteasyProviderFactory.getContextData(Providers.class);
427 ResteasyProviderFactory.pushContext(Providers.class, providerFactory);
428 Object obj = null;
429 try
430 {
431 InputStream is = streamFactory.getInputStream();
432 if (is == null)
433 {
434 throw new ClientResponseFailure(Messages.MESSAGES.inputStreamEmpty(), this);
435 }
436 if (isMarshalledEntity)
437 {
438 is = new InputStreamToByteArray(is);
439
440 }
441
442 final Object finalObj = new ClientReaderInterceptorContext(readerInterceptors, providerFactory, useType,
443 useGeneric, annotations, media, getResponseHeaders(), new InputStreamWrapper(is), attributes)
444 .proceed();
445 obj = finalObj;
446 if (isMarshalledEntity)
447 {
448 InputStreamToByteArray isba = (InputStreamToByteArray) is;
449 final byte[] bytes = isba.toByteArray();
450 return new MarshalledEntity()
451 {
452 @Override
453 public byte[] getMarshalledBytes()
454 {
455 return bytes;
456 }
457
458 @Override
459 public Object getEntity()
460 {
461 return finalObj;
462 }
463 };
464 }
465 else
466 {
467 return (T2) finalObj;
468 }
469
470 }
471 catch (Exception e)
472 {
473 if (e instanceof ReaderException)
474 {
475 throw (ReaderException) e;
476 }
477 else
478 {
479 throw new ReaderException(e);
480 }
481 }
482 finally
483 {
484 ResteasyProviderFactory.popContextData(Providers.class);
485 if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
486 if (obj instanceof ProvidersContextRetainer)
487 {
488 ((ProvidersContextRetainer) obj).setProviders(providerFactory);
489 }
490 }
491 }
492
493 private static class InputStreamWrapper extends FilterInputStream {
494 protected InputStreamWrapper(InputStream in) {
495 super(in);
496 }
497
498 @Override
499 public void close() throws IOException {
500 }
501 }
502
503 @Override
504 public <T2> T2 getEntity(GenericType<T2> genericType)
505 {
506 return getEntity(genericType.getType(), genericType.getGenericType());
507 }
508
509 @Override
510 public <T2> T2 getEntity(GenericType<T2> genericType, Annotation[] ann)
511 {
512 return getEntity(genericType.getType(), genericType.getGenericType(), ann);
513 }
514
515 public MultivaluedMap<String, String> getResponseHeaders()
516 {
517 return headers;
518 }
519
520 @Override
521 public MultivaluedMap<String, Object> getMetadata()
522 {
523 // hack to cast from <String, String> to <String, Object>
524 return (MultivaluedMap) headers;
525 }
526
527 @Override
528 public int getStatus()
529 {
530 return status;
531 }
532
533 @Override
534 public StatusType getStatusInfo()
535 {
536 StatusType statusType = Status.fromStatusCode(status);
537 if (statusType == null)
538 {
539 statusType = new StatusType()
540 {
541 @Override
542 public int getStatusCode()
543 {
544 return status;
545 }
546
547 @Override
548 public Status.Family getFamily()
549 {
550 return Status.Family.OTHER;
551 }
552
553 @Override
554 public String getReasonPhrase()
555 {
556 return "Unknown Code";
557 }
558 };
559 }
560 return statusType;
561 }
562
563 public void checkFailureStatus()
564 {
565 if (status > 399 && status < 599)
566 {
567 // throw createResponseFailure(format("Error status %d %s returned", status, getResponseStatus()));
568 throw createResponseFailure(Messages.MESSAGES.clientResponseFailureStatus(status, getResponseStatus()));
569 }
570 }
571
572 public ClientResponseFailure createResponseFailure(String message)
573 {
574 return createResponseFailure(message, null);
575 }
576
577 public ClientResponseFailure createResponseFailure(String message, Exception e)
578 {
579 setException(e);
580 this.returnType = byte[].class;
581 this.genericReturnType = null;
582 this.annotations = null;
583 return new ClientResponseFailure(message, e, (ClientResponse<byte[]>) this);
584 }
585
586 @Override
587 public Status getResponseStatus()
588 {
589 return Status.fromStatusCode(getStatus());
590 }
591
592 public boolean wasReleased()
593 {
594 return wasReleased;
595 }
596
597 public void setWasReleased(boolean wasReleased)
598 {
599 this.wasReleased = wasReleased;
600 }
601
602 public final void releaseConnection()
603 {
604 if (!wasReleased)
605 {
606 if (streamFactory != null) streamFactory.performReleaseConnection();
607 wasReleased = true;
608 }
609 }
610
611 @Override
612 // this is synchronized to protect against premature finalize called by the GC
613 protected synchronized final void finalize() throws Throwable
614 {
615 releaseConnection();
616 }
617
618 @Override
619 public <T> T readEntity(Class<T> entityType)
620 {
621 throw new NotImplementedYetException();
622 }
623
624 @Override
625 public <T> T readEntity(javax.ws.rs.core.GenericType<T> entityType)
626 {
627 throw new NotImplementedYetException();
628 }
629
630 @Override
631 public <T> T readEntity(Class<T> entityType, Annotation[] annotations)
632 {
633 throw new NotImplementedYetException();
634 }
635
636 @Override
637 public <T> T readEntity(javax.ws.rs.core.GenericType<T> entityType, Annotation[] annotations)
638 {
639 throw new NotImplementedYetException();
640 }
641
642 @Override
643 public boolean hasEntity()
644 {
645 throw new NotImplementedYetException();
646 }
647
648 @Override
649 public boolean bufferEntity()
650 {
651 throw new NotImplementedYetException();
652 }
653
654 @Override
655 public void close()
656 {
657 releaseConnection();
658 }
659
660 @Override
661 public String getHeaderString(String name)
662 {
663 throw new NotImplementedYetException();
664 }
665
666 @Override
667 public Locale getLanguage()
668 {
669 throw new NotImplementedYetException();
670 }
671
672 @Override
673 public int getLength()
674 {
675 throw new NotImplementedYetException();
676 }
677
678 @Override
679 public Map<String, NewCookie> getCookies()
680 {
681 throw new NotImplementedYetException();
682 }
683
684 @Override
685 public EntityTag getEntityTag()
686 {
687 throw new NotImplementedYetException();
688 }
689
690 @Override
691 public Date getDate()
692 {
693 throw new NotImplementedYetException();
694 }
695
696 @Override
697 public Date getLastModified()
698 {
699 throw new NotImplementedYetException();
700 }
701
702 @Override
703 public Set<javax.ws.rs.core.Link> getLinks()
704 {
705 throw new NotImplementedYetException();
706 }
707
708 @Override
709 public boolean hasLink(String relation)
710 {
711 throw new NotImplementedYetException();
712 }
713
714 @Override
715 public javax.ws.rs.core.Link getLink(String relation)
716 {
717 throw new NotImplementedYetException();
718 }
719
720 @Override
721 public javax.ws.rs.core.Link.Builder getLinkBuilder(String relation)
722 {
723 throw new NotImplementedYetException();
724 }
725
726 @Override
727 public URI getLocation()
728 {
729 throw new NotImplementedYetException();
730 }
731
732 @Override
733 public Set<String> getAllowedMethods()
734 {
735 throw new NotImplementedYetException();
736 }
737
738 @Override
739 public MultivaluedMap<String, String> getStringHeaders()
740 {
741 throw new NotImplementedYetException();
742 }
743 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/ClientErrorInterceptor.java less more
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ClientResponse;
3
4 import javax.ws.rs.core.Response;
5
6 /**
7 * {@link ClientErrorInterceptor} provides a hook into the proxy
8 * {@link ClientResponse} request lifecycle. If a Client Proxy method is called,
9 * resulting in a client exception, and the proxy return type is not
10 * {@link Response} or {@link ClientResponse}, registered interceptors will be
11 * given a chance to process the response manually, or throw a new exception. If
12 * all interceptors successfully return, RestEasy will re-throw the original
13 * encountered exception.
14 *
15 * @author <a href="mailto:lincoln@ocpsoft.com">Lincoln Baxter, III</a>
16 */
17 public interface ClientErrorInterceptor
18 {
19 /**
20 * Attempt to handle the current {@link ClientResponse}. If this method
21 * returns successfully, the next registered
22 * {@link ClientErrorInterceptor} will attempt to handle the
23 * {@link ClientResponse}. If this method throws an exception, no further
24 * interceptors will be processed.
25 *
26 * @throws RuntimeException RestEasy will abort request processing if any exception is
27 * thrown from this method.
28 */
29 void handle(ClientResponse<?> response) throws RuntimeException;
30 }
+0
-23
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/ClientInterceptorRepository.java less more
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
3
4 import javax.ws.rs.ext.ReaderInterceptor;
5 import javax.ws.rs.ext.WriterInterceptor;
6 import java.util.LinkedList;
7
8 /**
9 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
10 * @version $Revision: 1 $
11 */
12 public interface ClientInterceptorRepository
13 {
14
15 LinkedList<ReaderInterceptor> getReaderInterceptorList();
16
17 LinkedList<WriterInterceptor> getWriterInterceptorList();
18
19 LinkedList<ClientExecutionInterceptor> getExecutionInterceptorList();
20
21 void registerInterceptor(Object interceptor);
22 }
+0
-201
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/ClientInterceptorRepositoryImpl.java less more
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.core.interception.ReaderInterceptorRegistry;
3 import org.jboss.resteasy.core.interception.WriterInterceptorRegistry;
4 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
5 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
6 import org.jboss.resteasy.spi.interception.MessageBodyReaderInterceptor;
7 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
8
9 import javax.ws.rs.ext.ReaderInterceptor;
10 import javax.ws.rs.ext.WriterInterceptor;
11
12 import java.lang.reflect.Array;
13 import java.util.Arrays;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.LinkedList;
17 import java.util.Map;
18 import java.util.Map.Entry;
19
20 @SuppressWarnings("unchecked")
21 public class ClientInterceptorRepositoryImpl implements ClientInterceptorRepository
22 {
23
24 private static enum InterceptorType
25 {
26 MessageBodyReader(ReaderInterceptor.class),
27 MessageBodyWriter(
28 WriterInterceptor.class),
29 ClientExecution(
30 ClientExecutionInterceptor.class);
31
32 Class<?> clazz;
33
34 public static InterceptorType getInterceptorTypeFor(Class<?> type)
35 {
36 for (InterceptorType interceptorType : InterceptorType.values())
37 {
38 if (type == interceptorType.clazz)
39 {
40 return interceptorType;
41 }
42 }
43 return null;
44 }
45
46 InterceptorType(Class<?> clazz)
47 {
48 this.clazz = clazz;
49 }
50 }
51
52 private Map<InterceptorType, LinkedList<?>> interceptorLists = new HashMap<InterceptorType, LinkedList<?>>();
53
54 protected ReaderInterceptor[] getReaderInterceptors()
55 {
56 return getArray(ReaderInterceptor.class);
57 }
58
59 protected WriterInterceptor[] getWriterInterceptors()
60 {
61 return getArray(WriterInterceptor.class);
62 }
63
64 protected ClientExecutionInterceptor[] getExecutionInterceptors()
65 {
66 return getArray(ClientExecutionInterceptor.class);
67 }
68
69 private <T> T[] getArray(Class<T> type)
70 {
71 LinkedList<T> interceptors = getInterceptors(type);
72 return (T[]) interceptors.toArray((T[]) Array.newInstance(type,
73 interceptors.size()));
74 }
75
76 protected void setReaderInterceptors(
77 ReaderInterceptor[] readerInterceptors)
78 {
79 setData(InterceptorType.MessageBodyReader, readerInterceptors);
80 }
81
82 protected void setWriterInterceptors(
83 WriterInterceptor[] writerInterceptors)
84 {
85 setData(InterceptorType.MessageBodyWriter, writerInterceptors);
86 }
87
88 protected void setExecutionInterceptors(
89 ClientExecutionInterceptor[] executionInterceptors)
90 {
91 setData(InterceptorType.ClientExecution, executionInterceptors);
92 }
93
94 protected void setExecutionInterceptors(
95 Collection<ClientExecutionInterceptor> executionInterceptorList)
96 {
97 setData(InterceptorType.ClientExecution, executionInterceptorList);
98 }
99
100 public LinkedList<ReaderInterceptor> getReaderInterceptorList()
101 {
102 return getInterceptors(InterceptorType.MessageBodyReader);
103 }
104
105 public LinkedList<WriterInterceptor> getWriterInterceptorList()
106 {
107 return getInterceptors(InterceptorType.MessageBodyWriter);
108 }
109
110 public LinkedList<ClientExecutionInterceptor> getExecutionInterceptorList()
111 {
112 return getInterceptors(InterceptorType.ClientExecution);
113 }
114
115 protected <T> LinkedList<T> getInterceptors(Class<T> clazz)
116 {
117 InterceptorType interceptorType = InterceptorType
118 .getInterceptorTypeFor(clazz);
119 if (interceptorType == null)
120 return null;
121 return getInterceptors(interceptorType);
122 }
123
124 protected synchronized LinkedList getInterceptors(
125 InterceptorType interceptorType)
126 {
127 LinkedList interceptors = interceptorLists.get(interceptorType);
128 if (interceptors == null)
129 {
130 interceptorLists.put(interceptorType, interceptors = new LinkedList());
131 }
132 return interceptors;
133 }
134
135 private void setData(InterceptorType type, Object[] arr)
136 {
137 setData(type, Arrays.asList(arr));
138 }
139
140 private void setData(InterceptorType type, Collection newList)
141 {
142 LinkedList list = getInterceptors(type);
143 list.clear();
144 list.addAll(newList);
145 }
146
147 public void copyClientInterceptorsTo(ClientInterceptorRepositoryImpl copyTo)
148 {
149 for (Entry<InterceptorType, LinkedList<?>> entry : interceptorLists
150 .entrySet())
151 {
152 LinkedList copyToInterceptors = copyTo.getInterceptors(entry.getKey());
153 LinkedList copyFromInterceptors = this.getInterceptors(entry.getKey());
154 copyToInterceptors.addAll(copyFromInterceptors);
155 }
156 }
157
158 public void prefixClientInterceptorsTo(ClientInterceptorRepositoryImpl copyTo)
159 {
160 for (Entry<InterceptorType, LinkedList<?>> entry : interceptorLists
161 .entrySet())
162 {
163 LinkedList copyToInterceptors = copyTo.getInterceptors(entry.getKey());
164 LinkedList copyFromInterceptors = this.getInterceptors(entry.getKey());
165 for (Object interceptor : copyFromInterceptors)
166 {
167 copyToInterceptors.addFirst(interceptor);
168 }
169 }
170 }
171
172 public void registerInterceptor(Object interceptor)
173 {
174 boolean registered = false;
175 if (interceptor instanceof ClientExecutionInterceptor)
176 {
177 getExecutionInterceptorList().add(
178 (ClientExecutionInterceptor) interceptor);
179 registered = true;
180 }
181 if (interceptor instanceof MessageBodyReaderInterceptor)
182 {
183 getReaderInterceptorList().add(
184 new ReaderInterceptorRegistry.ReaderInterceptorFacade((MessageBodyReaderInterceptor)interceptor));
185 registered = true;
186 }
187 if (interceptor instanceof MessageBodyWriterInterceptor)
188 {
189 getWriterInterceptorList().add(
190 new WriterInterceptorRegistry.WriterInterceptorFacade((MessageBodyWriterInterceptor) interceptor));
191 registered = true;
192 }
193
194 if (!registered)
195 {
196 throw new RuntimeException(Messages.MESSAGES.entityNotOfUnderstoodType());
197 }
198 }
199
200 }
+0
-178
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/ClientInvoker.java less more
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.ProxyConfig;
6 import org.jboss.resteasy.client.core.extractors.ClientErrorHandler;
7 import org.jboss.resteasy.client.core.extractors.ClientRequestContext;
8 import org.jboss.resteasy.client.core.extractors.EntityExtractor;
9 import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory;
10 import org.jboss.resteasy.client.core.marshallers.ClientMarshallerFactory;
11 import org.jboss.resteasy.client.core.marshallers.Marshaller;
12 import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper;
13 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
14 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
15 import org.jboss.resteasy.spi.ResteasyProviderFactory;
16 import org.jboss.resteasy.util.MediaTypeHelper;
17
18 import javax.ws.rs.Path;
19 import javax.ws.rs.core.HttpHeaders;
20 import javax.ws.rs.core.MediaType;
21 import javax.ws.rs.ext.Providers;
22
23 import java.lang.reflect.Method;
24 import java.net.URI;
25 import java.util.HashMap;
26 import java.util.Map;
27
28 /**
29 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
30 * @version $Revision: 1 $
31 */
32 @SuppressWarnings("unchecked")
33 public class ClientInvoker extends ClientInterceptorRepositoryImpl implements MethodInvoker
34 {
35 protected org.jboss.resteasy.spi.old.ResteasyProviderFactory providerFactory;
36 protected String httpMethod;
37 protected ResteasyUriBuilder uri;
38 protected Method method;
39 protected Class declaring;
40 protected MediaType accepts;
41 protected Marshaller[] marshallers;
42 protected ClientExecutor executor;
43 protected boolean followRedirects;
44 protected EntityExtractor extractor;
45 protected EntityExtractorFactory extractorFactory;
46 protected URI baseUri;
47 protected Map<String, Object> attributes = new HashMap<String, Object>();
48
49
50 public ClientInvoker(URI baseUri, Class declaring, Method method, ResteasyProviderFactory providerFactory, ClientExecutor executor, EntityExtractorFactory extractorFactory)
51 {
52 this(baseUri, declaring, method, new ProxyConfig(null, executor, providerFactory, extractorFactory, null, null, null));
53 }
54
55 public ClientInvoker(URI baseUri, Class declaring, Method method, ProxyConfig config)
56 {
57 this.declaring = declaring;
58 this.method = method;
59 this.marshallers = ClientMarshallerFactory.createMarshallers(declaring, method, providerFactory, config.getServerConsumes());
60 this.providerFactory = (org.jboss.resteasy.spi.old.ResteasyProviderFactory)config.getProviderFactory();
61 this.executor = config.getExecutor();
62 final MediaType[] acpts = MediaTypeHelper.getProduces(declaring, method, config.getServerProduces());
63 accepts = acpts != null ? acpts[0] : null;
64 this.uri = new ResteasyUriBuilder();
65 this.baseUri = baseUri;
66 uri.uri(baseUri);
67 if (declaring.isAnnotationPresent(Path.class)) uri.path(declaring);
68 if (method.isAnnotationPresent(Path.class)) uri.path(method);
69 this.extractorFactory = config.getExtractorFactory();
70 this.extractor = extractorFactory.createExtractor(method);
71 }
72
73 public Map<String, Object> getAttributes()
74 {
75 return attributes;
76 }
77
78 public MediaType getAccepts()
79 {
80 return accepts;
81 }
82
83 public Method getMethod()
84 {
85 return method;
86 }
87
88 public Class getDeclaring()
89 {
90 return declaring;
91 }
92
93 public ResteasyProviderFactory getProviderFactory()
94 {
95 return providerFactory;
96 }
97
98 public Object invoke(Object[] args)
99 {
100 boolean isProvidersSet = ResteasyProviderFactory.getContextData(Providers.class) != null;
101 if (!isProvidersSet) ResteasyProviderFactory.pushContext(Providers.class, providerFactory);
102
103 try
104 {
105 if (uri == null) throw new RuntimeException(Messages.MESSAGES.baseURINotSetForClientProxy());
106
107
108 ClientRequest request = createRequest(args);
109
110 BaseClientResponse clientResponse = null;
111 try
112 {
113 clientResponse = (BaseClientResponse) request.httpMethod(httpMethod);
114 }
115 catch (Exception e)
116 {
117 ClientExceptionMapper<Exception> mapper = providerFactory.getClientExceptionMapper(Exception.class);
118 if (mapper != null)
119 {
120 throw mapper.toException(e);
121 }
122 throw new RuntimeException(e);
123 }
124 ClientErrorHandler errorHandler = new ClientErrorHandler(providerFactory.getClientErrorInterceptors());
125 clientResponse.setAttributeExceptionsTo(method.toString());
126 clientResponse.setAnnotations(method.getAnnotations());
127 ClientRequestContext clientRequestContext = new ClientRequestContext(request, clientResponse, errorHandler, extractorFactory, baseUri);
128 return extractor.extractEntity(clientRequestContext);
129 }
130 finally
131 {
132 if (!isProvidersSet) ResteasyProviderFactory.popContextData(Providers.class);
133 }
134 }
135
136 protected ClientRequest createRequest(Object[] args)
137 {
138 ClientRequest request = new ClientRequest(uri, executor, providerFactory);
139 request.getAttributes().putAll(attributes);
140 if (accepts != null) request.header(HttpHeaders.ACCEPT, accepts.toString());
141 this.copyClientInterceptorsTo(request);
142
143 boolean isClientResponseResult = ClientResponse.class.isAssignableFrom(method.getReturnType());
144 request.followRedirects(!isClientResponseResult || this.followRedirects);
145
146 for (int i = 0; i < marshallers.length; i++)
147 {
148 marshallers[i].build(request, args[i]);
149 }
150 return request;
151 }
152
153 public String getHttpMethod()
154 {
155 return httpMethod;
156 }
157
158 public void setHttpMethod(String httpMethod)
159 {
160 this.httpMethod = httpMethod;
161 }
162
163 public boolean isFollowRedirects()
164 {
165 return followRedirects;
166 }
167
168 public void setFollowRedirects(boolean followRedirects)
169 {
170 this.followRedirects = followRedirects;
171 }
172
173 public void followRedirects()
174 {
175 setFollowRedirects(true);
176 }
177 }
+0
-34
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/ClientInvokerInterceptorFactory.java less more
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3
4 import java.lang.reflect.Method;
5
6 @SuppressWarnings("unchecked")
7 public class ClientInvokerInterceptorFactory
8 {
9 public static void applyDefaultInterceptors(
10 ClientInterceptorRepositoryImpl repository,
11 ResteasyProviderFactory providerFactory)
12 {
13 applyDefaultInterceptors(repository, providerFactory, null, null);
14 }
15
16 public static void applyDefaultInterceptors(
17 ClientInterceptorRepositoryImpl repository,
18 ResteasyProviderFactory providerFactory, Class declaring, Method method)
19 {
20 repository.setReaderInterceptors(providerFactory
21 .getClientReaderInterceptorRegistry().postMatch(declaring,
22 method));
23 repository.setWriterInterceptors(providerFactory
24 .getClientWriterInterceptorRegistry().postMatch(declaring,
25 method));
26 if (providerFactory instanceof org.jboss.resteasy.spi.old.ResteasyProviderFactory)
27 {
28 repository.setExecutionInterceptors(((org.jboss.resteasy.spi.old.ResteasyProviderFactory) providerFactory)
29 .getClientExecutionInterceptorRegistry().bind(declaring, method));
30 }
31 }
32
33 }
+0
-13
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/ClientInvokerModifier.java less more
0 package org.jboss.resteasy.client.core;
1
2 /**
3 * used to modify all of the ClientInvokers of a given ResteasyClientProxy. @see
4 * ResteasyClientProxy.applyClientInvokerModifier
5 *
6 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
7 * @version $Revision: 1 $
8 */
9 public interface ClientInvokerModifier
10 {
11 void modify(ClientInvoker invoker);
12 }
+0
-115
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/ClientProxy.java less more
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ProxyBuilder;
3 import org.jboss.resteasy.client.ProxyConfig;
4 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
5
6 import java.lang.reflect.InvocationHandler;
7 import java.lang.reflect.Method;
8 import java.net.URI;
9 import java.util.Map;
10
11 /**
12 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
13 * @version $Revision: 1 $
14 */
15 public class ClientProxy implements InvocationHandler
16 {
17 private Map<Method, MethodInvoker> methodMap;
18 private Class<?> clazz;
19 private final URI base;
20 private final ProxyConfig config;
21
22 public ClientProxy(Map<Method, MethodInvoker> methodMap, URI base, ProxyConfig config)
23 {
24 super();
25 this.methodMap = methodMap;
26 this.base = base;
27 this.config = config;
28 }
29
30 public Class<?> getClazz()
31 {
32 return clazz;
33 }
34
35 public void setClazz(Class<?> clazz)
36 {
37 this.clazz = clazz;
38 }
39
40 public Object invoke(Object o, Method method, Object[] args)
41 throws Throwable
42 {
43 // equals and hashCode were added for cases where the proxy is added to
44 // collections. The Spring transaction management, for example, adds
45 // transactional Resources to a Collection, and it calls equals and
46 // hashCode.
47
48 MethodInvoker clientInvoker = methodMap.get(method);
49 if (clientInvoker == null)
50 {
51 if (method.getName().equals("equals"))
52 {
53 return this.equals(o);
54 }
55 else if (method.getName().equals("hashCode"))
56 {
57 return this.hashCode();
58 }
59 else if (method.getName().equals("toString") && (args == null || args.length == 0))
60 {
61 return this.toString();
62 }
63 else if (method.getName().equals("getResteasyClientInvokers"))
64 {
65 return methodMap.values();
66 }
67 else if (method.getName().equals("applyClientInvokerModifier"))
68 {
69 ClientInvokerModifier modifier = (ClientInvokerModifier) args[0];
70 for (MethodInvoker invoker : methodMap.values())
71 {
72 if(invoker instanceof ClientInvoker)
73 modifier.modify((ClientInvoker)invoker);
74 }
75
76 return null;
77 }
78 else if(method.getName().equals("as") && args.length == 1 && args[0] instanceof Class)
79 {
80 return ProxyBuilder.createProxy((Class<?>)args[0], base, config);
81 }
82 }
83
84 if (clientInvoker == null)
85 {
86 throw new RuntimeException(Messages.MESSAGES.couldNotFindMethod(method));
87 }
88 return clientInvoker.invoke(args);
89 }
90
91 @Override
92 public boolean equals(Object obj)
93 {
94 if (obj == null || !(obj instanceof ClientProxy))
95 return false;
96 ClientProxy other = (ClientProxy) obj;
97 if (other == this)
98 return true;
99 if (other.clazz != this.clazz)
100 return false;
101 return super.equals(obj);
102 }
103
104 @Override
105 public int hashCode()
106 {
107 return clazz.hashCode();
108 }
109
110 public String toString()
111 {
112 return "Client Proxy for :" + clazz.getName();
113 }
114 }
+0
-6
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/MethodInvoker.java less more
0 package org.jboss.resteasy.client.core;
1
2 public interface MethodInvoker
3 {
4 Object invoke(Object[] args);
5 }
+0
-114
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/SelfExpandingBufferredInputStream.java less more
0 package org.jboss.resteasy.client.core;
1
2 import java.io.BufferedInputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
7
8 /**
9 * Extension of {@link BufferedInputStream} enforcing the contract where reset()
10 * always returns to the beginning of the stream, and the internal buffer
11 * expands automatically to the total length of content read from the underlying
12 * stream.
13 *
14 * @author ul8b
15 */
16 public class SelfExpandingBufferredInputStream extends BufferedInputStream
17 {
18 private static int defaultBufferSize = 8192;
19
20 public SelfExpandingBufferredInputStream(InputStream in)
21 {
22 super(in);
23 super.mark(defaultBufferSize);
24 }
25
26 public SelfExpandingBufferredInputStream(InputStream in, int size)
27 {
28 super(in, size);
29 super.mark(size);
30 }
31
32 /**
33 * Not supported. Mark position is always zero.
34 */
35 @Override
36 public synchronized void mark(int readlimit)
37 {
38 throw new UnsupportedOperationException(Messages.MESSAGES.alwaysMarkedAtIndex0());
39 }
40
41 @Override
42 public synchronized int read() throws IOException
43 {
44 if (pos == marklimit)
45 {
46 expand();
47 }
48 return super.read();
49 }
50
51 @Override
52 public synchronized int read(byte[] b, int off, int len) throws IOException
53 {
54 while (pos + len > marklimit)
55 {
56 expand();
57 }
58 return super.read(b, off, len);
59 }
60
61 @Override
62 public int read(byte[] b) throws IOException
63 {
64 while (pos + b.length > marklimit)
65 {
66 expand();
67 }
68 return super.read(b);
69 }
70
71 /**
72 * Double the current buffer size limit. Reset to zero, then double the
73 * buffer size and restore last position in the buffer.
74 *
75 * @throws IOException
76 */
77 private void expand() throws IOException
78 {
79 int lastPos = pos;
80 super.reset();
81 super.mark(marklimit * 2);
82 pos = lastPos;
83 }
84
85 /**
86 * Return the current maximum size of the internal buffer. This is
87 * independent of how much data is actually contained within the buffer.
88 */
89 public int getBufSize()
90 {
91 return buf.length;
92 }
93
94 public int getCount()
95 {
96 return count;
97 }
98
99 public int getPos()
100 {
101 return pos;
102 }
103
104 public int getMarkLimit()
105 {
106 return marklimit;
107 }
108
109 public int getMarkPos()
110 {
111 return markpos;
112 }
113 }
+0
-55
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/SubResourceInvoker.java less more
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.ProxyBuilder;
3 import org.jboss.resteasy.client.ProxyConfig;
4 import org.jboss.resteasy.client.ProxyFactory;
5
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Method;
10 import java.net.URI;
11
12 public class SubResourceInvoker implements MethodInvoker
13 {
14 final ProxyConfig config;
15 final Class<?> iface;
16 final String base;
17 final String format;
18
19 public SubResourceInvoker(URI uri, Method method, ProxyConfig config)
20 {
21 String base = uri.toString();
22 if (!base.endsWith("/"))
23 base = base + "/";
24 this.base = base;
25 this.iface = method.getReturnType();
26 this.config = config;
27 String path = method.getAnnotation(Path.class).value();
28 if (path.startsWith("/"))
29 path = path.substring(1);
30 Annotation[][] params = method.getParameterAnnotations();
31 int index = 1;
32 for (Annotation[] param : params)
33 {
34 for (Annotation a : param)
35 {
36 if (a instanceof PathParam)
37 {
38 String name = ((PathParam) a).value();
39 path = path.replaceFirst("\\{" + name + "(\\s)*(:.*)?\\}", "%" + index + "\\$s");
40 break;
41 }
42 }
43 index++;
44 }
45 this.format = path;
46 }
47
48 @Override
49 public Object invoke(Object[] args)
50 {
51 String path = String.format(format, args);
52 return ProxyBuilder.createProxy(iface, ProxyFactory.createUri(base + path), config);
53 }
54 }
+0
-17
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/VoidEntityTypeFactory.java less more
0 package org.jboss.resteasy.client.core;
1
2 import org.jboss.resteasy.client.EntityTypeFactory;
3
4 import javax.ws.rs.core.MultivaluedMap;
5
6 public class VoidEntityTypeFactory implements EntityTypeFactory
7 {
8
9 @SuppressWarnings("unchecked")
10 public Class getEntityType(int status,
11 MultivaluedMap<String, Object> metadata)
12 {
13 return Void.class;
14 }
15
16 }
+0
-639
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/executors/ApacheHttpClient4Executor.java less more
0 package org.jboss.resteasy.client.core.executors;
1
2 import org.apache.commons.io.output.DeferredFileOutputStream;
3 import org.apache.http.Header;
4 import org.apache.http.HttpEntity;
5 import org.apache.http.HttpResponse;
6 import org.apache.http.NameValuePair;
7 import org.apache.http.client.HttpClient;
8 import org.apache.http.client.entity.UrlEncodedFormEntity;
9 import org.apache.http.client.methods.HttpGet;
10 import org.apache.http.client.methods.HttpPost;
11 import org.apache.http.client.methods.HttpRequestBase;
12 import org.apache.http.client.params.HttpClientParams;
13 import org.apache.http.conn.ClientConnectionManager;
14 import org.apache.http.entity.ByteArrayEntity;
15 import org.apache.http.impl.client.DefaultHttpClient;
16 import org.apache.http.entity.FileEntity;
17 import org.apache.http.message.BasicHeader;
18 import org.apache.http.message.BasicNameValuePair;
19 import org.apache.http.protocol.HTTP;
20 import org.apache.http.protocol.HttpContext;
21 import org.jboss.resteasy.client.ClientExecutor;
22 import org.jboss.resteasy.client.ClientRequest;
23 import org.jboss.resteasy.client.ClientResponse;
24 import org.jboss.resteasy.client.core.BaseClientResponse;
25 import org.jboss.resteasy.client.core.BaseClientResponse.BaseClientResponseStreamFactory;
26 import org.jboss.resteasy.client.core.SelfExpandingBufferredInputStream;
27 import org.jboss.resteasy.client.exception.mapper.ApacheHttpClient4ExceptionMapper;
28 import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper;
29 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
30 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
31 import org.jboss.resteasy.spi.ResteasyProviderFactory;
32 import org.jboss.resteasy.util.CaseInsensitiveMap;
33 import org.jboss.resteasy.util.Types;
34
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.core.UriBuilder;
37
38 import java.io.BufferedInputStream;
39 import java.io.ByteArrayOutputStream;
40 import java.io.File;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.lang.management.ManagementFactory;
44 import java.lang.reflect.Type;
45 import java.util.ArrayList;
46 import java.util.List;
47 import java.util.Map;
48
49 /**
50 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
51 * @version $Revision: 1 $
52 */
53 public class ApacheHttpClient4Executor implements ClientExecutor
54 {
55 public static final String BYTE_MEMORY_UNIT = "BY";
56 public static final String KILOBYTE_MEMORY_UNIT = "KB";
57 public static final String MEGABYTE_MEMORY_UNIT = "MB";
58 public static final String GIGABYTE_MEMORY_UNIT = "GB";
59
60 /**
61 * Used to build temp file prefix.
62 */
63 private static String processId = null;
64
65 static
66 {
67 ApacheHttpClient4Executor.processId = ManagementFactory.getRuntimeMXBean().getName().replaceAll("[^0-9a-zA-Z]", "");
68 }
69
70 static synchronized private void checkClientExceptionMapper()
71 {
72 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
73 if (factory instanceof org.jboss.resteasy.spi.old.ResteasyProviderFactory)
74 {
75 org.jboss.resteasy.spi.old.ResteasyProviderFactory f = (org.jboss.resteasy.spi.old.ResteasyProviderFactory)factory;
76 if (f.getClientExceptionMapper(Exception.class) == null)
77 {
78 Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class,
79 ClientExceptionMapper.class)[0];
80 f.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);
81 }
82 }
83 }
84
85 protected HttpClient httpClient;
86 protected boolean createdHttpClient;
87 protected HttpContext httpContext;
88 protected boolean closed;
89
90 /**
91 * For uploading File's over JAX-RS framework, this property, together with {@link #fileUploadMemoryUnit},
92 * defines the maximum File size allowed in memory. If fileSize exceeds this size, it will be stored to
93 * {@link #fileUploadTempFileDir}. <br>
94 * <br>
95 * Defaults to 1 MB
96 */
97 private int fileUploadInMemoryThresholdLimit = 1;
98
99 /**
100 * The unit for {@link #fileUploadInMemoryThresholdLimit}. <br>
101 * <br>
102 * Defaults to MB.
103 *
104 * @see MemoryUnit
105 */
106 private MemoryUnit fileUploadMemoryUnit = MemoryUnit.MB;
107
108 /**
109 * Temp directory to write output request stream to. Any file to be uploaded has to be written out to the
110 * output request stream to be sent to the service and when the File is too huge the output request stream is
111 * written out to the disk rather than to memory. <br>
112 * <br>
113 * Defaults to JVM temp directory.
114 */
115 private File fileUploadTempFileDir = new File(System.getProperty("java.io.tmpdir"));
116
117 protected int responseBufferSize = 8192;
118
119 public ApacheHttpClient4Executor()
120 {
121 this(new DefaultHttpClient(), null);
122 this.createdHttpClient = true;
123 }
124
125 public ApacheHttpClient4Executor(HttpClient httpClient)
126 {
127 this(httpClient, null);
128 }
129
130 public ApacheHttpClient4Executor(HttpClient httpClient, HttpContext httpContext)
131 {
132 this.httpClient = httpClient;
133 this.httpContext = httpContext;
134 checkClientExceptionMapper();
135 }
136
137 /**
138 * Response stream is wrapped in a BufferedInputStream. Default is 8192. Value of 0 will not wrap it.
139 * Value of -1 will use a SelfExpandingBufferedInputStream
140 *
141 * @return
142 */
143 public int getResponseBufferSize()
144 {
145 return responseBufferSize;
146 }
147
148 /**
149 * Response stream is wrapped in a BufferedInputStream. Default is 8192. Value of 0 will not wrap it.
150 * Value of -1 will use a SelfExpandingBufferedInputStream
151 *
152 * @param responseBufferSize
153 */
154 public void setResponseBufferSize(int responseBufferSize)
155 {
156 this.responseBufferSize = responseBufferSize;
157 }
158
159 public HttpClient getHttpClient()
160 {
161 return httpClient;
162 }
163
164 public HttpContext getHttpContext()
165 {
166 return httpContext;
167 }
168
169 public void setHttpContext(HttpContext httpContext)
170 {
171 this.httpContext = httpContext;
172 }
173
174 public static CaseInsensitiveMap<String> extractHeaders(
175 HttpResponse response)
176 {
177 final CaseInsensitiveMap<String> headers = new CaseInsensitiveMap<String>();
178
179 for (Header header : response.getAllHeaders())
180 {
181 headers.add(header.getName(), header.getValue());
182 }
183 return headers;
184 }
185
186 public ClientRequest createRequest(String uriTemplate)
187 {
188 return new ClientRequest(uriTemplate, this);
189 }
190
191 public ClientRequest createRequest(UriBuilder uriBuilder)
192 {
193 return new ClientRequest(uriBuilder, this);
194 }
195
196 static class ResponseStream extends SelfExpandingBufferredInputStream
197 {
198 BaseClientResponse response;
199
200 public ResponseStream(InputStream in, BaseClientResponse response)
201 {
202 super(in);
203 // Keep a reference to the response object to prevent it being finalized prematurely
204 this.response = response;
205 }
206
207 public synchronized void close() throws IOException
208 {
209 super.close();
210 // Response object is no longer needed and can be finalized
211 response = null;
212 }
213 }
214
215 protected InputStream createBufferedStream(InputStream is)
216 {
217 if (responseBufferSize == 0)
218 {
219 return is;
220 }
221 if (responseBufferSize < 0)
222 {
223 return new SelfExpandingBufferredInputStream(is);
224 }
225 BufferedInputStream bis = new BufferedInputStream(is, responseBufferSize);
226 // mark read limit
227 bis.mark(responseBufferSize);
228 return bis;
229 }
230
231 @SuppressWarnings("unchecked")
232 public ClientResponse execute(ClientRequest request) throws Exception
233 {
234 String uri = request.getUri();
235 final HttpRequestBase httpMethod = createHttpMethod(uri, request.getHttpMethod());
236 try
237 {
238 loadHttpMethod(request, httpMethod);
239
240 final HttpResponse res = httpClient.execute(httpMethod, httpContext);
241
242 final BaseClientResponse response = new BaseClientResponse(null, this);
243 BaseClientResponseStreamFactory sf = new BaseClientResponseStreamFactory()
244 {
245 InputStream stream;
246
247 public InputStream getInputStream() throws IOException
248 {
249 if (stream == null)
250 {
251 HttpEntity entity = res.getEntity();
252 if (entity == null) return null;
253 // stream = new SelfExpandingBufferredInputStream(entity.getContent());
254 stream = createBufferedStream(entity.getContent());
255 }
256 return stream;
257 }
258
259 public void performReleaseConnection()
260 {
261 // Apache Client 4 is stupid, You have to get the InputStream and close it if there is an entity
262 // otherwise the connection is never released. There is, of course, no close() method on response
263 // to make this easier.
264 try
265 {
266 if (stream != null)
267 {
268 stream.close();
269 }
270 else
271 {
272 InputStream is = getInputStream();
273 if (is != null)
274 {
275 is.close();
276 }
277 }
278 }
279 catch (Exception ignore)
280 {
281 }
282 }
283 };
284 response.setStreamFactory(sf);
285 response.setAttributes(request.getAttributes());
286 response.setStatus(res.getStatusLine().getStatusCode());
287 response.setHeaders(extractHeaders(res));
288 response.setProviderFactory(request.getProviderFactory());
289 return response;
290 }
291 finally
292 {
293 cleanUpAfterExecute(httpMethod);
294 }
295 }
296
297 /**
298 * If passed httpMethod is of type HttpPost then obtain its entity. If the entity has an enclosing File then
299 * delete it by invoking this method after the request has completed. The entity will have an enclosing File
300 * only if it was too huge to fit into memory.
301 *
302 * @param httpMethod - the httpMethod to clean up.
303 * @see #writeRequestBodyToOutputStream(ClientRequest)
304 */
305 protected void cleanUpAfterExecute(final HttpRequestBase httpMethod)
306 {
307 if (httpMethod != null && httpMethod instanceof HttpPost)
308 {
309 HttpPost postMethod = (HttpPost) httpMethod;
310 HttpEntity entity = postMethod.getEntity();
311 if (entity != null && entity instanceof FileExposingFileEntity)
312 {
313 File tempRequestFile = ((FileExposingFileEntity) entity).getFile();
314 try
315 {
316 boolean isDeleted = tempRequestFile.delete();
317 if (!isDeleted)
318 {
319 handleFileNotDeletedError(tempRequestFile, null);
320 }
321 }
322 catch (Exception ex)
323 {
324 handleFileNotDeletedError(tempRequestFile, ex);
325 }
326 }
327 }
328 }
329
330 private HttpRequestBase createHttpMethod(String url, String restVerb)
331 {
332 if ("GET".equals(restVerb))
333 {
334 return new HttpGet(url);
335 }
336 else if ("POST".equals(restVerb))
337 {
338 return new HttpPost(url);
339 }
340 else
341 {
342 final String verb = restVerb;
343 return new HttpPost(url)
344 {
345 @Override
346 public String getMethod()
347 {
348 return verb;
349 }
350 };
351 }
352 }
353
354 public void loadHttpMethod(final ClientRequest request, HttpRequestBase httpMethod) throws Exception
355 {
356 if (httpMethod instanceof HttpGet && request.followRedirects())
357 {
358 HttpClientParams.setRedirecting(httpMethod.getParams(), true);
359 }
360 else
361 {
362 HttpClientParams.setRedirecting(httpMethod.getParams(), false);
363 }
364
365 if (request.getBody() != null && !request.getFormParameters().isEmpty())
366 throw new RuntimeException(Messages.MESSAGES.cannotSendFormParametersAndEntity());
367
368 if (!request.getFormParameters().isEmpty())
369 {
370 commitHeaders(request, httpMethod);
371 HttpPost post = (HttpPost) httpMethod;
372
373 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
374
375 for (Map.Entry<String, List<String>> formParam : request.getFormParameters().entrySet())
376 {
377 List<String> values = formParam.getValue();
378 for (String value : values)
379 {
380 formparams.add(new BasicNameValuePair(formParam.getKey(), value));
381 }
382 }
383
384 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
385 post.setEntity(entity);
386 }
387 else if (request.getBody() != null)
388 {
389 if (httpMethod instanceof HttpGet) throw new RuntimeException(Messages.MESSAGES.getRequestCannotHaveBody());
390
391 try
392 {
393 HttpEntity entity = buildEntity(request);
394 HttpPost post = (HttpPost) httpMethod;
395 commitHeaders(request, httpMethod);
396 post.setEntity(entity);
397 }
398 catch (IOException e)
399 {
400 throw new RuntimeException(e);
401 }
402 }
403 else // no body
404 {
405 commitHeaders(request, httpMethod);
406 }
407 }
408
409 /**
410 * Build the HttpEntity to be sent to the Service as part of (POST) request. Creates a off-memory
411 * {@link FileExposingFileEntity} or a regular in-memory {@link ByteArrayEntity} depending on if the request
412 * OutputStream fit into memory when built by calling {@link #writeRequestBodyToOutputStream(ClientRequest)}.
413 *
414 * @param request -
415 * @return - the built HttpEntity
416 * @throws IOException -
417 */
418 protected HttpEntity buildEntity(final ClientRequest request) throws IOException
419 {
420 HttpEntity entityToBuild = null;
421 DeferredFileOutputStream memoryManagedOutStream = writeRequestBodyToOutputStream(request);
422
423 if (memoryManagedOutStream.isInMemory())
424 {
425 ByteArrayEntity entityToBuildByteArray = new ByteArrayEntity(memoryManagedOutStream.getData());
426 entityToBuildByteArray.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, request.getBodyContentType().toString()));
427 entityToBuild = entityToBuildByteArray;
428 }
429 else
430 {
431 entityToBuild = new FileExposingFileEntity(memoryManagedOutStream.getFile(), request.getBodyContentType().toString());
432 }
433
434 return entityToBuild;
435 }
436
437 /**
438 * Creates the request OutputStream, to be sent to the end Service invoked, as a
439 * <a href="http://commons.apache.org/io/api-release/org/apache/commons/io/output/DeferredFileOutputStream.html"
440 * >DeferredFileOutputStream</a>.
441 *
442 * @param request -
443 * @return - DeferredFileOutputStream with the ClientRequest written out per HTTP specification.
444 * @throws IOException -
445 */
446 private DeferredFileOutputStream writeRequestBodyToOutputStream(final ClientRequest request) throws IOException
447 {
448 DeferredFileOutputStream memoryManagedOutStream =
449 new DeferredFileOutputStream(this.fileUploadInMemoryThresholdLimit * getMemoryUnitMultiplier(),
450 getTempfilePrefix(), ".tmp", this.fileUploadTempFileDir);
451 request.writeRequestBody(request.getHeadersAsObjects(), memoryManagedOutStream);
452 memoryManagedOutStream.close();
453 return memoryManagedOutStream;
454 }
455
456 /**
457 * @return - the constant to multiply {@link #fileUploadInMemoryThresholdLimit} with based on
458 * {@link #fileUploadMemoryUnit} enumeration value.
459 */
460 private int getMemoryUnitMultiplier()
461 {
462 switch (this.fileUploadMemoryUnit)
463 {
464 case BY:
465 return 1;
466 case KB:
467 return 1024;
468 case MB:
469 return 1024 * 1024;
470 case GB:
471 return 1024 * 1024 * 1024;
472 }
473 return 1;
474 }
475
476 /**
477 * Use context information, which will include node name, to avoid conflicts in case of multiple VMS using same
478 * temp directory location.
479 *
480 * @return -
481 */
482 protected String getTempfilePrefix()
483 {
484 return ApacheHttpClient4Executor.processId;
485 }
486
487 /**
488 * Log that the file did not get deleted but prevent the request from failing by eating the exception.
489 * Register the file to be deleted on exit, so it will get deleted eventually.
490 *
491 * @param tempRequestFile -
492 * @param ex - a null may be passed in which case this param gets ignored.
493 */
494 private void handleFileNotDeletedError(File tempRequestFile, Exception ex)
495 {
496 LogMessages.LOGGER.couldNotDeleteFile(tempRequestFile.getAbsolutePath(), ex);
497 tempRequestFile.deleteOnExit();
498 }
499
500 /**
501 * Setter for the {@link HttpClient} to which this class delegates the actual HTTP call. Note that this class
502 * acts as the adapter between RestEasy and Apache HTTP Component library.
503 *
504 * @param pHttpClient -
505 */
506 void setHttpClient(HttpClient pHttpClient)
507 {
508 this.httpClient = pHttpClient;
509 }
510
511 /**
512 * Setter for {@link #fileUploadInMemoryThresholdLimit}
513 *
514 * @param pInMemoryThresholdLimit - the inMemoryThresholdLimitMB to set
515 */
516 public void setFileUploadInMemoryThresholdLimit(int pInMemoryThresholdLimit)
517 {
518 this.fileUploadInMemoryThresholdLimit = pInMemoryThresholdLimit;
519 }
520
521 /**
522 * Setter for {@link #fileUploadTempFileDir}
523 *
524 * @param pTempFileDir the tempFileDir to set
525 */
526 public void setFileUploadTempFileDir(File pTempFileDir)
527 {
528 this.fileUploadTempFileDir = pTempFileDir;
529 }
530
531 /**
532 * Setter for {@link #fileUploadMemoryUnit}
533 *
534 * @param pMemoryUnit the memoryUnit to set
535 */
536 public void setFileUploadMemoryUnit(String pMemoryUnit)
537 {
538 this.fileUploadMemoryUnit = MemoryUnit.valueOf(pMemoryUnit);
539 }
540
541 public void commitHeaders(ClientRequest request, HttpRequestBase httpMethod)
542 {
543 MultivaluedMap<String, String> headers = request.getHeaders();
544 for (Map.Entry<String, List<String>> header : headers.entrySet())
545 {
546 List<String> values = header.getValue();
547 for (String value : values)
548 {
549 // System.out.println(String.format("setting %s = %s", header.getKey(), value));
550 httpMethod.addHeader(header.getKey(), value);
551 }
552 }
553 }
554
555 public void close()
556 {
557 if (closed)
558 return;
559
560 if (createdHttpClient && httpClient != null)
561 {
562 ClientConnectionManager manager = httpClient.getConnectionManager();
563 if (manager != null)
564 {
565 manager.shutdown();
566 }
567 }
568 closed = true;
569 }
570
571 public boolean isClosed()
572 {
573 return closed;
574 }
575
576 public void finalize() throws Throwable
577 {
578 close();
579 super.finalize();
580 }
581
582 /**
583 * We use {@link FileEntity} as the {@link HttpEntity} implementation when the request OutputStream has been
584 * saved to a File on disk (because it was too large to fit into memory see
585 * {@link RestCFHttpClientExecutor#writeRequestBodyToOutputStream(ClientRequest)}); however, we have to delete
586 * the File supporting the <code>FileEntity</code>, otherwise the disk will soon run out of space - remember
587 * that there can be very huge files, in GB range, processed on a regular basis - and FileEntity exposes its
588 * content File as a protected field. For the enclosing parent class ( {@link ApacheHttpClient4Executor} ) to be
589 * able to get a handle to this content File and delete it, this class expose the content File.<br>
590 * This class is private scoped to prevent access to this content File outside of the parent class.
591 *
592 * @author <a href="mailto:stikoo@digitalriver.com">Sandeep Tikoo</a>
593 */
594 private static class FileExposingFileEntity extends FileEntity
595 {
596 /**
597 * @param pFile -
598 * @param pContentType -
599 */
600 public FileExposingFileEntity(File pFile, String pContentType)
601 {
602 super(pFile, pContentType);
603 }
604
605 /**
606 * @return - the content File enclosed by this FileEntity.
607 */
608 File getFile()
609 {
610 return this.file;
611 }
612 }
613
614 /**
615 * Enumeration to represent memory units.
616 */
617 private static enum MemoryUnit
618 {
619 /**
620 * Bytes
621 */
622 BY,
623 /**
624 * Killo Bytes
625 */
626 KB,
627
628 /**
629 * Mega Bytes
630 */
631 MB,
632
633 /**
634 * Giga Bytes
635 */
636 GB
637 }
638 }
+0
-202
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/executors/InMemoryClientExecutor.java less more
0 package org.jboss.resteasy.client.core.executors;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.core.BaseClientResponse;
6 import org.jboss.resteasy.client.core.BaseClientResponse.BaseClientResponseStreamFactory;
7 import org.jboss.resteasy.core.Dispatcher;
8 import org.jboss.resteasy.core.SynchronousDispatcher;
9 import org.jboss.resteasy.core.SynchronousExecutionContext;
10 import org.jboss.resteasy.mock.MockHttpRequest;
11 import org.jboss.resteasy.mock.MockHttpResponse;
12 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
13 import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
14 import org.jboss.resteasy.spi.Registry;
15 import org.jboss.resteasy.spi.ResteasyProviderFactory;
16
17 import javax.ws.rs.core.HttpHeaders;
18 import javax.ws.rs.core.MediaType;
19 import javax.ws.rs.core.MultivaluedMap;
20 import javax.ws.rs.core.UriBuilder;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.URI;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31
32 /**
33 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
34 * @version $Revision: 1 $
35 */
36 @SuppressWarnings("unchecked")
37 public class InMemoryClientExecutor implements ClientExecutor
38 {
39 protected Dispatcher dispatcher;
40 protected URI baseUri;
41
42 public InMemoryClientExecutor()
43 {
44 dispatcher = new SynchronousDispatcher(ResteasyProviderFactory.getInstance());
45 }
46
47 public InMemoryClientExecutor(Dispatcher dispatcher)
48 {
49 this.dispatcher = dispatcher;
50 }
51
52 public URI getBaseUri()
53 {
54 return baseUri;
55 }
56
57 public void setBaseUri(URI baseUri)
58 {
59 this.baseUri = baseUri;
60 }
61
62 public ClientRequest createRequest(String uriTemplate)
63 {
64 return new ClientRequest(uriTemplate, this);
65 }
66
67 public ClientRequest createRequest(UriBuilder uriBuilder)
68 {
69 return new ClientRequest(uriBuilder, this);
70 }
71
72
73 public ClientResponse execute(ClientRequest request) throws Exception
74 {
75 MockHttpRequest mockHttpRequest = MockHttpRequest.create(request.getHttpMethod(), new URI(request.getUri()),
76 baseUri);
77 final MockHttpResponse mockResponse = new MockHttpResponse();
78 mockHttpRequest.setAsynchronousContext(new SynchronousExecutionContext((SynchronousDispatcher)dispatcher, mockHttpRequest, mockResponse));
79 loadHttpMethod(request, mockHttpRequest);
80
81 dispatcher.invoke(mockHttpRequest, mockResponse);
82 return createResponse(request, mockResponse);
83 }
84
85 protected BaseClientResponse createResponse(ClientRequest request, final MockHttpResponse mockResponse)
86 {
87 BaseClientResponseStreamFactory streamFactory = createStreamFactory(mockResponse);
88 BaseClientResponse response = new BaseClientResponse(streamFactory, this);
89 response.setStatus(mockResponse.getStatus());
90 setHeaders(mockResponse, response);
91 response.setProviderFactory(request.getProviderFactory());
92 response.setAttributes(request.getAttributes());
93 return response;
94 }
95
96 protected void setHeaders(final MockHttpResponse mockResponse, BaseClientResponse response)
97 {
98 MultivaluedMapImpl<String, String> responseHeaders = new MultivaluedMapImpl<String, String>();
99 for (Entry<String, List<Object>> entry : mockResponse.getOutputHeaders().entrySet())
100 {
101 List<String> values = new ArrayList<String>(entry.getValue().size());
102 for (Object value : entry.getValue())
103 {
104 values.add(value.toString());
105 }
106 responseHeaders.addMultiple(entry.getKey(), values);
107 }
108 response.setHeaders(responseHeaders);
109 }
110
111 public static BaseClientResponseStreamFactory createStreamFactory(final MockHttpResponse mockResponse)
112 {
113 return new BaseClientResponseStreamFactory()
114 {
115 InputStream stream;
116
117 public InputStream getInputStream() throws IOException
118 {
119 if (stream == null)
120 {
121 stream = new ByteArrayInputStream(mockResponse.getOutput());
122 }
123 return stream;
124 }
125
126 public void performReleaseConnection()
127 {
128 }
129 };
130 }
131
132 public void loadHttpMethod(ClientRequest request, MockHttpRequest mockHttpRequest) throws Exception
133 {
134 // TODO: punt on redirects, for now.
135 // if (httpMethod instanceof GetMethod && request.followRedirects())
136 // httpMethod.setFollowRedirects(true);
137 // else httpMethod.setFollowRedirects(false);
138
139 if (request.getBody() != null && !request.getFormParameters().isEmpty())
140 throw new RuntimeException(Messages.MESSAGES.cannotSendFormParametersAndEntity());
141
142 if (!request.getFormParameters().isEmpty())
143 {
144 commitHeaders(request, mockHttpRequest);
145 for (Map.Entry<String, List<String>> formParam : request.getFormParameters().entrySet())
146 {
147 String key = formParam.getKey();
148 for (String value : formParam.getValue())
149 {
150 mockHttpRequest.getFormParameters().add(key, value);
151 }
152 }
153 }
154 else if (request.getBody() != null)
155 {
156 ByteArrayOutputStream baos = new ByteArrayOutputStream();
157
158 MediaType bodyContentType = request.getBodyContentType();
159 request.getHeadersAsObjects().add(HttpHeaders.CONTENT_TYPE, bodyContentType.toString());
160
161 request.writeRequestBody(request.getHeadersAsObjects(), baos);
162 // commit headers after byte array is complete.
163 commitHeaders(request, mockHttpRequest);
164 mockHttpRequest.content(baos.toByteArray());
165 mockHttpRequest.contentType(bodyContentType);
166 }
167 else
168 {
169 commitHeaders(request, mockHttpRequest);
170 }
171 }
172
173 public void commitHeaders(ClientRequest request, MockHttpRequest mockHttpRequest)
174 {
175 MultivaluedMap headers = mockHttpRequest.getHttpHeaders().getRequestHeaders();
176 headers.putAll(request.getHeaders());
177 }
178
179 private void setBody(ClientRequest request, MockHttpRequest mockHttpRequest) throws IOException
180 {
181 if (request.getBody() == null)
182 return;
183
184 }
185
186 public Registry getRegistry()
187 {
188 return this.dispatcher.getRegistry();
189 }
190
191 public Dispatcher getDispatcher()
192 {
193 return dispatcher;
194 }
195
196 public void close()
197 {
198 // empty
199 }
200
201 }
+0
-179
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/executors/URLConnectionClientExecutor.java less more
0 package org.jboss.resteasy.client.core.executors;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.core.BaseClientResponse;
6 import org.jboss.resteasy.client.core.BaseClientResponse.BaseClientResponseStreamFactory;
7 import org.jboss.resteasy.util.CaseInsensitiveMap;
8 import org.jboss.resteasy.util.CommitHeaderOutputStream;
9
10 import javax.ws.rs.core.MultivaluedMap;
11 import javax.ws.rs.core.UriBuilder;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.OutputStream;
15 import java.net.HttpURLConnection;
16 import java.net.ProtocolException;
17 import java.net.URL;
18 import java.util.List;
19 import java.util.Map.Entry;
20
21 import static org.jboss.resteasy.util.HttpHeaderNames.*;
22
23 public class URLConnectionClientExecutor implements ClientExecutor
24 {
25
26 public ClientResponse<?> execute(ClientRequest request) throws Exception
27 {
28 HttpURLConnection connection = createConnection(request);
29 return execute(request, connection);
30 }
31
32 private void commitHeaders(ClientRequest request, HttpURLConnection connection)
33 {
34 for (Entry<String, List<String>> entry : request.getHeaders().entrySet())
35 {
36 String value = null;
37 if (entry.getValue().size() == 1)
38 value = entry.getValue().get(0);
39 else
40 {
41 StringBuilder b = new StringBuilder();
42 String add = "";
43 for (String v : entry.getValue())
44 {
45 b.append(add).append(v);
46 add = ",";
47 }
48 value = b.toString();
49 }
50 connection.addRequestProperty(entry.getKey(), value);
51 }
52 }
53
54 public ClientRequest createRequest(String uriTemplate)
55 {
56 return new ClientRequest(uriTemplate, this);
57 }
58
59 public ClientRequest createRequest(UriBuilder uriBuilder)
60 {
61 return new ClientRequest(uriBuilder, this);
62 }
63
64 protected HttpURLConnection createConnection(ClientRequest request) throws Exception
65 {
66 String uri = request.getUri();
67 String httpMethod = request.getHttpMethod();
68
69 HttpURLConnection connection = (HttpURLConnection) new URL(uri).openConnection();
70 connection.setRequestMethod(httpMethod);
71 return connection;
72 }
73
74 private <T> ClientResponse<T> execute(ClientRequest request, final HttpURLConnection connection) throws IOException
75 {
76 outputBody(request, connection);
77 final int status = connection.getResponseCode();
78 BaseClientResponse<T> response = new BaseClientResponse<T>(new BaseClientResponseStreamFactory()
79 {
80 public InputStream getInputStream() throws IOException
81 {
82 return (status < 300) ? connection.getInputStream() : connection.getErrorStream();
83 }
84
85 public void performReleaseConnection()
86 {
87 try
88 {
89 getInputStream().close();
90 }
91 catch (IOException e)
92 {
93 }
94 connection.disconnect();
95 }
96 }, this);
97 response.setProviderFactory(request.getProviderFactory());
98 response.setStatus(status);
99 response.setHeaders(getHeaders(connection));
100 response.setAttributes(request.getAttributes());
101 return response;
102 }
103
104 public void close()
105 {
106 // empty
107 }
108
109 private MultivaluedMap<String, String> getHeaders(
110 final HttpURLConnection connection)
111 {
112 MultivaluedMap<String, String> headers = new CaseInsensitiveMap<String>();
113
114 for (Entry<String, List<String>> header : connection.getHeaderFields()
115 .entrySet())
116 {
117 if (header.getKey() != null)
118 for (String value : header.getValue())
119 headers.add(header.getKey(), value);
120 }
121 return headers;
122 }
123
124 private void outputBody(final ClientRequest request, final HttpURLConnection connection)
125 {
126 if (request.getBody() != null)
127 {
128 // System.out.println(request.getBody());
129 if (connection.getRequestProperty(CONTENT_TYPE) == null)
130 {
131 String type = request.getBodyContentType().toString();
132 connection.addRequestProperty(CONTENT_TYPE, type);
133 }
134 try
135 {
136 final CommitHeaderOutputStream commit = new CommitHeaderOutputStream();
137 CommitHeaderOutputStream.CommitCallback callback = new CommitHeaderOutputStream.CommitCallback()
138 {
139 @Override
140 public void commit()
141 {
142 connection.setDoOutput(true);
143 commitHeaders(request, connection);
144 OutputStream os = null;
145 try
146 {
147 os = connection.getOutputStream();
148 }
149 catch (IOException e)
150 {
151 throw new RuntimeException(e);
152 }
153 commit.setDelegate(os);
154
155 }
156 };
157 commit.setHeaders(callback);
158 try
159 {
160 request.writeRequestBody(request.getHeadersAsObjects(), commit);
161 }
162 finally
163 {
164 commit.getDelegate().flush();
165 commit.getDelegate().close();
166 }
167 }
168 catch (IOException e)
169 {
170 throw new RuntimeException(e);
171 }
172 }
173 else
174 {
175 commitHeaders(request, connection);
176 }
177 }
178 }
+0
-84
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/extractors/BodyEntityExtractor.java less more
0 /**
1 *
2 */
3 package org.jboss.resteasy.client.core.extractors;
4
5 import org.jboss.resteasy.client.ClientResponseFailure;
6 import org.jboss.resteasy.client.core.BaseClientResponse;
7 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
8
9 import javax.ws.rs.ext.MessageBodyReader;
10
11 import java.io.InputStream;
12 import java.lang.reflect.Method;
13
14 /**
15 * BodyEntityExtractor extract body objects from responses. This ends up calling
16 * the appropriate MessageBodyReader through a series of calls
17 *
18 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
19 * @version $Revision: 1 $
20 * @see EntityExtractorFactory
21 * @see MessageBodyReader
22 */
23 @SuppressWarnings("unchecked")
24 public class BodyEntityExtractor implements EntityExtractor
25 {
26 private final Method method;
27
28 public BodyEntityExtractor(Method method)
29 {
30 this.method = method;
31 }
32
33 public Object extractEntity(ClientRequestContext context, Object... args)
34 {
35 final BaseClientResponse response = context.getClientResponse();
36 try
37 {
38 response.checkFailureStatus();
39 }
40 catch (ClientResponseFailure ce)
41 {
42 // If ClientResponseFailure do a copy of the response and then release the connection,
43 // we need to use the copy here and not the original response
44 context.getErrorHandler().clientErrorHandling((BaseClientResponse) ce.getResponse(), ce);
45 }
46 catch (RuntimeException e)
47 {
48 context.getErrorHandler().clientErrorHandling(response, e);
49 }
50
51 // only release connection if it is not an instance of an
52 // InputStream
53 boolean releaseConnectionAfter = true;
54 try
55 {
56 // void methods should be handled before this method gets called, but it's worth being defensive
57 if (method.getReturnType() == null)
58 {
59 // throw new RuntimeException(
60 // "No type information to extract entity with. You use other getEntity() methods");
61 throw new RuntimeException(Messages.MESSAGES.noTypeInformationForEntity());
62 }
63 Object obj = response.getEntity(method.getReturnType(), method.getGenericReturnType());
64 if (obj instanceof InputStream)
65 {
66 releaseConnectionAfter = false;
67 // we make sure that on GC, the Response does not release the InputStream
68 response.setWasReleased(true);
69 }
70 return obj;
71 }
72 catch (RuntimeException e)
73 {
74 context.getErrorHandler().clientErrorHandling(response, e);
75 }
76 finally
77 {
78 if (releaseConnectionAfter)
79 response.releaseConnection();
80 }
81 throw new RuntimeException(Messages.MESSAGES.shouldBeUnreachable());
82 }
83 }
+0
-53
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/extractors/ClientErrorHandler.java less more
0 package org.jboss.resteasy.client.core.extractors;
1
2 import org.jboss.resteasy.client.core.BaseClientResponse;
3 import org.jboss.resteasy.client.core.ClientErrorInterceptor;
4
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.util.List;
8
9 /**
10 * This class handles client errors (of course...).
11 *
12 * @author Solomon.Duskis
13 */
14
15 // TODO: expand this class for more robust, complicated error handling
16
17 public class ClientErrorHandler
18 {
19 private List<ClientErrorInterceptor> interceptors;
20
21 public ClientErrorHandler(List<ClientErrorInterceptor> interceptors)
22 {
23 this.interceptors = interceptors;
24 }
25
26 @SuppressWarnings("unchecked")
27 public void clientErrorHandling(BaseClientResponse clientResponse, RuntimeException e)
28 {
29 for (ClientErrorInterceptor handler : interceptors)
30 {
31 try
32 {
33 // attempt to reset the stream in order to provide a fresh stream
34 // to each ClientErrorInterceptor -- failing to reset the stream
35 // could mean that an unusable stream will be passed to the
36 // interceptor
37 InputStream stream = clientResponse.getStreamFactory().getInputStream();
38 if (stream != null)
39 {
40 stream.reset();
41 }
42 }
43 catch (IOException e1)
44 {
45 // eat this exception since it's not really relevant for the client
46 // response
47 }
48 handler.handle(clientResponse);
49 }
50 throw e;
51 }
52 }
+0
-50
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/extractors/ClientRequestContext.java less more
0 package org.jboss.resteasy.client.core.extractors;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.core.BaseClientResponse;
4
5 import java.net.URI;
6
7 public class ClientRequestContext
8 {
9 private ClientRequest request;
10 private BaseClientResponse<?> clientResponse;
11 private ClientErrorHandler errorHandler;
12 private EntityExtractorFactory extractorFactory;
13 private URI baseURI;
14
15 public ClientRequestContext(ClientRequest request, BaseClientResponse<?> clientResponse,
16 ClientErrorHandler errorHandler, EntityExtractorFactory extractorFactory, URI baseURI)
17 {
18 this.request = request;
19 this.clientResponse = clientResponse;
20 this.errorHandler = errorHandler;
21 this.extractorFactory = extractorFactory;
22 this.baseURI = baseURI;
23 }
24
25 public ClientRequest getRequest()
26 {
27 return request;
28 }
29
30 public BaseClientResponse getClientResponse()
31 {
32 return clientResponse;
33 }
34
35 public ClientErrorHandler getErrorHandler()
36 {
37 return errorHandler;
38 }
39
40 public EntityExtractorFactory getExtractorFactory()
41 {
42 return extractorFactory;
43 }
44
45 public URI getBaseURI()
46 {
47 return baseURI;
48 }
49 }
+0
-80
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/extractors/ClientResponseProxy.java less more
0 package org.jboss.resteasy.client.core.extractors;
1
2 import java.lang.reflect.InvocationHandler;
3 import java.lang.reflect.Method;
4 import java.util.Map;
5
6 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
7
8 /**
9 * Implement a client proxy for ProxyFactory. This class implements each method
10 * using an EntityExtractor
11 *
12 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
13 * @version $Revision: 1 $
14 * @see ProxyFactory
15 * @see EntityExtractor
16 * @see EntityExtractorFactory
17 * @see ResponseObjectEntityExtractorFactory
18 */
19 @SuppressWarnings("unchecked")
20 public class ClientResponseProxy implements InvocationHandler
21 {
22 private ClientRequestContext context;
23 private Map<Method, EntityExtractor<?>> methodMap;
24 private Class<?> clazz;
25
26 public ClientResponseProxy(ClientRequestContext context, Map<Method, EntityExtractor<?>> methodMap, Class<?> clazz)
27 {
28 super();
29 this.methodMap = methodMap;
30 this.clazz = clazz;
31 this.context = context;
32 }
33
34 public Object invoke(Object o, Method method, Object[] args) throws Throwable
35 {
36 // equals and hashCode were added for cases where the proxy is added to
37 // collections. The Spring transaction management, for example, adds
38 // transactional Resources to a Collection, and it calls equals and
39 // hashCode.
40 if (method.getName().equals("equals"))
41 {
42 return this.equals(o);
43 }
44 else if (method.getName().equals("hashCode"))
45 {
46 return this.hashCode();
47 }
48
49 EntityExtractor entityExtractor = methodMap.get(method);
50 if (entityExtractor == null)
51 throw new RuntimeException(Messages.MESSAGES.couldNotProcessMethod(method));
52
53 return entityExtractor.extractEntity(context, entityExtractor, args);
54 }
55
56 @Override
57 public boolean equals(Object obj)
58 {
59 if (obj == null || !(obj instanceof ClientResponseProxy))
60 return false;
61 ClientResponseProxy other = (ClientResponseProxy) obj;
62 if (other == this)
63 return true;
64 if (other.clazz != this.clazz)
65 return false;
66 return super.equals(obj);
67 }
68
69 @Override
70 public int hashCode()
71 {
72 return clazz.hashCode();
73 }
74
75 public String toString()
76 {
77 return "Client Proxy for :" + clazz.getName();
78 }
79 }
+0
-169
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/extractors/DefaultEntityExtractorFactory.java less more
0 package org.jboss.resteasy.client.core.extractors;
1
2 import org.jboss.resteasy.annotations.legacy.ClientResponseType;
3 import org.jboss.resteasy.annotations.ResponseObject;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.client.ClientResponseFailure;
6 import org.jboss.resteasy.client.EntityTypeFactory;
7 import org.jboss.resteasy.client.core.BaseClientResponse;
8 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
9 import org.jboss.resteasy.util.Types;
10
11 import javax.ws.rs.core.Response;
12
13 import java.lang.reflect.Method;
14 import java.lang.reflect.ParameterizedType;
15 import java.lang.reflect.Type;
16
17 /**
18 * @author Solomon.Duskis
19 */
20 @SuppressWarnings("unchecked")
21 public class DefaultEntityExtractorFactory implements EntityExtractorFactory
22 {
23
24 public static final EntityExtractor clientResponseExtractor = new EntityExtractor<ClientResponse>()
25 {
26 public ClientResponse extractEntity(ClientRequestContext context, Object... args)
27 {
28 return context.getClientResponse();
29 }
30 };
31
32 public static EntityExtractor<Response.Status> createStatusExtractor(final boolean release)
33 {
34 return new EntityExtractor<Response.Status>()
35 {
36 public Response.Status extractEntity(ClientRequestContext context, Object... args)
37 {
38 if (release)
39 context.getClientResponse().releaseConnection();
40 return context.getClientResponse().getResponseStatus();
41 }
42 };
43 }
44
45 public static final EntityExtractor createVoidExtractor(final boolean release)
46 {
47 return new EntityExtractor()
48 {
49 public Object extractEntity(ClientRequestContext context, Object... args)
50 {
51 try
52 {
53 context.getClientResponse().checkFailureStatus();
54 }
55 catch (ClientResponseFailure ce)
56 {
57 // If ClientResponseFailure do a copy of the response and then release the connection,
58 // we need to use the copy here and not the original response
59 context.getErrorHandler().clientErrorHandling((BaseClientResponse) ce.getResponse(), ce);
60 }
61 catch (RuntimeException e)
62 {
63 context.getErrorHandler().clientErrorHandling(context.getClientResponse(), e);
64 }
65 if (release)
66 context.getClientResponse().releaseConnection();
67 return null;
68 }
69 };
70 }
71
72 public EntityExtractor createExtractor(final Method method)
73 {
74 final Class returnType = method.getReturnType();
75 if (isVoidReturnType(returnType))
76 return createVoidExtractor(true);
77 if (returnType.equals(Response.Status.class))
78 return createStatusExtractor(true);
79
80 if (Response.class.isAssignableFrom(returnType))
81 return createResponseTypeEntityExtractor(method);
82
83 if (returnType.isInterface() && returnType.isAnnotationPresent(ResponseObject.class))
84 return new ResponseObjectProxy(method, new ResponseObjectEntityExtractorFactory());
85
86 // We are not a ClientResponse type so we need to unmarshall and narrow it
87 // to right type. If we are unable to unmarshall, or encounter any kind of
88 // Exception, give the ClientErrorHandlers a chance to handle the
89 // ClientResponse manually.
90
91 return new BodyEntityExtractor(method);
92 }
93
94 protected EntityExtractor createResponseTypeEntityExtractor(final Method method)
95 {
96 final ClientResponseType responseHint = method.getAnnotation(ClientResponseType.class);
97 if (responseHint != null)
98 {
99 final Class responseHintReturnType = responseHint.entityType();
100 if (isVoidReturnType(responseHintReturnType))
101 {
102 final Class<? extends EntityTypeFactory> entityTypeFactory = responseHint.entityTypeFactory();
103 return new EntityExtractor()
104 {
105 public Object extractEntity(ClientRequestContext context, Object... args)
106 {
107 EntityTypeFactory factory = null;
108 try
109 {
110 factory = entityTypeFactory.newInstance();
111 }
112 catch (InstantiationException e)
113 {
114 throw context.getClientResponse().createResponseFailure(Messages.MESSAGES.couldNotCreateEntityFactory(entityTypeFactory.getClass().getName()));
115 }
116 catch (IllegalAccessException e)
117 {
118 throw ((BaseClientResponse<?>)context.getClientResponse())
119 .createResponseFailure(Messages.MESSAGES.couldNotCreateEntityFactoryMessage(entityTypeFactory.getClass().getName(), e.getMessage()));
120 }
121 context.getClientResponse().setReturnType(
122 factory.getEntityType(((BaseClientResponse<?>) context.getClientResponse()).getStatus(),
123 ((BaseClientResponse<?>) context.getClientResponse()).getMetadata()));
124 return context.getClientResponse();
125 }
126 };
127 }
128 else
129 {
130 return new EntityExtractor()
131 {
132 public Object extractEntity(ClientRequestContext context, Object... args)
133 {
134 context.getClientResponse().setReturnType(responseHintReturnType);
135 return context.getClientResponse();
136 }
137 };
138 }
139 }
140 else
141 {
142 final Type methodGenericReturnType = method.getGenericReturnType();
143 if (methodGenericReturnType instanceof ParameterizedType)
144 {
145 final ParameterizedType zType = (ParameterizedType) methodGenericReturnType;
146 final Type genericReturnType = zType.getActualTypeArguments()[0];
147 final Class<?> responseReturnType = Types.getRawType(genericReturnType);
148 return new EntityExtractor()
149 {
150 public Object extractEntity(ClientRequestContext context, Object... args)
151 {
152 context.getClientResponse().setReturnType(responseReturnType);
153 context.getClientResponse().setGenericReturnType(genericReturnType);
154 return context.getClientResponse();
155 }
156 };
157 }
158 else
159 return clientResponseExtractor;
160 }
161 }
162
163 public static final boolean isVoidReturnType(Class<?> returnType)
164 {
165 return returnType == null || void.class.equals(returnType) || Void.class.equals(returnType);
166 }
167
168 }
+0
-16
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/extractors/EntityExtractor.java less more
0 package org.jboss.resteasy.client.core.extractors;
1
2
3 /**
4 * EntityExtractor extract objects from responses. An extractor can extract a
5 * status, a header, a cookie, the response body, the clientRequest object, the
6 * clientResponse object, or anything else that a "response object" might need.
7 *
8 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
9 * @version $Revision: 1 $
10 * @see EntityExtractorFactory
11 */
12 public interface EntityExtractor<T>
13 {
14 T extractEntity(ClientRequestContext context, Object... args);
15 }
+0
-19
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/extractors/EntityExtractorFactory.java less more
0 package org.jboss.resteasy.client.core.extractors;
1
2 import java.lang.reflect.Method;
3
4 /**
5 * Create an EntityExtractor based on a method. This will allow different
6 * factories to be used for different purposes, including custom user driven
7 * factories.
8 *
9 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
10 * @version $Revision: 1 $
11 * @see EntityExtractor, DefaultObjectEntityExtractor,
12 * ResponseObjectEntityExtractor
13 */
14 public interface EntityExtractorFactory
15 {
16 @SuppressWarnings("unchecked")
17 public EntityExtractor createExtractor(Method method);
18 }
+0
-252
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/extractors/ResponseObjectEntityExtractorFactory.java less more
0 package org.jboss.resteasy.client.core.extractors;
1
2 import org.jboss.resteasy.annotations.Body;
3 import org.jboss.resteasy.annotations.LinkHeaderParam;
4 import org.jboss.resteasy.annotations.Status;
5 import org.jboss.resteasy.client.ClientExecutor;
6 import org.jboss.resteasy.client.ClientRequest;
7 import org.jboss.resteasy.client.Link;
8 import org.jboss.resteasy.client.LinkHeader;
9 import org.jboss.resteasy.client.ProxyFactory;
10 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
11 import org.jboss.resteasy.spi.ResteasyProviderFactory;
12 import org.jboss.resteasy.util.IsHttpMethod;
13
14 import javax.ws.rs.HeaderParam;
15 import javax.ws.rs.core.Response;
16
17 import java.lang.reflect.Method;
18 import java.net.MalformedURLException;
19 import java.net.URI;
20 import java.net.URISyntaxException;
21 import java.net.URL;
22 import java.util.Set;
23
24 /**
25 * This class represents the method level creation of a "rich response object"
26 * that has the @ResponseObject annotation. These EntityExtractors will be used
27 * to implment methods of ResponseObject via ResponseObjectEntityExtractor
28 *
29 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
30 * @version $Revision: 1 $
31 * @see EntityExtractor, ResponseObjectEntityExtractor
32 */
33 public class ResponseObjectEntityExtractorFactory extends DefaultEntityExtractorFactory
34 {
35
36 @SuppressWarnings("unchecked")
37 public EntityExtractor createExtractor(final Method method)
38 {
39 final Class<?> returnType = method.getReturnType();
40 if (method.isAnnotationPresent(Status.class))
41 {
42 if (returnType == Integer.class || returnType == int.class)
43 {
44
45 return new EntityExtractor<Integer>()
46 {
47 public Integer extractEntity(ClientRequestContext context, Object... args)
48 {
49 return context.getClientResponse().getStatus();
50 }
51 };
52 }
53 else if (returnType == Response.Status.class)
54 {
55 return createStatusExtractor(false);
56 }
57 }
58
59 if (method.isAnnotationPresent(Body.class))
60 {
61 return new BodyEntityExtractor(method);
62 }
63
64 final HeaderParam headerParam = method.getAnnotation(HeaderParam.class);
65 if (headerParam != null)
66 {
67 return new EntityExtractor()
68 {
69 public Object extractEntity(ClientRequestContext context, Object... args)
70 {
71 return context.getClientResponse().getResponseHeaders().getFirst(headerParam.value());
72 }
73 };
74 }
75
76 final LinkHeaderParam link = method.getAnnotation(LinkHeaderParam.class);
77 if (link != null)
78 {
79 return processLinkHeader(method, returnType, link);
80 }
81
82 if (returnType == ClientRequest.class)
83 {
84 return new EntityExtractor()
85 {
86 public Object extractEntity(ClientRequestContext context, Object... args)
87 {
88 return context.getRequest();
89 }
90 };
91 }
92
93 if (Response.class.isAssignableFrom(returnType))
94 {
95 return createResponseTypeEntityExtractor(method);
96 }
97
98 if (returnType == LinkHeader.class)
99 {
100 return new EntityExtractor()
101 {
102 public Object extractEntity(ClientRequestContext context, Object... args)
103 {
104 return context.getClientResponse().getLinkHeader();
105 }
106 };
107 }
108
109 return null;
110 }
111
112 private EntityExtractor processLinkHeader(final Method method, final Class<?> returnType,
113 final LinkHeaderParam link)
114 {
115 if ("".equals(link.rel()) && "".equals(link.title()))
116 {
117 throw new RuntimeException(Messages.MESSAGES.mustSetLinkHeaderRelOrTitle(method.getClass().getName(), method.getName()));
118 }
119 if (!"".equals(link.rel()) && !"".equals(link.title()))
120 {
121 throw new RuntimeException(Messages.MESSAGES.canOnlySetLinkHeaderRelOrTitle(method.getClass().getName(), method.getName()));
122 }
123
124 if (returnType == Link.class)
125 {
126 return new EntityExtractor()
127 {
128 public Object extractEntity(ClientRequestContext context, Object... args)
129 {
130 return getLink(link, context);
131 }
132 };
133 }
134
135 if (isInvokerMethod(method))
136 {
137 return new EntityExtractor()
138 {
139 public Object extractEntity(ClientRequestContext context, Object... args)
140 {
141 URI uri = getURI(method, link, context);
142 if (uri == null)
143 return null;
144
145 ClientRequest request = context.getRequest();
146 EntityExtractorFactory extractor = context.getExtractorFactory();
147 ResteasyProviderFactory provider = request.getProviderFactory();
148 ClientExecutor executor = request.getExecutor();
149 return ProxyFactory.createClientInvoker(method.getDeclaringClass(), method, uri,
150 executor, provider, extractor).invoke(args);
151 }
152 };
153 }
154
155 if (returnType == String.class)
156 {
157 return new EntityExtractor<String>()
158 {
159 public String extractEntity(ClientRequestContext context, Object... args)
160 {
161 Link link2 = getLink(link, context);
162 return link2 == null ? null : link2.getHref();
163 }
164 };
165 }
166
167 if (returnType == URL.class)
168 {
169 return new EntityExtractor<URL>()
170 {
171 public URL extractEntity(ClientRequestContext context, Object... args)
172 {
173 return getURL(method, link, context);
174 }
175 };
176 }
177 if (returnType == URI.class)
178 {
179 return new EntityExtractor<URI>()
180 {
181 public URI extractEntity(ClientRequestContext context, Object... args)
182 {
183 return getURI(method, link, context);
184 }
185 };
186 }
187
188 if (returnType.equals(ClientRequest.class))
189 {
190 return new EntityExtractor<ClientRequest>()
191 {
192 public ClientRequest extractEntity(ClientRequestContext context, Object... args)
193 {
194 URI uri = getURI(method, link, context);
195 return uri == null ? null : context.getRequest().createSubsequentRequest(uri);
196 }
197 };
198 }
199
200 return null;
201 }
202
203 private static boolean isInvokerMethod(Method method)
204 {
205 Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
206 return httpMethods != null && httpMethods.size() == 1;
207 }
208
209 private Link getLink(final LinkHeaderParam link, ClientRequestContext context)
210 {
211 LinkHeader linkHeader = context.getClientResponse().getLinkHeader();
212 if (!"".equals(link.rel()))
213 return linkHeader.getLinkByRelationship(link.rel());
214 else
215 return linkHeader.getLinkByTitle(link.title());
216 }
217
218 private URI getURI(final Method method, Link link)
219 {
220 if (link == null)
221 {
222 return null;
223 }
224 try
225 {
226 return new URI(link.getHref());
227 }
228 catch (URISyntaxException e)
229 {
230 throw new RuntimeException(Messages.MESSAGES.couldNotCreateURI(link.getHref(), method.getClass().getName(), method.getName()), e);
231 }
232 }
233
234 private URI getURI(final Method method, final LinkHeaderParam link, ClientRequestContext context)
235 {
236 return getURI(method, getLink(link, context));
237 }
238
239 private URL getURL(final Method method, final LinkHeaderParam link, ClientRequestContext context)
240 {
241 URI uri = getURI(method, link, context);
242 try
243 {
244 return uri == null ? null : uri.toURL();
245 }
246 catch (MalformedURLException e)
247 {
248 throw new RuntimeException(Messages.MESSAGES.couldNotCreateURI(uri.toASCIIString(), method.getClass().getName(), method.getName()), e);
249 }
250 }
251 }
+0
-40
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/extractors/ResponseObjectProxy.java less more
0 package org.jboss.resteasy.client.core.extractors;
1
2 import java.lang.reflect.Method;
3 import java.lang.reflect.Proxy;
4 import java.util.HashMap;
5
6 /**
7 * This class represents the proxying functionality for creating a
8 * "rich response object" that has the @ResponseObject annotation. The method
9 * implementations ware created in ResponseObjectEntityExtractorFactory
10 *
11 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
12 * @version $Revision: 1 $
13 * @see EntityExtractor, ResponseObjectEntityExtractorFactory
14 */
15
16 @SuppressWarnings("unchecked")
17 public class ResponseObjectProxy<T> implements EntityExtractor
18 {
19 private Class<T> returnType;
20 private HashMap<Method, EntityExtractor<?>> methodHandlers;
21
22 public ResponseObjectProxy(Method method, EntityExtractorFactory extractorFactory)
23 {
24 this.returnType = (Class<T>) method.getReturnType();
25 this.methodHandlers = new HashMap<Method, EntityExtractor<?>>();
26 for (Method interfaceMethod : this.returnType.getMethods())
27 {
28 this.methodHandlers.put(interfaceMethod, extractorFactory.createExtractor(interfaceMethod));
29 }
30 }
31
32 public Object extractEntity(ClientRequestContext context, Object... args)
33 {
34 Class<?>[] intfs = {returnType};
35 ClientResponseProxy clientProxy = new ClientResponseProxy(context, methodHandlers, returnType);
36 return Proxy.newProxyInstance(returnType.getClassLoader(), intfs, clientProxy);
37 }
38
39 }
+0
-144
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/ClientMarshallerFactory.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.annotations.Form;
3 import org.jboss.resteasy.client.ClientURI;
4 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
5 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.util.FindAnnotation;
7 import org.jboss.resteasy.util.MediaTypeHelper;
8
9 import javax.ws.rs.BeanParam;
10 import javax.ws.rs.CookieParam;
11 import javax.ws.rs.Encoded;
12 import javax.ws.rs.FormParam;
13 import javax.ws.rs.HeaderParam;
14 import javax.ws.rs.MatrixParam;
15 import javax.ws.rs.PathParam;
16 import javax.ws.rs.QueryParam;
17 import javax.ws.rs.core.Context;
18 import javax.ws.rs.core.Cookie;
19 import javax.ws.rs.core.MediaType;
20
21 import java.lang.annotation.Annotation;
22 import java.lang.reflect.AccessibleObject;
23 import java.lang.reflect.Method;
24 import java.lang.reflect.Type;
25
26 public class ClientMarshallerFactory
27 {
28
29 public static Marshaller[] createMarshallers(Class declaringClass, Method method, ResteasyProviderFactory providerFactory)
30 {
31 return createMarshallers(declaringClass, method, providerFactory, null);
32 }
33
34 public static Marshaller[] createMarshallers(Class declaringClass, Method method, ResteasyProviderFactory providerFactory, MediaType defaultConsumes)
35 {
36 Marshaller[] params = new Marshaller[method.getParameterTypes().length];
37 for (int i = 0; i < method.getParameterTypes().length; i++)
38 {
39 Class<?> type = method.getParameterTypes()[i];
40 Annotation[] annotations = method.getParameterAnnotations()[i];
41 Type genericType = method.getGenericParameterTypes()[i];
42 AccessibleObject target = method;
43 params[i] = ClientMarshallerFactory.createMarshaller(declaringClass, providerFactory, type, annotations, genericType, target, defaultConsumes, false);
44 }
45 return params;
46 }
47
48 public static Marshaller createMarshaller(Class<?> declaring,
49 ResteasyProviderFactory providerFactory, Class<?> type,
50 Annotation[] annotations, Type genericType, AccessibleObject target,
51 boolean ignoreBody)
52 {
53 return createMarshaller(declaring, providerFactory, type, annotations, genericType, target, null, ignoreBody);
54 }
55
56 public static Marshaller createMarshaller(Class<?> declaring,
57 ResteasyProviderFactory providerFactory, Class<?> type,
58 Annotation[] annotations, Type genericType, AccessibleObject target, MediaType defaultConsumes,
59 boolean ignoreBody)
60 {
61 Marshaller marshaller = null;
62
63 QueryParam query;
64 HeaderParam header;
65 MatrixParam matrix;
66 PathParam uriParam;
67 CookieParam cookie;
68 FormParam formParam;
69 // Form form;
70
71 boolean isEncoded = FindAnnotation.findAnnotation(annotations,
72 Encoded.class) != null;
73
74 if ((query = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null)
75 {
76 marshaller = new QueryParamMarshaller(query.value());
77 }
78 else if ((header = FindAnnotation.findAnnotation(annotations,
79 HeaderParam.class)) != null)
80 {
81 marshaller = new HeaderParamMarshaller(header.value());
82 }
83 else if ((cookie = FindAnnotation.findAnnotation(annotations,
84 CookieParam.class)) != null)
85 {
86 marshaller = new CookieParamMarshaller(cookie.value());
87 }
88 else if ((uriParam = FindAnnotation.findAnnotation(annotations,
89 PathParam.class)) != null)
90 {
91 marshaller = new PathParamMarshaller(uriParam.value(), isEncoded,
92 providerFactory);
93 }
94 else if ((matrix = FindAnnotation.findAnnotation(annotations,
95 MatrixParam.class)) != null)
96 {
97 marshaller = new MatrixParamMarshaller(matrix.value());
98 }
99 else if ((formParam = FindAnnotation.findAnnotation(annotations,
100 FormParam.class)) != null)
101 {
102 marshaller = new FormParamMarshaller(formParam.value());
103 }
104 else if ((/* form = */FindAnnotation.findAnnotation(annotations,
105 Form.class)) != null)
106 {
107 marshaller = new FormMarshaller(type, providerFactory);
108 }
109 else if ((/* form = */FindAnnotation.findAnnotation(annotations,
110 BeanParam.class)) != null)
111 {
112 marshaller = new FormMarshaller(type, providerFactory);
113 }
114 else if ((FindAnnotation.findAnnotation(annotations,
115 Context.class)) != null)
116 {
117 marshaller = new NOOPMarshaller();
118 }
119 else if (type.equals(Cookie.class))
120 {
121 marshaller = new CookieParamMarshaller(null);
122 }
123 // this is for HATEAOS clients
124 else if (FindAnnotation.findAnnotation(annotations, ClientURI.class) != null
125 || FindAnnotation.findAnnotation(annotations, org.jboss.resteasy.annotations.ClientURI.class) != null)
126 {
127 marshaller = new URIParamMarshaller();
128 }
129 else if (!ignoreBody)
130 {
131 MediaType mediaType = MediaTypeHelper.getConsumes(declaring, target);
132 if(mediaType == null)
133 mediaType = defaultConsumes;
134 if (mediaType == null)
135 {
136 throw new RuntimeException(Messages.MESSAGES.mustDefineConsumes());
137 }
138 marshaller = new MessageBodyParameterMarshaller(mediaType, type,
139 genericType, annotations);
140 }
141 return marshaller;
142 }
143 }
+0
-38
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/CookieParamMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import javax.ws.rs.core.Cookie;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class CookieParamMarshaller implements Marshaller
11 {
12 private String cookieName;
13
14 public CookieParamMarshaller(String cookieName)
15 {
16 this.cookieName = cookieName;
17 }
18
19 public String getCookieName()
20 {
21 return cookieName;
22 }
23
24 public void build(ClientRequest request, Object object)
25 {
26 if (object == null) return; // don't set a null value
27 if (object instanceof Cookie)
28 {
29 Cookie cookie = (Cookie) object;
30 request.cookie(cookie);
31 }
32 else
33 {
34 request.cookie(cookieName, object);
35 }
36 }
37 }
+0
-227
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/FormMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.spi.LoggableFailure;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import java.io.ByteArrayOutputStream;
7 import java.io.DataOutputStream;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Field;
10 import java.lang.reflect.InvocationTargetException;
11 import java.lang.reflect.Method;
12 import java.lang.reflect.Modifier;
13 import java.lang.reflect.Type;
14 import java.security.DigestOutputStream;
15 import java.security.MessageDigest;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20
21 /**
22 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
23 * @version $Revision: 1 $
24 */
25 public class FormMarshaller implements Marshaller
26 {
27 protected HashMap<Field, Marshaller> fieldMap = new HashMap<Field, Marshaller>();
28
29 private static class GetterMethod
30 {
31 private GetterMethod(Method method, Marshaller marshaller)
32 {
33 this.method = method;
34 this.marshaller = marshaller;
35 }
36
37 public Method method;
38 public Marshaller marshaller;
39 }
40
41 protected List<GetterMethod> getters = new ArrayList<GetterMethod>();
42 protected HashMap<Long, Method> getterHashes = new HashMap<Long, Method>();
43 protected Class clazz;
44
45 public FormMarshaller(Class clazz, ResteasyProviderFactory factory)
46 {
47 this.clazz = clazz;
48
49 populateMap(clazz, factory);
50 }
51
52 public static long methodHash(Method method)
53 throws Exception
54 {
55 Class[] parameterTypes = method.getParameterTypes();
56 StringBuilder methodDesc = new StringBuilder(method.getName()).append("(");
57 for (int j = 0; j < parameterTypes.length; j++)
58 {
59 methodDesc.append(getTypeString(parameterTypes[j]));
60 }
61 methodDesc.append(")").append(getTypeString(method.getReturnType()));
62 return createHash(methodDesc.toString());
63 }
64
65 public static long createHash(String methodDesc)
66 throws Exception
67 {
68 long hash = 0;
69 ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512);
70 MessageDigest messagedigest = MessageDigest.getInstance("SHA");
71 DataOutputStream dataoutputstream = new DataOutputStream(new DigestOutputStream(bytearrayoutputstream, messagedigest));
72 dataoutputstream.writeUTF(methodDesc);
73 dataoutputstream.flush();
74 byte abyte0[] = messagedigest.digest();
75 for (int j = 0; j < Math.min(8, abyte0.length); j++)
76 hash += (long) (abyte0[j] & 0xff) << j * 8;
77 return hash;
78
79 }
80
81 static String getTypeString(Class cl)
82 {
83 if (cl == Byte.TYPE)
84 {
85 return "B";
86 }
87 else if (cl == Character.TYPE)
88 {
89 return "C";
90 }
91 else if (cl == Double.TYPE)
92 {
93 return "D";
94 }
95 else if (cl == Float.TYPE)
96 {
97 return "F";
98 }
99 else if (cl == Integer.TYPE)
100 {
101 return "I";
102 }
103 else if (cl == Long.TYPE)
104 {
105 return "J";
106 }
107 else if (cl == Short.TYPE)
108 {
109 return "S";
110 }
111 else if (cl == Boolean.TYPE)
112 {
113 return "Z";
114 }
115 else if (cl == Void.TYPE)
116 {
117 return "V";
118 }
119 else if (cl.isArray())
120 {
121 return "[" + getTypeString(cl.getComponentType());
122 }
123 else
124 {
125 return "L" + cl.getName().replace('.', '/') + ";";
126 }
127 }
128
129 protected void populateMap(Class clazz, ResteasyProviderFactory factory)
130 {
131 for (Field field : clazz.getDeclaredFields())
132 {
133 Annotation[] annotations = field.getAnnotations();
134 if (annotations == null || annotations.length == 0) continue;
135 Class type = field.getType();
136 Type genericType = field.getGenericType();
137
138 Marshaller marshaller = ClientMarshallerFactory.createMarshaller(
139 clazz, factory, type, annotations, genericType, field, true);
140 if (marshaller != null)
141 {
142 if (!Modifier.isPublic(field.getModifiers())) field.setAccessible(true);
143 fieldMap.put(field, marshaller);
144 }
145 }
146 for (Method method : clazz.getDeclaredMethods())
147 {
148 if (!method.getName().startsWith("get")) continue;
149
150 if (method.getParameterTypes().length > 0) continue;
151
152 Annotation[] annotations = method.getAnnotations();
153 if (annotations == null || annotations.length == 0) continue;
154
155 Class type = method.getReturnType();
156 Type genericType = method.getGenericReturnType();
157
158 Marshaller marshaller = ClientMarshallerFactory
159 .createMarshaller(clazz, factory, type, annotations,
160 genericType, method, true);
161 if (marshaller != null)
162 {
163 long hash = 0;
164 try
165 {
166 hash = methodHash(method);
167 }
168 catch (Exception e)
169 {
170 throw new RuntimeException(e);
171 }
172 if (!Modifier.isPrivate(method.getModifiers()))
173 {
174 Method older = getterHashes.get(hash);
175 if (older != null) continue;
176 }
177
178 if (!Modifier.isPublic(method.getModifiers())) method.setAccessible(true);
179 getters.add(new GetterMethod(method, marshaller));
180 getterHashes.put(hash, method);
181 }
182
183 }
184 if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class))
185 populateMap(clazz.getSuperclass(), factory);
186
187
188 }
189
190 public void build(ClientRequest request, Object object)
191 {
192 if (object == null) return;
193
194 for (Map.Entry<Field, Marshaller> entry : fieldMap.entrySet())
195 {
196
197 try
198 {
199 Object val = entry.getKey().get(object);
200 entry.getValue().build(request, val);
201 }
202 catch (IllegalAccessException e)
203 {
204 throw new LoggableFailure(e);
205 }
206 }
207 for (GetterMethod getter : getters)
208 {
209 Object val = null;
210 try
211 {
212 val = getter.method.invoke(object);
213 }
214 catch (IllegalAccessException e)
215 {
216 throw new RuntimeException(e);
217 }
218 catch (InvocationTargetException e)
219 {
220 throw new RuntimeException(e);
221 }
222 getter.marshaller.build(request, val);
223 }
224 }
225
226 }
+0
-80
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/FormParamMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import java.util.Collection;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class FormParamMarshaller implements Marshaller
11 {
12 private String paramName;
13
14 public FormParamMarshaller(String paramName)
15 {
16 this.paramName = paramName;
17 }
18
19 public void build(ClientRequest request, Object object)
20 {
21 if (object == null) return;
22
23 if (object instanceof Collection)
24 {
25 for (Object obj : (Collection) object)
26 {
27 request.formParameter(paramName, obj);
28 }
29 }
30 else if (object.getClass().isArray())
31 {
32 if (object.getClass().getComponentType().isPrimitive())
33 {
34 Class componentType = object.getClass().getComponentType();
35 if (componentType.equals(boolean.class))
36 {
37 for (Boolean bool : (boolean[]) object) request.formParameter(paramName, bool.toString());
38 }
39 else if (componentType.equals(byte.class))
40 {
41 for (Byte val : (byte[]) object) request.formParameter(paramName, val.toString());
42 }
43 else if (componentType.equals(short.class))
44 {
45 for (Short val : (short[]) object) request.formParameter(paramName, val.toString());
46 }
47 else if (componentType.equals(int.class))
48 {
49 for (Integer val : (int[]) object) request.formParameter(paramName, val.toString());
50 }
51 else if (componentType.equals(long.class))
52 {
53 for (Long val : (long[]) object) request.formParameter(paramName, val.toString());
54 }
55 else if (componentType.equals(float.class))
56 {
57 for (Float val : (float[]) object) request.formParameter(paramName, val.toString());
58 }
59 else if (componentType.equals(double.class))
60 {
61 for (Double val : (double[]) object) request.formParameter(paramName, val.toString());
62 }
63 }
64 else
65 {
66 Object[] objs = (Object[]) object;
67 for (Object obj : objs)
68 {
69 request.formParameter(paramName, obj);
70
71 }
72 }
73 }
74 else
75 {
76 request.formParameter(paramName, object);
77 }
78 }
79 }
+0
-79
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/HeaderParamMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import java.util.Collection;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class HeaderParamMarshaller implements Marshaller
11 {
12 private String paramName;
13
14 public HeaderParamMarshaller(String paramName)
15 {
16 this.paramName = paramName;
17 }
18
19 public void build(ClientRequest request, Object object)
20 {
21 if (object == null) return;
22 if (object instanceof Collection)
23 {
24 for (Object obj : (Collection) object)
25 {
26 request.header(paramName, obj);
27 }
28 }
29 else if (object.getClass().isArray())
30 {
31 if (object.getClass().getComponentType().isPrimitive())
32 {
33 Class componentType = object.getClass().getComponentType();
34 if (componentType.equals(boolean.class))
35 {
36 for (Boolean bool : (boolean[]) object) request.header(paramName, bool.toString());
37 }
38 else if (componentType.equals(byte.class))
39 {
40 for (Byte val : (byte[]) object) request.header(paramName, val.toString());
41 }
42 else if (componentType.equals(short.class))
43 {
44 for (Short val : (short[]) object) request.header(paramName, val.toString());
45 }
46 else if (componentType.equals(int.class))
47 {
48 for (Integer val : (int[]) object) request.header(paramName, val.toString());
49 }
50 else if (componentType.equals(long.class))
51 {
52 for (Long val : (long[]) object) request.header(paramName, val.toString());
53 }
54 else if (componentType.equals(float.class))
55 {
56 for (Float val : (float[]) object) request.header(paramName, val.toString());
57 }
58 else if (componentType.equals(double.class))
59 {
60 for (Double val : (double[]) object) request.header(paramName, val.toString());
61 }
62 }
63 else
64 {
65 Object[] objs = (Object[]) object;
66 for (Object obj : objs)
67 {
68 request.header(paramName, obj);
69
70 }
71 }
72 }
73 else
74 {
75 request.header(paramName, object);
76 }
77 }
78 }
+0
-12
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/Marshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 */
8 public interface Marshaller
9 {
10 void build(ClientRequest request, Object target);
11 }
+0
-37
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/MatrixParamMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import java.util.Collection;
3 import java.util.Iterator;
4
5 import org.jboss.resteasy.client.ClientRequest;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 */
11 public class MatrixParamMarshaller implements Marshaller
12 {
13 private String paramName;
14
15 public MatrixParamMarshaller(String paramName)
16 {
17 this.paramName = paramName;
18 }
19
20 public void build(ClientRequest request, Object object)
21 {
22 if (object == null) return; // Don't add a null matrix parameter
23 if (object instanceof Collection)
24 {
25 for (Iterator<?> it = Collection.class.cast(object).iterator(); it.hasNext(); )
26 {
27 request.matrixParameter(paramName, it.next());
28 }
29 }
30 else
31 {
32 request.matrixParameter(paramName, object);
33 }
34 }
35
36 }
+0
-43
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/MessageBodyParameterMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import javax.ws.rs.core.MediaType;
5 import java.lang.annotation.Annotation;
6 import java.lang.reflect.Type;
7
8 /**
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @version $Revision: 1 $
11 */
12 public class MessageBodyParameterMarshaller implements Marshaller
13 {
14 private Class type;
15 private MediaType mediaType;
16 private Type genericType;
17 private Annotation[] annotations;
18
19 public MessageBodyParameterMarshaller(MediaType mediaType, Class type, Type genericType, Annotation[] annotations)
20 {
21 this.type = type;
22 this.mediaType = mediaType;
23 this.genericType = genericType;
24 this.annotations = annotations;
25 }
26
27 public void build(ClientRequest request, Object object)
28 {
29 request.body(mediaType, object, type, genericType, annotations);
30 }
31
32 public Class getType()
33 {
34 return type;
35 }
36
37 public MediaType getMediaType()
38 {
39 return mediaType;
40 }
41
42 }
+0
-18
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/NOOPMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 /**
5 * Marshaller that doesn't do anything with the target. Useful for @Context parameters which are server-generated.
6 *
7 * @author Stephane Epardaud
8 */
9 public class NOOPMarshaller implements Marshaller
10 {
11
12 public void build(ClientRequest request, Object target)
13 {
14 // do nothing at all
15 }
16
17 }
+0
-28
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/PathParamMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 /**
6 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7 * @version $Revision: 1 $
8 */
9 public class PathParamMarshaller implements Marshaller
10 {
11 private String paramName;
12 private boolean encoded;
13 private ResteasyProviderFactory factory;
14
15 public PathParamMarshaller(String paramName, boolean encoded, ResteasyProviderFactory factory)
16 {
17 this.paramName = paramName;
18 this.encoded = encoded;
19 this.factory = factory;
20 }
21
22 public void build(ClientRequest request, Object object)
23 {
24 request.pathParameter(paramName, object);
25 }
26
27 }
+0
-79
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/QueryParamMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import java.util.Collection;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class QueryParamMarshaller implements Marshaller
11 {
12 private String paramName;
13
14 public QueryParamMarshaller(String paramName)
15 {
16 this.paramName = paramName;
17 }
18
19 public void build(ClientRequest request, Object object)
20 {
21 if (object == null) return;
22 if (object instanceof Collection)
23 {
24 for (Object obj : (Collection) object)
25 {
26 request.queryParameter(paramName, obj);
27 }
28 }
29 else if (object.getClass().isArray())
30 {
31 if (object.getClass().getComponentType().isPrimitive())
32 {
33 Class componentType = object.getClass().getComponentType();
34 if (componentType.equals(boolean.class))
35 {
36 for (Boolean bool : (boolean[]) object) request.queryParameter(paramName, bool.toString());
37 }
38 else if (componentType.equals(byte.class))
39 {
40 for (Byte val : (byte[]) object) request.queryParameter(paramName, val.toString());
41 }
42 else if (componentType.equals(short.class))
43 {
44 for (Short val : (short[]) object) request.queryParameter(paramName, val.toString());
45 }
46 else if (componentType.equals(int.class))
47 {
48 for (Integer val : (int[]) object) request.queryParameter(paramName, val.toString());
49 }
50 else if (componentType.equals(long.class))
51 {
52 for (Long val : (long[]) object) request.queryParameter(paramName, val.toString());
53 }
54 else if (componentType.equals(float.class))
55 {
56 for (Float val : (float[]) object) request.queryParameter(paramName, val.toString());
57 }
58 else if (componentType.equals(double.class))
59 {
60 for (Double val : (double[]) object) request.queryParameter(paramName, val.toString());
61 }
62 }
63 else
64 {
65 Object[] objs = (Object[]) object;
66 for (Object obj : objs)
67 {
68 request.queryParameter(paramName, obj);
69
70 }
71 }
72 }
73 else
74 {
75 request.queryParameter(paramName, object);
76 }
77 }
78 }
+0
-27
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/ResteasyClientProxy.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.core.ClientInvoker;
3 import org.jboss.resteasy.client.core.ClientInvokerModifier;
4
5 import java.util.Collection;
6
7 /**
8 * implemented by every generated proxy
9 *
10 * @deprecated The Resteasy client framework in resteasy-jaxrs is replaced by the JAX-RS 2.0 compliant resteasy-client module.
11 *
12 * @see resteasy-client
13 * @see org.jboss.resteasy.client.jaxrs.internal.proxy.ResteasyClientProxy
14 *
15 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
16 * @version $Revision: 1 $
17 */
18 @Deprecated
19 public interface ResteasyClientProxy
20 {
21 Collection<ClientInvoker> getResteasyClientInvokers();
22
23 void applyClientInvokerModifier(ClientInvokerModifier modifier);
24
25 <T> T as(Class<T> iface);
26 }
+0
-50
resteasy-legacy/src/main/java/org/jboss/resteasy/client/core/marshallers/URIParamMarshaller.java less more
0 package org.jboss.resteasy.client.core.marshallers;
1
2 import org.jboss.resteasy.client.ClientRequest;
3
4 import java.net.URI;
5 import java.net.URISyntaxException;
6 import java.net.URL;
7
8 /**
9 * allows a user to specify the url.
10 *
11 * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a>
12 * @version $Revision: 1 $
13 */
14 public class URIParamMarshaller implements Marshaller
15 {
16 public void build(ClientRequest request, Object target)
17 {
18 URI uri = getUri(target);
19
20 if (uri != null)
21 {
22 request.overrideUri(uri);
23 }
24 }
25
26 private URI getUri(Object target)
27 {
28 try
29 {
30 if (target instanceof URI)
31 {
32 return (URI) target;
33 }
34 else if (target instanceof URL)
35 {
36 return ((URL) target).toURI();
37 }
38 else if (target instanceof String)
39 {
40 return new URI(target.toString());
41 }
42 }
43 catch (URISyntaxException e)
44 {
45 throw new RuntimeException(e);
46 }
47 return null;
48 }
49 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthChallengeException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyAuthChallengeException extends ResteasyAuthenticationException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyAuthChallengeException()
13 {
14 }
15
16 public ResteasyAuthChallengeException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyAuthChallengeException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyAuthChallengeException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthenticationException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyAuthenticationException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyAuthenticationException()
13 {
14 }
15
16 public ResteasyAuthenticationException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyAuthenticationException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyAuthenticationException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyCircularRedirectException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyCircularRedirectException extends ResteasyRedirectException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyCircularRedirectException()
13 {
14 }
15
16 public ResteasyCircularRedirectException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyCircularRedirectException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyCircularRedirectException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyClientException extends RuntimeException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyClientException()
13 {
14 }
15
16 public ResteasyClientException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyClientException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyClientException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientProtocolException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyClientProtocolException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyClientProtocolException()
13 {
14 }
15
16 public ResteasyClientProtocolException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyClientProtocolException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyClientProtocolException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectTimeoutException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyConnectTimeoutException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyConnectTimeoutException()
13 {
14 }
15
16 public ResteasyConnectTimeoutException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyConnectTimeoutException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyConnectTimeoutException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionClosedException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyConnectionClosedException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyConnectionClosedException()
13 {
14 }
15
16 public ResteasyConnectionClosedException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyConnectionClosedException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyConnectionClosedException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionPoolTimeoutException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyConnectionPoolTimeoutException extends ResteasyConnectTimeoutException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyConnectionPoolTimeoutException()
13 {
14 }
15
16 public ResteasyConnectionPoolTimeoutException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyConnectionPoolTimeoutException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyConnectionPoolTimeoutException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyCookieRestrictionViolationException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyCookieRestrictionViolationException extends ResteasyMalformedCookieException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyCookieRestrictionViolationException()
13 {
14 }
15
16 public ResteasyCookieRestrictionViolationException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyCookieRestrictionViolationException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyCookieRestrictionViolationException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyCredentialsNotAvailableException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyCredentialsNotAvailableException extends ResteasyAuthenticationException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyCredentialsNotAvailableException()
13 {
14 }
15
16 public ResteasyCredentialsNotAvailableException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyCredentialsNotAvailableException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyCredentialsNotAvailableException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpContentTooLargeException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyHttpContentTooLargeException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyHttpContentTooLargeException()
13 {
14 }
15
16 public ResteasyHttpContentTooLargeException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyHttpContentTooLargeException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyHttpContentTooLargeException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyHttpException extends ResteasyClientException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyHttpException()
13 {
14 }
15
16 public ResteasyHttpException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyHttpException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyHttpException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpHostConnectException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyHttpHostConnectException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyHttpHostConnectException()
13 {
14 }
15
16 public ResteasyHttpHostConnectException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyHttpHostConnectException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyHttpHostConnectException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpRecoverableException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyHttpRecoverableException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyHttpRecoverableException()
13 {
14 }
15
16 public ResteasyHttpRecoverableException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyHttpRecoverableException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyHttpRecoverableException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyIOException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyIOException extends ResteasyClientException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyIOException()
13 {
14 }
15
16 public ResteasyIOException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyIOException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyIOException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidCredentialsException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyInvalidCredentialsException extends ResteasyAuthenticationException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyInvalidCredentialsException()
13 {
14 }
15
16 public ResteasyInvalidCredentialsException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyInvalidCredentialsException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyInvalidCredentialsException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidRedirectLocationException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyInvalidRedirectLocationException extends ResteasyRedirectException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyInvalidRedirectLocationException()
13 {
14 }
15
16 public ResteasyInvalidRedirectLocationException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyInvalidRedirectLocationException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyInvalidRedirectLocationException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChallengeException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyMalformedChallengeException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyMalformedChallengeException()
13 {
14 }
15
16 public ResteasyMalformedChallengeException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyMalformedChallengeException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyMalformedChallengeException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChunkCodingException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyMalformedChunkCodingException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyMalformedChunkCodingException()
13 {
14 }
15
16 public ResteasyMalformedChunkCodingException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyMalformedChunkCodingException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyMalformedChunkCodingException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedCookieException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyMalformedCookieException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyMalformedCookieException()
13 {
14 }
15
16 public ResteasyMalformedCookieException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyMalformedCookieException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyMalformedCookieException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyMethodNotSupportedException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyMethodNotSupportedException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyMethodNotSupportedException()
13 {
14 }
15
16 public ResteasyMethodNotSupportedException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyMethodNotSupportedException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyMethodNotSupportedException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyNTLMEngineException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyNTLMEngineException extends ResteasyAuthenticationException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyNTLMEngineException()
13 {
14 }
15
16 public ResteasyNTLMEngineException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyNTLMEngineException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyNTLMEngineException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyNoHttpResponseException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyNoHttpResponseException extends ResteasyIOException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyNoHttpResponseException()
13 {
14 }
15
16 public ResteasyNoHttpResponseException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyNoHttpResponseException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyNoHttpResponseException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyNonRepeatableRequestException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyNonRepeatableRequestException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyNonRepeatableRequestException()
13 {
14 }
15
16 public ResteasyNonRepeatableRequestException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyNonRepeatableRequestException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyNonRepeatableRequestException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyProtocolException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyProtocolException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyProtocolException()
13 {
14 }
15
16 public ResteasyProtocolException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyProtocolException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyProtocolException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyRedirectException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyRedirectException extends ResteasyNonRepeatableRequestException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyRedirectException()
13 {
14 }
15
16 public ResteasyRedirectException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyRedirectException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyRedirectException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyTunnelRefusedException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyTunnelRefusedException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyTunnelRefusedException()
13 {
14 }
15
16 public ResteasyTunnelRefusedException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyTunnelRefusedException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyTunnelRefusedException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyURIException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyURIException extends ResteasyHttpException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyURIException()
13 {
14 }
15
16 public ResteasyURIException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyURIException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyURIException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/ResteasyUnsupportedHttpVersionException.java less more
0 package org.jboss.resteasy.client.exception;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public class ResteasyUnsupportedHttpVersionException extends ResteasyProtocolException
9 {
10 private static final long serialVersionUID = -5711578608757689465L;
11
12 public ResteasyUnsupportedHttpVersionException()
13 {
14 }
15
16 public ResteasyUnsupportedHttpVersionException(String message)
17 {
18 super(message);
19 }
20
21 public ResteasyUnsupportedHttpVersionException(String message, Throwable cause)
22 {
23 super(message, cause);
24 }
25
26 public ResteasyUnsupportedHttpVersionException(Throwable cause)
27 {
28 super(cause);
29 }
30 }
+0
-168
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/mapper/ApacheHttpClient4ExceptionMapper.java less more
0 package org.jboss.resteasy.client.exception.mapper;
1
2 import org.apache.http.ConnectionClosedException;
3 import org.apache.http.HttpException;
4 import org.apache.http.MalformedChunkCodingException;
5 import org.apache.http.MethodNotSupportedException;
6 import org.apache.http.NoHttpResponseException;
7 import org.apache.http.ProtocolException;
8 import org.apache.http.UnsupportedHttpVersionException;
9 import org.apache.http.auth.AuthenticationException;
10 import org.apache.http.auth.InvalidCredentialsException;
11 import org.apache.http.auth.MalformedChallengeException;
12 import org.apache.http.client.CircularRedirectException;
13 import org.apache.http.client.ClientProtocolException;
14 import org.apache.http.client.NonRepeatableRequestException;
15 import org.apache.http.client.RedirectException;
16 import org.apache.http.conn.ConnectTimeoutException;
17 import org.apache.http.conn.ConnectionPoolTimeoutException;
18 import org.apache.http.conn.HttpHostConnectException;
19 import org.apache.http.cookie.CookieRestrictionViolationException;
20 import org.apache.http.cookie.MalformedCookieException;
21 import org.apache.http.impl.auth.NTLMEngineException;
22 import org.apache.http.impl.client.TunnelRefusedException;
23 import org.jboss.resteasy.client.exception.ResteasyAuthenticationException;
24 import org.jboss.resteasy.client.exception.ResteasyCircularRedirectException;
25 import org.jboss.resteasy.client.exception.ResteasyClientException;
26 import org.jboss.resteasy.client.exception.ResteasyClientProtocolException;
27 import org.jboss.resteasy.client.exception.ResteasyConnectTimeoutException;
28 import org.jboss.resteasy.client.exception.ResteasyConnectionClosedException;
29 import org.jboss.resteasy.client.exception.ResteasyConnectionPoolTimeoutException;
30 import org.jboss.resteasy.client.exception.ResteasyCookieRestrictionViolationException;
31 import org.jboss.resteasy.client.exception.ResteasyHttpException;
32 import org.jboss.resteasy.client.exception.ResteasyHttpHostConnectException;
33 import org.jboss.resteasy.client.exception.ResteasyIOException;
34 import org.jboss.resteasy.client.exception.ResteasyInvalidCredentialsException;
35 import org.jboss.resteasy.client.exception.ResteasyMalformedChallengeException;
36 import org.jboss.resteasy.client.exception.ResteasyMalformedChunkCodingException;
37 import org.jboss.resteasy.client.exception.ResteasyMalformedCookieException;
38 import org.jboss.resteasy.client.exception.ResteasyMethodNotSupportedException;
39 import org.jboss.resteasy.client.exception.ResteasyNTLMEngineException;
40 import org.jboss.resteasy.client.exception.ResteasyNoHttpResponseException;
41 import org.jboss.resteasy.client.exception.ResteasyNonRepeatableRequestException;
42 import org.jboss.resteasy.client.exception.ResteasyProtocolException;
43 import org.jboss.resteasy.client.exception.ResteasyRedirectException;
44 import org.jboss.resteasy.client.exception.ResteasyTunnelRefusedException;
45 import org.jboss.resteasy.client.exception.ResteasyUnsupportedHttpVersionException;
46
47 import javax.ws.rs.ext.Provider;
48 import java.io.IOException;
49
50 /**
51 *
52 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
53 * @version $Revision: 1.1 $
54 *
55 * Copyright Jul 28, 2012
56 */
57 @Provider
58 public class ApacheHttpClient4ExceptionMapper implements ClientExceptionMapper<Exception>
59 {
60 @Override
61 public ResteasyClientException toException(Exception exception)
62 {
63 if (exception instanceof IOException)
64 {
65 return mapIOException(IOException.class.cast(exception));
66 }
67 if (exception instanceof HttpException)
68 {
69 return mapHttpException(HttpException.class.cast(exception));
70 }
71 return new ResteasyClientException("Unexpected exception type", exception);
72 }
73
74 private ResteasyClientException mapIOException(IOException e)
75 {
76 if (ClientProtocolException.class.equals(e.getClass()))
77 {
78 return new ResteasyClientProtocolException(e);
79 }
80 if (ConnectionClosedException.class.equals(e.getClass()))
81 {
82 return new ResteasyConnectionClosedException(e);
83 }
84 if (ConnectionPoolTimeoutException.class.equals(e.getClass()))
85 {
86 return new ResteasyConnectionPoolTimeoutException(e);
87 }
88 if (ConnectTimeoutException.class.equals(e.getClass()))
89 {
90 return new ResteasyConnectTimeoutException(e);
91 }
92 if (HttpHostConnectException.class.equals(e.getClass()))
93 {
94 return new ResteasyHttpHostConnectException(e);
95 }
96 if (MalformedChunkCodingException.class.equals(e.getClass()))
97 {
98 return new ResteasyMalformedChunkCodingException(e);
99 }
100 if (NoHttpResponseException.class.equals(e.getClass()))
101 {
102 return new ResteasyNoHttpResponseException(e);
103 }
104 if (NoHttpResponseException.class.equals(e.getClass()))
105 {
106 return new ResteasyNoHttpResponseException(e);
107 }
108 return new ResteasyIOException("IOException", e);
109 }
110
111 private ResteasyClientException mapHttpException(HttpException e)
112 {
113 if (AuthenticationException.class.equals(e.getClass()))
114 {
115 return new ResteasyAuthenticationException(e);
116 }
117 if (CircularRedirectException.class.equals(e.getClass()))
118 {
119 return new ResteasyCircularRedirectException(e);
120 }
121 if (CookieRestrictionViolationException.class.equals(e.getClass()))
122 {
123 return new ResteasyCookieRestrictionViolationException(e);
124 }
125 if (InvalidCredentialsException.class.equals(e.getClass()))
126 {
127 return new ResteasyInvalidCredentialsException(e);
128 }
129 if (MalformedChallengeException.class.equals(e.getClass()))
130 {
131 return new ResteasyMalformedChallengeException(e);
132 }
133 if (MalformedCookieException.class.equals(e.getClass()))
134 {
135 return new ResteasyMalformedCookieException(e);
136 }
137 if (MethodNotSupportedException.class.equals(e.getClass()))
138 {
139 return new ResteasyMethodNotSupportedException(e);
140 }
141 if (NonRepeatableRequestException.class.equals(e.getClass()))
142 {
143 return new ResteasyNonRepeatableRequestException(e);
144 }
145 if (NTLMEngineException.class.equals(e.getClass()))
146 {
147 return new ResteasyNTLMEngineException(e);
148 }
149 if (ProtocolException.class.equals(e.getClass()))
150 {
151 return new ResteasyProtocolException(e);
152 }
153 if (RedirectException.class.equals(e.getClass()))
154 {
155 return new ResteasyRedirectException(e);
156 }
157 if (TunnelRefusedException.class.equals(e.getClass()))
158 {
159 return new ResteasyTunnelRefusedException(e);
160 }
161 if (UnsupportedHttpVersionException.class.equals(e.getClass()))
162 {
163 return new ResteasyUnsupportedHttpVersionException(e);
164 }
165 return new ResteasyHttpException("HttpException", e);
166 }
167 }
+0
-12
resteasy-legacy/src/main/java/org/jboss/resteasy/client/exception/mapper/ClientExceptionMapper.java less more
0 package org.jboss.resteasy.client.exception.mapper;
1
2 /**
3 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
4 * @version $Revision: 1.1 $
5 *
6 * Copyright Jul 28, 2012
7 */
8 public interface ClientExceptionMapper<E extends Throwable>
9 {
10 RuntimeException toException(E exception);
11 }
+0
-23
resteasy-legacy/src/main/java/org/jboss/resteasy/client/package-info.java less more
0 /**
1 * JAX-RS specification 1.1 ({@link <a href="https://jcp.org/en/jsr/detail?id=311">https://jcp.org/en/jsr/detail?id=311</a>})
2 * had no client framework, so Resteasy release 2.x provided one. It has two ways to access a server resource:
3 *
4 * <ol>
5 * <li>
6 * {@link org.jboss.resteasy.client.ClientRequest}
7 * </li>
8 * <li>
9 * a proxy that implements an interface implemented by the target resource
10 * </ol>
11 *
12 * JAX-RS specification 2.0
13 * ({@link <a href="https://www.jcp.org/aboutJava/communityprocess/final/jsr339/index.html">https://www.jcp.org/aboutJava/communityprocess/final/jsr339/index.html</a>})
14 * introduced an official client framework, so the older Resteasy client framework is now deprecated. However, the new JAX-RS
15 * framework does not include a proxy feature, so Resteasy extends the official client framework with a new proxy feature.
16 * A proxy can be created using {@link org.jboss.resteasy.client.jaxrs.ResteasyWebTarget}, which extends the api class
17 * javax.ws.rs.client.WebTarget
18 * <p>
19 * For more information, see the Resteasy User Guide
20 * {@link <a href="http://docs.jboss.org/resteasy/docs/">http://docs.jboss.org/resteasy/docs/</a>}.
21 */
22 package org.jboss.resteasy.client;
+0
-29
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/AbstractReaderInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import java.io.InputStream;
3 import java.lang.annotation.Annotation;
4 import java.lang.reflect.Type;
5
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.ReaderInterceptor;
9
10 import org.jboss.resteasy.spi.ResteasyProviderFactory;
11
12 /**
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext instead.
16 */
17 @Deprecated
18 public abstract class AbstractReaderInterceptorContext extends org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext
19 {
20
21 public AbstractReaderInterceptorContext(MediaType mediaType, ResteasyProviderFactory providerFactory,
22 Annotation[] annotations, ReaderInterceptor[] interceptors, MultivaluedMap<String, String> headers,
23 Type genericType, Class type, InputStream inputStream)
24 {
25 super(mediaType, providerFactory, annotations, interceptors, headers, genericType, type, inputStream);
26 }
27
28 }
+0
-29
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/AbstractWriterInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import java.io.OutputStream;
3 import java.lang.annotation.Annotation;
4 import java.lang.reflect.Type;
5
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.WriterInterceptor;
9
10 import org.jboss.resteasy.spi.ResteasyProviderFactory;
11
12 /**
13 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
14 * @version $Revision: 1 $
15 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext instead.
16 */
17 @Deprecated
18 public abstract class AbstractWriterInterceptorContext extends org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext
19 {
20
21 public AbstractWriterInterceptorContext(WriterInterceptor[] interceptors, Annotation[] annotations, Object entity,
22 Type genericType, MediaType mediaType, Class type, OutputStream outputStream,
23 ResteasyProviderFactory providerFactory, MultivaluedMap<String, Object> headers)
24 {
25 super(interceptors, annotations, entity, genericType, mediaType, type, outputStream, providerFactory, headers);
26 }
27
28 }
+0
-60
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ClientExecutionContextImpl.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.client.ClientExecutor;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.spi.interception.ClientExecutionContext;
6 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
7
8 import java.util.List;
9
10 /**
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @version $Revision: 1 $
13 *
14 * @deprecated The Resteasy interceptor facility introduced in release 2.x
15 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
16 *
17 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
18 *
19 */
20 @Deprecated
21 public class ClientExecutionContextImpl implements ClientExecutionContext
22 {
23 protected List<ClientExecutionInterceptor> interceptors;
24 protected ClientExecutor executor;
25 protected ClientRequest request;
26 protected int index = 0;
27
28 public ClientExecutionContextImpl(List<ClientExecutionInterceptor> interceptors, ClientExecutor executor, ClientRequest request)
29 {
30 this.interceptors = interceptors;
31 this.executor = executor;
32 this.request = request;
33 }
34
35 public ClientRequest getRequest()
36 {
37 return request;
38 }
39
40 @SuppressWarnings("unchecked")
41 public ClientResponse proceed() throws Exception
42 {
43 if (index >= interceptors.size())
44 {
45 return executor.execute(request);
46 }
47 else
48 {
49 try
50 {
51 return interceptors.get(index++).execute(this);
52 }
53 finally
54 {
55 index--;
56 }
57 }
58 }
59 }
+0
-30
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ClientReaderInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import java.io.InputStream;
3 import java.lang.annotation.Annotation;
4 import java.lang.reflect.Type;
5 import java.util.Map;
6
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.ReaderInterceptor;
10
11 import org.jboss.resteasy.spi.ResteasyProviderFactory;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ClientReaderInterceptorContext instead.
17 */
18 @Deprecated
19 public class ClientReaderInterceptorContext extends org.jboss.resteasy.core.interception.jaxrs.ClientReaderInterceptorContext
20 {
21
22 public ClientReaderInterceptorContext(ReaderInterceptor[] interceptors, ResteasyProviderFactory providerFactory,
23 Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
24 MultivaluedMap<String, String> headers, InputStream inputStream, Map<String, Object> properties)
25 {
26 super(interceptors, providerFactory, type, genericType, annotations, mediaType, headers, inputStream, properties);
27 }
28
29 }
+0
-18
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ClientResponseFilterRegistry.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ClientResponseFilterRegistry instead.
8 */
9 @Deprecated
10 public class ClientResponseFilterRegistry extends org.jboss.resteasy.core.interception.jaxrs.ClientResponseFilterRegistry
11 {
12
13 public ClientResponseFilterRegistry(ResteasyProviderFactory providerFactory)
14 {
15 super(providerFactory);
16 }
17 }
+0
-31
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ClientWriterInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import java.io.OutputStream;
3 import java.lang.annotation.Annotation;
4 import java.lang.reflect.Type;
5 import java.util.Map;
6
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.WriterInterceptor;
10
11 import org.jboss.resteasy.spi.ResteasyProviderFactory;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ClientWriterInterceptorContext instead.
17 */
18 @Deprecated
19 public class ClientWriterInterceptorContext extends org.jboss.resteasy.core.interception.jaxrs.ClientWriterInterceptorContext
20 {
21
22 public ClientWriterInterceptorContext(WriterInterceptor[] interceptors, ResteasyProviderFactory providerFactory,
23 Object entity, Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
24 MultivaluedMap<String, Object> headers, OutputStream outputStream, Map<String, Object> properties)
25 {
26 super(interceptors, providerFactory, entity, type, genericType, annotations, mediaType, headers, outputStream,
27 properties);
28 }
29
30 }
+0
-180
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ContainerRequestFilterRegistry.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.core.ServerResponse;
3 import org.jboss.resteasy.core.interception.jaxrs.PostMatchContainerRequestContext;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
6 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
7
8 import javax.ws.rs.container.ContainerRequestContext;
9 import javax.ws.rs.container.ContainerRequestFilter;
10 import java.io.IOException;
11 import java.lang.reflect.AccessibleObject;
12 import java.lang.reflect.Method;
13
14 /**
15 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
16 * @version $Revision: 1 $
17 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ContainerRequestFilterRegistry instead.
18 */
19 @Deprecated
20 public class ContainerRequestFilterRegistry extends org.jboss.resteasy.core.interception.jaxrs.ContainerRequestFilterRegistry
21 {
22 protected LegacyPrecedence precedence;
23
24 public ContainerRequestFilterRegistry(ResteasyProviderFactory providerFactory, LegacyPrecedence precedence)
25 {
26 super(providerFactory);
27 this.precedence = precedence;
28 }
29
30 public ContainerRequestFilterRegistry clone(ResteasyProviderFactory factory)
31 {
32 ContainerRequestFilterRegistry clone = new ContainerRequestFilterRegistry(factory, precedence);
33 clone.interceptors.addAll(interceptors);
34 return clone;
35 }
36
37 private static class ContainerRequestFilterFacade implements ContainerRequestFilter
38 {
39 protected final PreProcessInterceptor interceptor;
40
41 private ContainerRequestFilterFacade(PreProcessInterceptor interceptor)
42 {
43 this.interceptor = interceptor;
44 }
45
46 @Override
47 public void filter(ContainerRequestContext requestContext) throws IOException
48 {
49 PostMatchContainerRequestContext ctx = (PostMatchContainerRequestContext)requestContext;
50 ServerResponse response = interceptor.preProcess(ctx.getHttpRequest(), ctx.getResourceMethod());
51 if (response != null)
52 {
53 requestContext.abortWith(response);
54 }
55 }
56 }
57
58 public abstract class AbstractLegacyInterceptorFactory extends AbstractInterceptorFactory
59 {
60 protected LegacyPrecedence precedence;
61
62 protected AbstractLegacyInterceptorFactory(Class declaring, LegacyPrecedence precedence)
63 {
64 super(declaring);
65 this.precedence = precedence;
66 }
67
68 @Override
69 protected void setPrecedence(Class<?> declaring)
70 {
71 order = precedence.calculateOrder(declaring);
72 }
73
74 @Override
75 public Match preMatch()
76 {
77 return null;
78 }
79
80 public Object getLegacyMatch(Class declaring, AccessibleObject target)
81 {
82 Object interceptor = getInterceptor();
83 if (interceptor instanceof AcceptedByMethod)
84 {
85 if (target == null || !(target instanceof Method)) return null;
86 Method method = (Method) target;
87 if (((AcceptedByMethod) interceptor).accept(declaring, method))
88 {
89 return interceptor;
90 } else
91 {
92 return null;
93 }
94 }
95 return interceptor;
96 }
97
98 }
99
100 protected class LegacySingletonInterceptorFactory extends AbstractLegacyInterceptorFactory
101 {
102 protected Object interceptor;
103
104 public LegacySingletonInterceptorFactory(Class declaring, Object interceptor, LegacyPrecedence precedence)
105 {
106 super(declaring, precedence);
107 this.interceptor = interceptor;
108 setPrecedence(declaring);
109 }
110
111 @Override
112 protected void initialize()
113 {
114 providerFactory.injectProperties(interceptor);
115 }
116
117 @Override
118 protected Object getInterceptor()
119 {
120 checkInitialize();
121 return interceptor;
122 }
123 }
124
125 protected class LegacyPerMethodInterceptorFactory extends AbstractLegacyInterceptorFactory
126 {
127
128 public LegacyPerMethodInterceptorFactory(Class declaring, LegacyPrecedence precedence)
129 {
130 super(declaring, precedence);
131 setPrecedence(declaring);
132 }
133
134 @Override
135 protected void initialize()
136 {
137 }
138
139 @Override
140 protected Object getInterceptor()
141 {
142 Object interceptor = createInterceptor();
143 providerFactory.injectProperties(interceptor);
144 return interceptor;
145 }
146 }
147
148 public void registerLegacy(Class<? extends PreProcessInterceptor> decl)
149 {
150 register(new LegacyPerMethodInterceptorFactory(decl, precedence)
151 {
152 @Override
153 public Match postMatch(Class declaring, AccessibleObject target)
154 {
155 Object obj = super.getLegacyMatch(declaring, target);
156 if (obj == null) return null;
157 PreProcessInterceptor interceptor = (PreProcessInterceptor)obj;
158 return new Match(new ContainerRequestFilterFacade(interceptor), order);
159 }
160
161 });
162 }
163
164 public void registerLegacy(PreProcessInterceptor interceptor)
165 {
166 register(new LegacySingletonInterceptorFactory(interceptor.getClass(), interceptor, precedence)
167 {
168 @Override
169 public Match postMatch(Class declaring, AccessibleObject target)
170 {
171 Object obj = super.getLegacyMatch(declaring, target);
172 if (obj == null) return null;
173 PreProcessInterceptor interceptor = (PreProcessInterceptor)obj;
174 return new Match(new ContainerRequestFilterFacade(interceptor), order);
175 }
176 });
177
178 }
179 }
+0
-21
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ContainerResponseContextImpl.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.specimpl.BuiltResponse;
3 import org.jboss.resteasy.spi.HttpRequest;
4 import org.jboss.resteasy.spi.HttpResponse;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl instead.
10 */
11 @Deprecated
12 public class ContainerResponseContextImpl extends org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl
13 {
14
15 public ContainerResponseContextImpl(HttpRequest request, HttpResponse httpResponse, BuiltResponse serverResponse)
16 {
17 super(request, httpResponse, serverResponse);
18 }
19
20 }
+0
-198
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ContainerResponseFilterRegistry.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.core.ServerResponse;
3 import org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl;
4 import org.jboss.resteasy.specimpl.BuiltResponse;
5 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
7 import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
8
9 import javax.ws.rs.container.ContainerRequestContext;
10 import javax.ws.rs.container.ContainerResponseContext;
11 import javax.ws.rs.container.ContainerResponseFilter;
12 import java.io.IOException;
13 import java.lang.reflect.AccessibleObject;
14 import java.lang.reflect.Method;
15
16 /**
17 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
18 * @version $Revision: 1 $
19 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ContainerResponseFilterRegistry instead.
20 */
21 @Deprecated
22 public class ContainerResponseFilterRegistry extends org.jboss.resteasy.core.interception.jaxrs.ContainerResponseFilterRegistry
23 {
24 protected LegacyPrecedence precedence;
25
26 public ContainerResponseFilterRegistry(ResteasyProviderFactory providerFactory)
27 {
28 this(providerFactory, new LegacyPrecedence());
29 }
30
31 public ContainerResponseFilterRegistry(ResteasyProviderFactory providerFactory, LegacyPrecedence precedence)
32 {
33 super(providerFactory);
34 this.precedence = precedence;
35 }
36
37 private static class ContainerResponseFilterFacade implements ContainerResponseFilter
38 {
39 protected final PostProcessInterceptor interceptor;
40
41 private ContainerResponseFilterFacade(PostProcessInterceptor interceptor)
42 {
43 this.interceptor = interceptor;
44 }
45
46 @Override
47 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException
48 {
49 ContainerResponseContextImpl ctx = (ContainerResponseContextImpl)responseContext;
50 BuiltResponse jaxrsResposne = ctx.getJaxrsResponse();
51 ServerResponse serverResponse = new ServerResponse(jaxrsResposne);
52 try
53 {
54 interceptor.postProcess(serverResponse);
55 }
56 finally
57 {
58 jaxrsResposne.setStatus(serverResponse.getStatus());
59 jaxrsResposne.setAnnotations(serverResponse.getAnnotations());
60 jaxrsResposne.setEntity(serverResponse.getEntity());
61 jaxrsResposne.setMetadata(serverResponse.getMetadata());
62 jaxrsResposne.setEntityClass(serverResponse.getEntityClass());
63 jaxrsResposne.setGenericType(serverResponse.getGenericType());
64 }
65
66 }
67 }
68
69 public ContainerResponseFilterRegistry clone(ResteasyProviderFactory factory)
70 {
71 ContainerResponseFilterRegistry clone = new ContainerResponseFilterRegistry(factory, precedence);
72 clone.interceptors.addAll(interceptors);
73 return clone;
74 }
75
76 public abstract class AbstractLegacyInterceptorFactory extends AbstractInterceptorFactory
77 {
78 protected LegacyPrecedence precedence;
79
80 protected AbstractLegacyInterceptorFactory(Class declaring, LegacyPrecedence precedence)
81 {
82 super(declaring);
83 this.precedence = precedence;
84 }
85
86 @Override
87 protected void setPrecedence(Class<?> declaring)
88 {
89 order = precedence.calculateOrder(declaring);
90 }
91
92 @Override
93 public Match preMatch()
94 {
95 return null;
96 }
97
98 public Object getLegacyMatch(Class declaring, AccessibleObject target)
99 {
100 Object interceptor = getInterceptor();
101 if (interceptor instanceof AcceptedByMethod)
102 {
103 if (target == null || !(target instanceof Method)) return null;
104 Method method = (Method) target;
105 if (((AcceptedByMethod) interceptor).accept(declaring, method))
106 {
107 return interceptor;
108 } else
109 {
110 return null;
111 }
112 }
113 return interceptor;
114 }
115
116 }
117
118 protected class LegacySingletonInterceptorFactory extends AbstractLegacyInterceptorFactory
119 {
120 protected Object interceptor;
121
122 public LegacySingletonInterceptorFactory(Class declaring, Object interceptor, LegacyPrecedence precedence)
123 {
124 super(declaring, precedence);
125 this.interceptor = interceptor;
126 setPrecedence(declaring);
127 }
128
129 @Override
130 protected void initialize()
131 {
132 providerFactory.injectProperties(interceptor);
133 }
134
135 @Override
136 protected Object getInterceptor()
137 {
138 checkInitialize();
139 return interceptor;
140 }
141 }
142
143 protected class LegacyPerMethodInterceptorFactory extends AbstractLegacyInterceptorFactory
144 {
145
146 public LegacyPerMethodInterceptorFactory(Class declaring, LegacyPrecedence precedence)
147 {
148 super(declaring, precedence);
149 setPrecedence(declaring);
150 }
151
152 @Override
153 protected void initialize()
154 {
155 }
156
157 @Override
158 protected Object getInterceptor()
159 {
160 Object interceptor = createInterceptor();
161 providerFactory.injectProperties(interceptor);
162 return interceptor;
163 }
164 }
165
166 public void registerLegacy(Class<? extends PostProcessInterceptor> decl)
167 {
168 register(new LegacyPerMethodInterceptorFactory(decl, precedence)
169 {
170 @Override
171 public Match postMatch(Class declaring, AccessibleObject target)
172 {
173 Object obj = getLegacyMatch(declaring, target);
174 if (obj == null) return null;
175 PostProcessInterceptor interceptor = (PostProcessInterceptor)obj;
176 return new Match(new ContainerResponseFilterFacade(interceptor), order);
177 }
178
179 });
180 }
181
182 public void registerLegacy(PostProcessInterceptor interceptor)
183 {
184 register(new LegacySingletonInterceptorFactory(interceptor.getClass(), interceptor, precedence)
185 {
186 @Override
187 public Match postMatch(Class declaring, AccessibleObject target)
188 {
189 Object obj = getLegacyMatch(declaring, target);
190 if (obj == null) return null;
191 PostProcessInterceptor interceptor = (PostProcessInterceptor)obj;
192 return new Match(new ContainerResponseFilterFacade(interceptor), order);
193 }
194 });
195
196 }
197 }
+0
-16
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/DecoratorMatcher.java less more
0 package org.jboss.resteasy.core.interception;
1
2 /**
3 * Finds DecoratorProcessors and calls decorates on them by introspecting annotations.
4 *
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 * @see org.jboss.resteasy.spi.DecoratorProcessor
8 * @see org.jboss.resteasy.annotations.DecorateTypes
9 * @see org.jboss.resteasy.annotations.Decorator
10 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.DecoratorMatcher instead.
11 */
12 @Deprecated
13 public class DecoratorMatcher extends org.jboss.resteasy.core.interception.jaxrs.DecoratorMatcher
14 {
15 }
+0
-278
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/InterceptorRegistry.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
4 import org.jboss.resteasy.spi.ConstructorInjector;
5 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
7
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.AccessibleObject;
10 import java.lang.reflect.Array;
11 import java.lang.reflect.Method;
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.Comparator;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18
19 /**
20 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
21 * @version $Revision: 1 $
22 *
23 * @deprecated The Resteasy interceptor facility introduced in release 2.x
24 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
25 *
26 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
27 */
28 @Deprecated
29 @SuppressWarnings("unchecked")
30 public class InterceptorRegistry<T>
31 {
32 protected static interface InterceptorFactory
33 {
34 Object preMatch();
35 Object postMatch(Class declaring, AccessibleObject target);
36 int getOrder();
37 }
38
39 protected abstract class AbstractInterceptorFactory implements InterceptorFactory
40 {
41
42 protected String precedence = "DEFAULT";
43 protected int order = 100000;
44
45 protected void setPrecedence(Class<?> clazz)
46 {
47 Precedence precedence = clazz.getAnnotation(Precedence.class);
48 if (precedence != null)
49 {
50 this.precedence = precedence.value();
51 Integer o = precedenceOrder.get(this.precedence);
52 if (o == null) throw new RuntimeException(Messages.MESSAGES.unknownInterceptorPrecedence(this.precedence));
53 this.order = o;
54 }
55 else
56 {
57 for (Annotation annotation : clazz.getAnnotations())
58 {
59 precedence = annotation.annotationType().getAnnotation(Precedence.class);
60 if (precedence != null)
61 {
62 this.precedence = precedence.value();
63 Integer o = precedenceOrder.get(this.precedence);
64 if (o == null) throw new RuntimeException(Messages.MESSAGES.unknownInterceptorPrecedence(this.precedence));
65 this.order = o;
66 break;
67 }
68 }
69 }
70 }
71
72 public String getPrecedence()
73 {
74 return precedence;
75 }
76
77 public int getOrder()
78 {
79 return order;
80 }
81
82 protected Object binding(Class declaring, AccessibleObject target, Object inter)
83 {
84 if (inter instanceof AcceptedByMethod)
85 {
86 if (target == null || !(target instanceof Method)) return null;
87 Method method = (Method)target;
88 if (((AcceptedByMethod)inter).accept(declaring, method))
89 {
90 return inter;
91 }
92 else
93 {
94 return null;
95 }
96 }
97 return inter;
98 }
99 }
100
101
102 protected class SingletonInterceptorFactory extends AbstractInterceptorFactory
103 {
104 private Object interceptor;
105
106 public SingletonInterceptorFactory(Object interceptor)
107 {
108 this.interceptor = interceptor;
109 setPrecedence(interceptor.getClass());
110 }
111
112 @Override
113 public Object preMatch()
114 {
115 return null;
116 }
117
118 @Override
119 public Object postMatch(Class declaring, AccessibleObject target)
120 {
121 final Object inter = interceptor;
122 return binding(declaring, target, inter);
123 }
124
125 }
126
127 protected class PerMethodInterceptorFactory extends AbstractInterceptorFactory
128 {
129 private ConstructorInjector constructorInjector;
130
131 public PerMethodInterceptorFactory(Class clazz)
132 {
133 constructorInjector = providerFactory.createConstructorInjector(clazz);
134 setPrecedence(clazz);
135 }
136
137 @Override
138 public Object preMatch()
139 {
140 return null;
141 }
142
143 @Override
144 public Object postMatch(Class declaring, AccessibleObject target)
145 {
146 final Object inter = constructorInjector.construct();
147 return binding(declaring, target, inter);
148 }
149 }
150
151 protected ResteasyProviderFactory providerFactory;
152 protected Class<T> intf;
153 protected List<InterceptorFactory> interceptors = new ArrayList<InterceptorFactory>();
154 protected Map<String, Integer> precedenceOrder = new HashMap<String, Integer>();
155 protected List<String> precedenceList = new ArrayList<String>();
156 protected List<InterceptorRegistryListener> listeners = new ArrayList<InterceptorRegistryListener>();
157
158 public InterceptorRegistry<T> cloneTo(ResteasyProviderFactory factory)
159 {
160 InterceptorRegistry<T> clone = new InterceptorRegistry<T>(intf, factory);
161 clone.interceptors.addAll(interceptors);
162 clone.precedenceOrder.putAll(precedenceOrder);
163 precedenceList.addAll(precedenceList);
164 return clone;
165 }
166
167 public class PrecedenceComparator implements Comparator<InterceptorFactory>
168 {
169 public int compare(InterceptorFactory factory, InterceptorFactory factory2)
170 {
171 return factory.getOrder() - factory2.getOrder();
172 }
173 }
174
175 public List<InterceptorRegistryListener> getListeners()
176 {
177 return listeners;
178 }
179
180 public Class<T> getIntf()
181 {
182 return intf;
183 }
184
185 public InterceptorRegistry(Class<T> intf, ResteasyProviderFactory providerFactory)
186 {
187 this.providerFactory = providerFactory;
188 this.intf = intf;
189 precedenceOrder.put("DEFAULT", 100000);
190 }
191
192 protected void recalculateOrder()
193 {
194 precedenceOrder.clear();
195 for (int i = 0; i < precedenceList.size(); i++)
196 {
197 precedenceOrder.put(precedenceList.get(i), i);
198 }
199 precedenceOrder.put("DEFAULT", 100000);
200 }
201
202 public void appendPrecedence(String precedence)
203 {
204 precedenceList.add(precedence);
205 recalculateOrder();
206 }
207
208 public void insertPrecedenceAfter(String after, String newPrecedence)
209 {
210 for (int i = 0; i < precedenceList.size(); i++)
211 {
212 if (precedenceList.get(i).equals(after))
213 {
214 precedenceList.add(i + 1, newPrecedence);
215 break;
216 }
217 }
218 recalculateOrder();
219 }
220
221 public void insertPrecedenceBefore(String after, String newPrecedence)
222 {
223 for (int i = 0; i < precedenceList.size(); i++)
224 {
225 if (precedenceList.get(i).equals(after))
226 {
227 precedenceList.add(i, newPrecedence);
228 break;
229 }
230 }
231 recalculateOrder();
232 }
233
234 public T[] bind(Class declaring, AccessibleObject target)
235 {
236 List<T> list = bindForList(declaring, target);
237 return list.toArray((T[]) Array.newInstance(intf, list.size()));
238 }
239
240 public List<T> bindForList(Class declaring, AccessibleObject target)
241 {
242 List<T> list = new ArrayList<T>();
243 for (InterceptorFactory factory : interceptors)
244 {
245 Object interceptor = factory.postMatch(declaring, target);
246 if (interceptor != null) addNewInterceptor(list, interceptor);
247 }
248 return list;
249 }
250
251 protected void addNewInterceptor(List<T> list, Object interceptor)
252 {
253 providerFactory.injectProperties(interceptor);
254 list.add((T) interceptor);
255 }
256
257 public void register(Class<? extends T> clazz)
258 {
259 interceptors.add(new PerMethodInterceptorFactory(clazz));
260 Collections.sort(interceptors, new PrecedenceComparator());
261 for (InterceptorRegistryListener listener : listeners)
262 {
263 listener.registryUpdated(this);
264 }
265 }
266
267 public void register(T interceptor)
268 {
269 interceptors.add(new SingletonInterceptorFactory(interceptor));
270 Collections.sort(interceptors, new PrecedenceComparator());
271 for (InterceptorRegistryListener listener : listeners)
272 {
273 listener.registryUpdated(this);
274 }
275 }
276
277 }
+0
-19
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/InterceptorRegistryListener.java less more
0 package org.jboss.resteasy.core.interception;
1
2 /**
3 * Callback interface for when an interceptor registry changes
4 *
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 *
8 * @deprecated The Resteasy interceptor facility introduced in release 2.x
9 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
10 *
11 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
12 */
13 @Deprecated
14 public interface InterceptorRegistryListener
15 {
16 void registryUpdated(InterceptorRegistry registry);
17
18 }
+0
-120
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/JaxrsInterceptorRegistry.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import java.lang.reflect.AccessibleObject;
3 import java.lang.reflect.Method;
4
5 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
7
8 /**
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @version $Revision: 1 $
11 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistry<T> instead.
12 */
13 @SuppressWarnings("unchecked")
14 @Deprecated
15 public class JaxrsInterceptorRegistry<T> extends org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistry<T>
16 {
17 public JaxrsInterceptorRegistry(ResteasyProviderFactory providerFactory, Class<T> intf)
18 {
19 super(providerFactory, intf);
20 }
21
22 public JaxrsInterceptorRegistry<T> clone(ResteasyProviderFactory factory)
23 {
24 JaxrsInterceptorRegistry<T> clone = new JaxrsInterceptorRegistry(factory, intf);
25 clone.interceptors.addAll(interceptors);
26 return clone;
27 }
28
29 public abstract class AbstractLegacyInterceptorFactory extends AbstractInterceptorFactory
30 {
31 protected LegacyPrecedence precedence;
32
33 protected AbstractLegacyInterceptorFactory(Class declaring, LegacyPrecedence precedence)
34 {
35 super(declaring);
36 this.precedence = precedence;
37 }
38
39 @Override
40 protected void setPrecedence(Class<?> declaring)
41 {
42 order = precedence.calculateOrder(declaring);
43 }
44
45 @Override
46 public Match preMatch()
47 {
48 return null;
49 }
50
51 public Object getLegacyMatch(Class declaring, AccessibleObject target)
52 {
53 Object interceptor = getInterceptor();
54 if (interceptor instanceof AcceptedByMethod)
55 {
56 if (target == null || !(target instanceof Method)) return null;
57 Method method = (Method) target;
58 if (((AcceptedByMethod) interceptor).accept(declaring, method))
59 {
60 return interceptor;
61 } else
62 {
63 return null;
64 }
65 }
66 return interceptor;
67 }
68
69 }
70
71 protected class LegacySingletonInterceptorFactory extends AbstractLegacyInterceptorFactory
72 {
73 protected Object interceptor;
74
75 public LegacySingletonInterceptorFactory(Class declaring, Object interceptor, LegacyPrecedence precedence)
76 {
77 super(declaring, precedence);
78 this.interceptor = interceptor;
79 setPrecedence(declaring);
80 }
81
82 @Override
83 protected void initialize()
84 {
85 providerFactory.injectProperties(interceptor);
86 }
87
88 @Override
89 protected Object getInterceptor()
90 {
91 checkInitialize();
92 return interceptor;
93 }
94 }
95
96 protected class LegacyPerMethodInterceptorFactory extends AbstractLegacyInterceptorFactory
97 {
98
99 public LegacyPerMethodInterceptorFactory(Class declaring, LegacyPrecedence precedence)
100 {
101 super(declaring, precedence);
102 setPrecedence(declaring);
103 }
104
105 @Override
106 protected void initialize()
107 {
108 }
109
110 @Override
111 protected Object getInterceptor()
112 {
113 Object interceptor = createInterceptor();
114 providerFactory.injectProperties(interceptor);
115 return interceptor;
116 }
117 }
118
119 }
+0
-13
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/JaxrsInterceptorRegistryListener.java less more
0 package org.jboss.resteasy.core.interception;
1
2 /**
3 * Callback interface for when an interceptor registry changes
4 *
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistryListener instead.
8 */
9 @Deprecated
10 public interface JaxrsInterceptorRegistryListener extends org.jboss.resteasy.core.interception.jaxrs.JaxrsInterceptorRegistryListener
11 {
12 }
+0
-98
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/LegacyPrecedence.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
4
5 import javax.ws.rs.Priorities;
6
7 import java.lang.annotation.Annotation;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.List;
11 import java.util.Map;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 */
17 @Deprecated
18 public class LegacyPrecedence
19 {
20 private static final int DEFAULTS_ORDER = 100000;
21 protected Map<String, Integer> precedenceOrder = new HashMap<String, Integer>();
22 protected List<String> precedenceList = new ArrayList<String>();
23
24 public LegacyPrecedence clone()
25 {
26 LegacyPrecedence precedence = new LegacyPrecedence();
27 precedence.precedenceList.addAll(precedenceList);
28 precedence.precedenceOrder.putAll(precedenceOrder);
29 return precedence;
30 }
31
32 public int calculateOrder(Class<?> clazz)
33 {
34 Precedence precedence = (Precedence)clazz.getAnnotation(Precedence.class);
35 if (precedence != null)
36 {
37 String value = precedence.value();
38 Integer o = precedenceOrder.get(value);
39 if (o == null) throw new RuntimeException(Messages.MESSAGES.unknownInterceptorPrecedence(value));
40 return o;
41 }
42 else
43 {
44 for (Annotation annotation : clazz.getAnnotations())
45 {
46 precedence = annotation.annotationType().getAnnotation(Precedence.class);
47 if (precedence != null)
48 {
49 String value = precedence.value();
50 Integer o = precedenceOrder.get(value);
51 if (o == null) throw new RuntimeException(Messages.MESSAGES.unknownInterceptorPrecedence(value));
52 return o;
53 }
54 }
55 }
56 return Priorities.USER;
57 }
58
59 public void addPrecedence(String precedent, int order)
60 {
61 precedenceList.add(precedent);
62 precedenceOrder.put(precedent, order);
63 }
64
65 public void appendPrecedence(String precedence)
66 {
67 precedenceList.add(precedence);
68
69 int greatest = 0;
70 for (Integer i : precedenceOrder.values())
71 {
72 if (i > greatest && ((int)i) != DEFAULTS_ORDER) greatest = i;
73 }
74
75 addPrecedence(precedence, greatest + 100);
76 }
77
78 public void insertPrecedenceAfter(String after, String newPrecedence)
79 {
80 int order = precedenceOrder.get(after);
81 order++;
82 addPrecedence(newPrecedence, order);
83 }
84
85 public void insertPrecedenceBefore(String after, String newPrecedence)
86 {
87 int order = precedenceOrder.get(after);
88 order--;
89 addPrecedence(newPrecedence, order);
90 }
91
92 public LegacyPrecedence()
93 {
94 precedenceOrder.put("DEFAULT", DEFAULTS_ORDER);
95 }
96
97 }
+0
-19
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/PostMatchContainerRequestContext.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.core.ResourceMethodInvoker;
3 import org.jboss.resteasy.spi.HttpRequest;
4
5 /**
6 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7 * @version $Revision: 1 $
8 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.PostMatchContainerRequestContext instead.
9 */
10 @Deprecated
11 public class PostMatchContainerRequestContext extends org.jboss.resteasy.core.interception.jaxrs.PostMatchContainerRequestContext
12 {
13
14 public PostMatchContainerRequestContext(HttpRequest request, ResourceMethodInvoker resourceMethod)
15 {
16 super(request, resourceMethod);
17 }
18 }
+0
-18
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/PreMatchContainerRequestContext.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.spi.HttpRequest;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext instead.
8 */
9 @Deprecated
10 public class PreMatchContainerRequestContext extends org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext
11 {
12
13 public PreMatchContainerRequestContext(HttpRequest request)
14 {
15 super(request);
16 }
17 }
+0
-287
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ReaderInterceptorRegistry.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
4 import org.jboss.resteasy.spi.interception.MessageBodyReaderContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyReaderInterceptor;
6
7 import javax.ws.rs.WebApplicationException;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.MultivaluedMap;
10 import javax.ws.rs.ext.ReaderInterceptor;
11 import javax.ws.rs.ext.ReaderInterceptorContext;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.AccessibleObject;
16 import java.lang.reflect.Method;
17 import java.lang.reflect.Type;
18
19 /**
20 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
21 * @version $Revision: 1 $
22 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ReaderInterceptorRegistry instead.
23 */
24 @Deprecated
25 public class ReaderInterceptorRegistry extends org.jboss.resteasy.core.interception.jaxrs.ReaderInterceptorRegistry
26 {
27 protected LegacyPrecedence precedence;
28
29 public ReaderInterceptorRegistry(ResteasyProviderFactory providerFactory, LegacyPrecedence precedence)
30 {
31 super(providerFactory);
32 this.precedence = precedence;
33 }
34
35 public ReaderInterceptorRegistry clone(ResteasyProviderFactory factory)
36 {
37 ReaderInterceptorRegistry clone = new ReaderInterceptorRegistry(factory, precedence);
38 clone.interceptors.addAll(interceptors);
39 return clone;
40 }
41
42 private static class MessageBodyReaderContextFacade implements MessageBodyReaderContext
43 {
44 protected final ReaderInterceptorContext readerInterceptorContext;
45
46 private MessageBodyReaderContextFacade(ReaderInterceptorContext readerInterceptorContext)
47 {
48 this.readerInterceptorContext = readerInterceptorContext;
49 }
50
51 @Override
52 public Class getType()
53 {
54 return readerInterceptorContext.getType();
55 }
56
57 @Override
58 public void setType(Class type)
59 {
60 readerInterceptorContext.setType(type);
61 }
62
63 @Override
64 public Type getGenericType()
65 {
66 return readerInterceptorContext.getGenericType();
67 }
68
69 @Override
70 public void setGenericType(Type genericType)
71 {
72 readerInterceptorContext.setGenericType(genericType);
73 }
74
75 @Override
76 public Annotation[] getAnnotations()
77 {
78 return readerInterceptorContext.getAnnotations();
79 }
80
81 @Override
82 public void setAnnotations(Annotation[] annotations)
83 {
84 readerInterceptorContext.setAnnotations(annotations);
85 }
86
87 @Override
88 public MediaType getMediaType()
89 {
90 return readerInterceptorContext.getMediaType();
91 }
92
93 @Override
94 public void setMediaType(MediaType mediaType)
95 {
96 readerInterceptorContext.setMediaType(mediaType);
97 }
98
99 @Override
100 public MultivaluedMap<String, String> getHeaders()
101 {
102 return readerInterceptorContext.getHeaders();
103 }
104
105 @Override
106 public InputStream getInputStream()
107 {
108 return readerInterceptorContext.getInputStream();
109 }
110
111 @Override
112 public void setInputStream(InputStream is)
113 {
114 readerInterceptorContext.setInputStream(is);
115 }
116
117 @Override
118 public Object getAttribute(String attribute)
119 {
120 return readerInterceptorContext.getProperty(attribute);
121 }
122
123 @Override
124 public void setAttribute(String name, Object value)
125 {
126 readerInterceptorContext.setProperty(name, value);
127 }
128
129 @Override
130 public void removeAttribute(String name)
131 {
132 readerInterceptorContext.removeProperty(name);
133 }
134
135 @Override
136 public Object proceed() throws IOException, WebApplicationException
137 {
138 return readerInterceptorContext.proceed();
139 }
140 }
141
142 public static class ReaderInterceptorFacade implements ReaderInterceptor
143 {
144 protected final MessageBodyReaderInterceptor interceptor;
145
146 public ReaderInterceptorFacade(MessageBodyReaderInterceptor interceptor)
147 {
148 this.interceptor = interceptor;
149 }
150
151 public MessageBodyReaderInterceptor getInterceptor()
152 {
153 return interceptor;
154 }
155
156 @Override
157 public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException
158 {
159 MessageBodyReaderContextFacade facade = new MessageBodyReaderContextFacade(readerInterceptorContext);
160 return interceptor.read(facade);
161 }
162 }
163
164 public abstract class AbstractLegacyInterceptorFactory extends AbstractInterceptorFactory
165 {
166 protected LegacyPrecedence precedence;
167
168 protected AbstractLegacyInterceptorFactory(Class declaring, LegacyPrecedence precedence)
169 {
170 super(declaring);
171 this.precedence = precedence;
172 }
173
174 @Override
175 protected void setPrecedence(Class<?> declaring)
176 {
177 order = precedence.calculateOrder(declaring);
178 }
179
180 @Override
181 public Match preMatch()
182 {
183 return null;
184 }
185
186 public Object getLegacyMatch(Class declaring, AccessibleObject target)
187 {
188 Object interceptor = getInterceptor();
189 if (interceptor instanceof AcceptedByMethod)
190 {
191 if (target == null || !(target instanceof Method)) return null;
192 Method method = (Method) target;
193 if (((AcceptedByMethod) interceptor).accept(declaring, method))
194 {
195 return interceptor;
196 } else
197 {
198 return null;
199 }
200 }
201 return interceptor;
202 }
203
204 }
205
206 protected class LegacySingletonInterceptorFactory extends AbstractLegacyInterceptorFactory
207 {
208 protected Object interceptor;
209
210 public LegacySingletonInterceptorFactory(Class declaring, Object interceptor, LegacyPrecedence precedence)
211 {
212 super(declaring, precedence);
213 this.interceptor = interceptor;
214 setPrecedence(declaring);
215 }
216
217 @Override
218 protected void initialize()
219 {
220 providerFactory.injectProperties(interceptor);
221 }
222
223 @Override
224 protected Object getInterceptor()
225 {
226 checkInitialize();
227 return interceptor;
228 }
229 }
230
231 protected class LegacyPerMethodInterceptorFactory extends AbstractLegacyInterceptorFactory
232 {
233
234 public LegacyPerMethodInterceptorFactory(Class declaring, LegacyPrecedence precedence)
235 {
236 super(declaring, precedence);
237 setPrecedence(declaring);
238 }
239
240 @Override
241 protected void initialize()
242 {
243 }
244
245 @Override
246 protected Object getInterceptor()
247 {
248 Object interceptor = createInterceptor();
249 providerFactory.injectProperties(interceptor);
250 return interceptor;
251 }
252 }
253
254
255 public void registerLegacy(Class<? extends MessageBodyReaderInterceptor> decl)
256 {
257 register(new LegacyPerMethodInterceptorFactory(decl, precedence)
258 {
259 @Override
260 public Match postMatch(Class declaring, AccessibleObject target)
261 {
262 Object obj = getLegacyMatch(declaring, target);
263 if (obj == null) return null;
264 MessageBodyReaderInterceptor interceptor = (MessageBodyReaderInterceptor)obj;
265 return new Match(new ReaderInterceptorFacade(interceptor), order);
266 }
267
268 });
269 }
270
271 public void registerLegacy(MessageBodyReaderInterceptor interceptor)
272 {
273 register(new LegacySingletonInterceptorFactory(interceptor.getClass(), interceptor, precedence)
274 {
275 @Override
276 public Match postMatch(Class declaring, AccessibleObject target)
277 {
278 Object obj = getLegacyMatch(declaring, target);
279 if (obj == null) return null;
280 MessageBodyReaderInterceptor interceptor = (MessageBodyReaderInterceptor)obj;
281 return new Match(new ReaderInterceptorFacade(interceptor), order);
282 }
283 });
284
285 }
286 }
+0
-18
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ResponseContainerRequestContext.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.spi.HttpRequest;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ResponseContainerRequestContext instead
8 */
9 @Deprecated
10 public class ResponseContainerRequestContext extends org.jboss.resteasy.core.interception.jaxrs.ResponseContainerRequestContext
11 {
12
13 public ResponseContainerRequestContext(HttpRequest request)
14 {
15 super(request);
16 }
17 }
+0
-30
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ServerReaderInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import java.io.InputStream;
3 import java.lang.annotation.Annotation;
4 import java.lang.reflect.Type;
5
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.ReaderInterceptor;
9
10 import org.jboss.resteasy.spi.HttpRequest;
11 import org.jboss.resteasy.spi.ResteasyProviderFactory;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ServerReaderInterceptorContext instead.
17 */
18 @Deprecated
19 public class ServerReaderInterceptorContext extends org.jboss.resteasy.core.interception.jaxrs.ServerReaderInterceptorContext
20 {
21
22 public ServerReaderInterceptorContext(ReaderInterceptor[] interceptors, ResteasyProviderFactory providerFactory,
23 Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
24 MultivaluedMap<String, String> headers, InputStream inputStream, HttpRequest request)
25 {
26 super(interceptors, providerFactory, type, genericType, annotations, mediaType, headers, inputStream, request);
27 }
28
29 }
+0
-30
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/ServerWriterInterceptorContext.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import java.io.OutputStream;
3 import java.lang.annotation.Annotation;
4 import java.lang.reflect.Type;
5
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.WriterInterceptor;
9
10 import org.jboss.resteasy.spi.HttpRequest;
11 import org.jboss.resteasy.spi.ResteasyProviderFactory;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.ServerWriterInterceptorContext instead.
17 */
18 @Deprecated
19 public class ServerWriterInterceptorContext extends org.jboss.resteasy.core.interception.jaxrs.ServerWriterInterceptorContext
20 {
21
22 public ServerWriterInterceptorContext(WriterInterceptor[] interceptors, ResteasyProviderFactory providerFactory,
23 Object entity, Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
24 MultivaluedMap<String, Object> headers, OutputStream outputStream, HttpRequest request)
25 {
26 super(interceptors, providerFactory, entity, type, genericType, annotations, mediaType, headers, outputStream, request);
27 }
28
29 }
+0
-298
resteasy-legacy/src/main/java/org/jboss/resteasy/core/interception/WriterInterceptorRegistry.java less more
0 package org.jboss.resteasy.core.interception;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
6
7 import javax.ws.rs.WebApplicationException;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.MultivaluedMap;
10 import javax.ws.rs.ext.WriterInterceptor;
11 import javax.ws.rs.ext.WriterInterceptorContext;
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.AccessibleObject;
16 import java.lang.reflect.Method;
17 import java.lang.reflect.Type;
18
19 /**
20 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
21 * @version $Revision: 1 $
22 * @deprecated Use org.jboss.resteasy.core.interception.jaxrs.WriterInterceptorRegistry instead.
23 */
24 @Deprecated
25 public class WriterInterceptorRegistry extends org.jboss.resteasy.core.interception.jaxrs.WriterInterceptorRegistry
26 {
27 protected LegacyPrecedence precedence;
28
29 public WriterInterceptorRegistry(ResteasyProviderFactory providerFactory, LegacyPrecedence precedence)
30 {
31 super(providerFactory);
32 this.precedence = precedence;
33 }
34
35 public WriterInterceptorRegistry clone(ResteasyProviderFactory factory)
36 {
37 WriterInterceptorRegistry clone = new WriterInterceptorRegistry(factory, precedence);
38 clone.interceptors.addAll(interceptors);
39 return clone;
40 }
41
42 private static class MessageBodyWriterContextFacade implements MessageBodyWriterContext
43 {
44 protected final WriterInterceptorContext writerInterceptorContext;
45
46 private MessageBodyWriterContextFacade(WriterInterceptorContext writerInterceptorContext)
47 {
48 this.writerInterceptorContext = writerInterceptorContext;
49 }
50
51 @Override
52 public Class getType()
53 {
54 return writerInterceptorContext.getType();
55 }
56
57 @Override
58 public void setType(Class type)
59 {
60 writerInterceptorContext.setType(type);
61 }
62
63 @Override
64 public Type getGenericType()
65 {
66 return writerInterceptorContext.getGenericType();
67 }
68
69 @Override
70 public void setGenericType(Type genericType)
71 {
72 writerInterceptorContext.setGenericType(genericType);
73 }
74
75 @Override
76 public Annotation[] getAnnotations()
77 {
78 return writerInterceptorContext.getAnnotations();
79 }
80
81 @Override
82 public void setAnnotations(Annotation[] annotations)
83 {
84 writerInterceptorContext.setAnnotations(annotations);
85 }
86
87 @Override
88 public MediaType getMediaType()
89 {
90 return writerInterceptorContext.getMediaType();
91 }
92
93 @Override
94 public void setMediaType(MediaType mediaType)
95 {
96 writerInterceptorContext.setMediaType(mediaType);
97 }
98
99 @Override
100 public MultivaluedMap<String, Object> getHeaders()
101 {
102 return writerInterceptorContext.getHeaders();
103 }
104
105 @Override
106 public Object getAttribute(String attribute)
107 {
108 return writerInterceptorContext.getProperty(attribute);
109 }
110
111 @Override
112 public void setAttribute(String name, Object value)
113 {
114 writerInterceptorContext.setProperty(name, value);
115 }
116
117 @Override
118 public void removeAttribute(String name)
119 {
120 writerInterceptorContext.removeProperty(name);
121 }
122
123 @Override
124 public Object getEntity()
125 {
126 return writerInterceptorContext.getEntity();
127 }
128
129 @Override
130 public void setEntity(Object entity)
131 {
132 writerInterceptorContext.setEntity(entity);
133 }
134
135 @Override
136 public OutputStream getOutputStream()
137 {
138 return writerInterceptorContext.getOutputStream();
139 }
140
141 @Override
142 public void setOutputStream(OutputStream os)
143 {
144 writerInterceptorContext.setOutputStream(os);
145 }
146
147 @Override
148 public void proceed() throws IOException, WebApplicationException
149 {
150 writerInterceptorContext.proceed();
151 }
152 }
153
154 public static class WriterInterceptorFacade implements WriterInterceptor
155 {
156 protected final MessageBodyWriterInterceptor interceptor;
157
158 public WriterInterceptorFacade(MessageBodyWriterInterceptor interceptor)
159 {
160 this.interceptor = interceptor;
161 }
162
163 public MessageBodyWriterInterceptor getInterceptor()
164 {
165 return interceptor;
166 }
167
168 @Override
169 public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException
170 {
171 MessageBodyWriterContextFacade facade = new MessageBodyWriterContextFacade(writerInterceptorContext);
172 interceptor.write(facade);
173 }
174 }
175
176 public abstract class AbstractLegacyInterceptorFactory extends AbstractInterceptorFactory
177 {
178 protected LegacyPrecedence precedence;
179
180 protected AbstractLegacyInterceptorFactory(Class declaring, LegacyPrecedence precedence)
181 {
182 super(declaring);
183 this.precedence = precedence;
184 }
185
186 @Override
187 protected void setPrecedence(Class<?> declaring)
188 {
189 order = precedence.calculateOrder(declaring);
190 }
191
192 @Override
193 public Match preMatch()
194 {
195 return null;
196 }
197
198 public Object getLegacyMatch(Class declaring, AccessibleObject target)
199 {
200 Object interceptor = getInterceptor();
201 if (interceptor instanceof AcceptedByMethod)
202 {
203 if (target == null || !(target instanceof Method)) return null;
204 Method method = (Method) target;
205 if (((AcceptedByMethod) interceptor).accept(declaring, method))
206 {
207 return interceptor;
208 } else
209 {
210 return null;
211 }
212 }
213 return interceptor;
214 }
215
216 }
217
218 protected class LegacySingletonInterceptorFactory extends AbstractLegacyInterceptorFactory
219 {
220 protected Object interceptor;
221
222 public LegacySingletonInterceptorFactory(Class declaring, Object interceptor, LegacyPrecedence precedence)
223 {
224 super(declaring, precedence);
225 this.interceptor = interceptor;
226 setPrecedence(declaring);
227 }
228
229 @Override
230 protected void initialize()
231 {
232 providerFactory.injectProperties(interceptor);
233 }
234
235 @Override
236 protected Object getInterceptor()
237 {
238 checkInitialize();
239 return interceptor;
240 }
241 }
242
243 protected class LegacyPerMethodInterceptorFactory extends AbstractLegacyInterceptorFactory
244 {
245
246 public LegacyPerMethodInterceptorFactory(Class declaring, LegacyPrecedence precedence)
247 {
248 super(declaring, precedence);
249 setPrecedence(declaring);
250 }
251
252 @Override
253 protected void initialize()
254 {
255 }
256
257 @Override
258 protected Object getInterceptor()
259 {
260 Object interceptor = createInterceptor();
261 providerFactory.injectProperties(interceptor);
262 return interceptor;
263 }
264 }
265
266 public void registerLegacy(Class<? extends MessageBodyWriterInterceptor> decl)
267 {
268 register(new LegacyPerMethodInterceptorFactory(decl, precedence)
269 {
270 @Override
271 public Match postMatch(Class declaring, AccessibleObject target)
272 {
273 Object obj = getLegacyMatch(declaring, target);
274 if (obj == null) return null;
275 MessageBodyWriterInterceptor interceptor = (MessageBodyWriterInterceptor)obj;
276 return new Match(new WriterInterceptorFacade(interceptor), order);
277 }
278
279 });
280 }
281
282 public void registerLegacy(MessageBodyWriterInterceptor interceptor)
283 {
284 register(new LegacySingletonInterceptorFactory(interceptor.getClass(), interceptor, precedence)
285 {
286 @Override
287 public Match postMatch(Class declaring, AccessibleObject target)
288 {
289 Object obj = getLegacyMatch(declaring, target);
290 if (obj == null) return null;
291 MessageBodyWriterInterceptor interceptor = (MessageBodyWriterInterceptor)obj;
292 return new Match(new WriterInterceptorFacade(interceptor), order);
293 }
294 });
295
296 }
297 }
+0
-150
resteasy-legacy/src/main/java/org/jboss/resteasy/logging/Logger.java less more
0 package org.jboss.resteasy.logging;
1
2 import java.lang.reflect.Constructor;
3 import java.lang.reflect.InvocationTargetException;
4
5 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
6
7 /**
8 * Logging abstraction. Call setLoggerType() to the logging framework you want to use.
9 *
10 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
11 * @version $Revision: 1 $
12 */
13 /**
14 * @deprecated See RESTEASY-1578.
15 */
16 @Deprecated
17 public abstract class Logger
18 {
19 public static enum LoggerType
20 {
21 JUL,
22 LOG4J,
23 SLF4J
24 }
25
26 /**
27 * Set this variable to set what logger you want. The default is java.util.logging
28 */
29 private static Constructor loggerConstructor = null;
30
31 public static void setLoggerType(LoggerType loggerType)
32 {
33 try
34 {
35 Class loggerClass = null;
36 if (loggerType == LoggerType.JUL)
37 {
38 loggerClass = Logger.class.getClassLoader().loadClass("org.jboss.resteasy.logging.impl.JULLogger");
39 }
40 else if (loggerType == LoggerType.LOG4J)
41 {
42 loggerClass = Logger.class.getClassLoader().loadClass("org.jboss.resteasy.logging.impl.Log4jLogger");
43 }
44 else if (loggerType == LoggerType.SLF4J)
45 {
46 loggerClass = Logger.class.getClassLoader().loadClass("org.jboss.resteasy.logging.impl.Slf4jLogger");
47 }
48 if (loggerClass == null)
49 throw new RuntimeException(Messages.MESSAGES.couldNotMatchUpLoggerTypeImplementation(loggerType.getClass()));
50 loggerConstructor = loggerClass.getDeclaredConstructor(String.class);
51 }
52 catch (ClassNotFoundException e)
53 {
54 throw new RuntimeException(e);
55 }
56 catch (NoSuchMethodException e)
57 {
58 throw new RuntimeException(e);
59 }
60
61 }
62
63 private static boolean classInClasspath(String className)
64 {
65 try
66 {
67 return Thread.currentThread().getContextClassLoader().loadClass(className) != null;
68 }
69 catch (ClassNotFoundException e)
70 {
71 return false;
72 }
73
74 }
75
76 static
77 {
78 LoggerType type = LoggerType.JUL;
79
80 if (classInClasspath("org.apache.log4j.Logger"))
81 {
82 type = LoggerType.LOG4J;
83 }
84 else if (classInClasspath("org.slf4j.Logger"))
85 {
86 type = LoggerType.SLF4J;
87 }
88
89 setLoggerType(type);
90 }
91
92
93 public static Logger getLogger(Class<?> clazz)
94 {
95 try
96 {
97 return (Logger) loggerConstructor.newInstance(clazz.getName());
98 }
99 catch (InstantiationException e)
100 {
101 throw new RuntimeException(e);
102 }
103 catch (IllegalAccessException e)
104 {
105 throw new RuntimeException(e);
106 }
107 catch (InvocationTargetException e)
108 {
109 throw new RuntimeException(e);
110 }
111 }
112
113
114 public abstract boolean isTraceEnabled();
115
116 public abstract void trace(String message);
117
118 public abstract void trace(String message, Object... params);
119
120 public abstract void trace(String message, Throwable error);
121
122 public abstract boolean isDebugEnabled();
123
124 public abstract void debug(String message);
125
126 public abstract void debug(String message, Object... params);
127
128 public abstract void debug(String message, Throwable error);
129
130 public abstract void info(String message);
131
132 public abstract void info(String message, Object... params);
133
134 public abstract void info(String message, Throwable error);
135
136 public abstract boolean isWarnEnabled();
137
138 public abstract void warn(String message);
139
140 public abstract void warn(String message, Object... params);
141
142 public abstract void warn(String message, Throwable error);
143
144 public abstract void error(String message);
145
146 public abstract void error(String message, Object... params);
147
148 public abstract void error(String message, Throwable error);
149 }
+0
-146
resteasy-legacy/src/main/java/org/jboss/resteasy/logging/impl/JULLogger.java less more
0 package org.jboss.resteasy.logging.impl;
1
2 import org.jboss.resteasy.logging.Logger;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 */
8 /**
9 * @deprecated See RESTEASY-1578.
10 */
11 @Deprecated
12 public class JULLogger extends Logger
13 {
14 private transient java.util.logging.Logger delegate;
15 private String classname;
16
17 public JULLogger(String classname)
18 {
19 delegate = java.util.logging.Logger.getLogger(classname);
20 this.classname = classname;
21 }
22
23 @Override
24 public boolean isTraceEnabled()
25 {
26 return delegate.isLoggable(java.util.logging.Level.FINEST);
27 }
28
29 @Override
30 public void trace(String message)
31 {
32 if (!delegate.isLoggable(java.util.logging.Level.FINEST)) return;
33 delegate.logp(java.util.logging.Level.FINEST, classname, "", message);
34 }
35
36 @Override
37 public void trace(String message, Object... params)
38 {
39 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
40 delegate.logp(java.util.logging.Level.FINEST, classname, "", message, params);
41 }
42
43 @Override
44 public void trace(String message, Throwable error)
45 {
46 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
47 delegate.logp(java.util.logging.Level.FINEST, classname, "", message, error);
48 }
49
50 @Override
51 public boolean isDebugEnabled()
52 {
53 return delegate.isLoggable(java.util.logging.Level.FINE);
54 }
55
56 @Override
57 public void debug(String message)
58 {
59 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
60 delegate.logp(java.util.logging.Level.FINE, classname, "", message);
61 }
62
63 @Override
64 public void debug(String message, Object... params)
65 {
66 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
67 delegate.logp(java.util.logging.Level.FINE, classname, "", message, params);
68 }
69
70 @Override
71 public void debug(String message, Throwable error)
72 {
73 if (!delegate.isLoggable(java.util.logging.Level.FINE)) return;
74 delegate.logp(java.util.logging.Level.FINE, classname, "", message, error);
75 }
76
77 @Override
78 public void info(String message)
79 {
80 if (!delegate.isLoggable(java.util.logging.Level.INFO)) return;
81 delegate.logp(java.util.logging.Level.INFO, classname, "", message);
82 }
83
84 @Override
85 public void info(String message, Object... params)
86 {
87 if (!delegate.isLoggable(java.util.logging.Level.INFO)) return;
88 delegate.logp(java.util.logging.Level.INFO, classname, "", message, params);
89 }
90
91 @Override
92 public void info(String message, Throwable error)
93 {
94 if (!delegate.isLoggable(java.util.logging.Level.INFO)) return;
95 delegate.logp(java.util.logging.Level.INFO, classname, "", message, error);
96 }
97
98 @Override
99 public void warn(String message)
100 {
101 if (!delegate.isLoggable(java.util.logging.Level.WARNING)) return;
102 delegate.logp(java.util.logging.Level.WARNING, classname, "", message);
103 }
104
105 @Override
106 public void warn(String message, Object... params)
107 {
108 if (!delegate.isLoggable(java.util.logging.Level.WARNING)) return;
109 delegate.logp(java.util.logging.Level.WARNING, classname, "", message, params);
110 }
111
112 @Override
113 public void warn(String message, Throwable error)
114 {
115 if (!delegate.isLoggable(java.util.logging.Level.WARNING)) return;
116 delegate.logp(java.util.logging.Level.WARNING, classname, "", message, error);
117 }
118
119 @Override
120 public void error(String message)
121 {
122 if (!delegate.isLoggable(java.util.logging.Level.SEVERE)) return;
123 delegate.logp(java.util.logging.Level.SEVERE, classname, "", message);
124 }
125
126 @Override
127 public void error(String message, Object... params)
128 {
129 if (!delegate.isLoggable(java.util.logging.Level.SEVERE)) return;
130 delegate.logp(java.util.logging.Level.SEVERE, classname, "", message, params);
131 }
132
133 @Override
134 public void error(String message, Throwable error)
135 {
136 if (!delegate.isLoggable(java.util.logging.Level.SEVERE)) return;
137 delegate.logp(java.util.logging.Level.SEVERE, classname, "", message, error);
138 }
139
140 @Override
141 public boolean isWarnEnabled()
142 {
143 return delegate.isLoggable(java.util.logging.Level.WARNING);
144 }
145 }
+0
-148
resteasy-legacy/src/main/java/org/jboss/resteasy/logging/impl/Log4jLogger.java less more
0 package org.jboss.resteasy.logging.impl;
1
2 import org.apache.log4j.Logger;
3
4 import java.text.MessageFormat;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 /**
11 * @deprecated See RESTEASY-1578.
12 */
13 @Deprecated
14 public class Log4jLogger extends org.jboss.resteasy.logging.Logger
15 {
16 private transient Logger delegate;
17 private String classname;
18
19 public Log4jLogger(String classname)
20 {
21 this.classname = classname;
22 delegate = Logger.getLogger(classname);
23 }
24
25 @Override
26 public boolean isTraceEnabled()
27 {
28 return delegate.isTraceEnabled();
29 }
30
31 @Override
32 public void trace(String message)
33 {
34 if (!delegate.isTraceEnabled()) return;
35 delegate.trace(message);
36 }
37
38 @Override
39 public void trace(String message, Object... params)
40 {
41 if (!delegate.isTraceEnabled()) return;
42 String msg = MessageFormat.format(message, params);
43 delegate.trace(msg);
44 }
45
46 @Override
47 public void trace(String message, Throwable error)
48 {
49 if (!delegate.isTraceEnabled()) return;
50 delegate.trace(message, error);
51 }
52
53 @Override
54 public boolean isDebugEnabled()
55 {
56 return delegate.isDebugEnabled();
57 }
58
59 @Override
60 public void debug(String message)
61 {
62 if (!delegate.isDebugEnabled()) return;
63 delegate.debug(message);
64 }
65
66 @Override
67 public void debug(String message, Object... params)
68 {
69 if (!delegate.isDebugEnabled()) return;
70 String msg = MessageFormat.format(message, params);
71 delegate.debug(msg);
72 }
73
74 @Override
75 public void debug(String message, Throwable error)
76 {
77 if (!isDebugEnabled()) return;
78 delegate.debug(message, error);
79 }
80
81 @Override
82 public void info(String message)
83 {
84 if (!(delegate.isInfoEnabled())) return;
85 delegate.info(message);
86 }
87
88 @Override
89 public void info(String message, Object... params)
90 {
91 if (!delegate.isInfoEnabled()) return;
92 String msg = MessageFormat.format(message, params);
93 delegate.info(msg);
94 }
95
96 @Override
97 public void info(String message, Throwable error)
98 {
99 if (!delegate.isInfoEnabled()) return;
100 delegate.info(message, error);
101 }
102
103 @Override
104 public void warn(String message)
105 {
106 delegate.warn(message);
107 }
108
109 @Override
110 public void warn(String message, Object... params)
111 {
112 String msg = MessageFormat.format(message, params);
113 delegate.warn(msg);
114 }
115
116 @Override
117 public void warn(String message, Throwable error)
118 {
119 delegate.warn(message, error);
120 }
121
122 @Override
123 public void error(String message)
124 {
125 delegate.warn(message);
126 }
127
128 @Override
129 public void error(String message, Object... params)
130 {
131 String msg = MessageFormat.format(message, params);
132 delegate.error(msg);
133 }
134
135 @Override
136 public void error(String message, Throwable error)
137 {
138 delegate.warn(message, error);
139 }
140
141 @Override
142 public boolean isWarnEnabled()
143 {
144 return true;
145 }
146
147 }
+0
-156
resteasy-legacy/src/main/java/org/jboss/resteasy/logging/impl/Slf4jLogger.java less more
0 package org.jboss.resteasy.logging.impl;
1
2 import org.slf4j.Logger;
3 import org.slf4j.LoggerFactory;
4
5 import java.text.MessageFormat;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 */
11 /**
12 * @deprecated See RESTEASY-1578.
13 */
14 @Deprecated
15 public class Slf4jLogger extends org.jboss.resteasy.logging.Logger
16 {
17 private transient Logger delegate;
18 private String classname;
19
20 public Slf4jLogger(String classname)
21 {
22 delegate = LoggerFactory.getLogger(classname);
23 this.classname = classname;
24 }
25
26 @Override
27 public boolean isTraceEnabled()
28 {
29 return delegate.isTraceEnabled();
30 }
31
32 @Override
33 public void trace(String message)
34 {
35 if (!delegate.isTraceEnabled()) return;
36 delegate.trace(message);
37 }
38
39 @Override
40 public void trace(String message, Object... params)
41 {
42 if (!delegate.isTraceEnabled()) return;
43 String msg = MessageFormat.format(message, params);
44 delegate.trace(msg);
45 }
46
47 @Override
48 public void trace(String message, Throwable error)
49 {
50 if (!delegate.isTraceEnabled()) return;
51 delegate.trace(message, error);
52
53 }
54
55 @Override
56 public boolean isDebugEnabled()
57 {
58 return delegate.isDebugEnabled();
59 }
60
61 @Override
62 public void debug(String message)
63 {
64 if (!delegate.isDebugEnabled()) return;
65 delegate.debug(message);
66 }
67
68 @Override
69 public void debug(String message, Object... params)
70 {
71 if (!delegate.isDebugEnabled()) return;
72 String msg = MessageFormat.format(message, params);
73 delegate.debug(msg);
74 }
75
76 @Override
77 public void debug(String message, Throwable error)
78 {
79 if (!delegate.isDebugEnabled()) return;
80 delegate.debug(message, error);
81 }
82
83 @Override
84 public void info(String message)
85 {
86 if (!delegate.isInfoEnabled()) return;
87 delegate.info(message);
88 }
89
90 @Override
91 public void info(String message, Object... params)
92 {
93 if (!delegate.isInfoEnabled()) return;
94 String msg = MessageFormat.format(message, params);
95 delegate.info(msg);
96 }
97
98 @Override
99 public void info(String message, Throwable error)
100 {
101 if (!delegate.isInfoEnabled()) return;
102 delegate.info(message, error);
103 }
104
105 @Override
106 public void warn(String message)
107 {
108 if (!delegate.isWarnEnabled()) return;
109 delegate.warn(message);
110 }
111
112 @Override
113 public void warn(String message, Object... params)
114 {
115 if (!delegate.isWarnEnabled()) return;
116 String msg = MessageFormat.format(message, params);
117 delegate.warn(msg);
118 }
119
120 @Override
121 public void warn(String message, Throwable error)
122 {
123 if (!delegate.isWarnEnabled()) return;
124 delegate.warn(message, error);
125 }
126
127 @Override
128 public void error(String message)
129 {
130 if (!delegate.isErrorEnabled()) return;
131 delegate.error(message);
132 }
133
134 @Override
135 public void error(String message, Object... params)
136 {
137 if (!delegate.isErrorEnabled()) return;
138 String msg = MessageFormat.format(message, params);
139 delegate.error(msg);
140 }
141
142 @Override
143 public void error(String message, Throwable error)
144 {
145 if (!delegate.isErrorEnabled()) return;
146 delegate.error(message, error);
147 }
148
149 @Override
150 public boolean isWarnEnabled()
151 {
152 return delegate.isWarnEnabled();
153 }
154
155 }
+0
-22
resteasy-legacy/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/AcceptEncodingGZIPFilter.java less more
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.Priorities;
4 import javax.ws.rs.client.ClientRequestFilter;
5 import javax.ws.rs.ext.Provider;
6
7 /**
8 * Must be used in conjunction with GZIPDecodingInterceptor
9 * <p/>
10 * Sets
11 *
12 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
13 * @deprecated Use org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter instead
14 * @version $Revision: 1 $
15 */
16 @Provider
17 @Priority(Priorities.HEADER_DECORATOR)
18 @Deprecated
19 public class AcceptEncodingGZIPFilter extends org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter implements ClientRequestFilter
20 {
21 }
+0
-42
resteasy-legacy/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/AcceptEncodingGZIPInterceptor.java less more
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import org.jboss.resteasy.annotations.interception.ClientInterceptor;
3 import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.spi.interception.ClientExecutionContext;
6 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
7
8 import javax.ws.rs.core.HttpHeaders;
9 import javax.ws.rs.ext.Provider;
10
11 /**
12 * Must be used in conjunction with GZIPDecodingInterceptor
13 * <p/>
14 * Sets
15 *
16 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
17 * @version $Revision: 1 $
18 */
19 @Provider
20 @ClientInterceptor
21 @HeaderDecoratorPrecedence
22 public class AcceptEncodingGZIPInterceptor implements ClientExecutionInterceptor
23 {
24 public ClientResponse execute(ClientExecutionContext ctx) throws Exception
25 {
26 String encoding = ctx.getRequest().getHeaders().getFirst(HttpHeaders.ACCEPT_ENCODING);
27 if (encoding == null)
28 {
29 ctx.getRequest().header(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate");
30 }
31 else
32 {
33 if (!encoding.contains("gzip"))
34 {
35 encoding += ", gzip";
36 ctx.getRequest().header(HttpHeaders.ACCEPT_ENCODING, encoding);
37 }
38 }
39 return ctx.proceed();
40 }
41 }
+0
-16
resteasy-legacy/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ClientContentEncodingAnnotationFeature.java less more
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import javax.ws.rs.ConstrainedTo;
3 import javax.ws.rs.RuntimeType;
4 import javax.ws.rs.container.DynamicFeature;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @deprecated Use org.jboss.resteasy.plugins.interceptors.ClientContentEncodingAnnotationFeature instead.
9 * @version $Revision: 1 $
10 */
11 @ConstrainedTo(RuntimeType.CLIENT)
12 @Deprecated
13 public class ClientContentEncodingAnnotationFeature extends org.jboss.resteasy.plugins.interceptors.ClientContentEncodingAnnotationFeature implements DynamicFeature
14 {
15 }
+0
-23
resteasy-legacy/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ClientContentEncodingAnnotationFilter.java less more
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.ConstrainedTo;
4 import javax.ws.rs.Priorities;
5 import javax.ws.rs.RuntimeType;
6 import javax.ws.rs.ext.WriterInterceptor;
7
8 /**
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @deprecated Use org.jboss.resteasy.plugins.interceptors.ClientContentEncodingAnnotationFilter instead.
11 * @version $Revision: 1 $
12 */
13 @ConstrainedTo(RuntimeType.CLIENT)
14 @Priority(Priorities.HEADER_DECORATOR)
15 @Deprecated
16 public class ClientContentEncodingAnnotationFilter extends org.jboss.resteasy.plugins.interceptors.ClientContentEncodingAnnotationFilter implements WriterInterceptor
17 {
18 public ClientContentEncodingAnnotationFilter(String encoding)
19 {
20 super(encoding);
21 }
22 }
+0
-27
resteasy-legacy/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/GZIPDecodingInterceptor.java less more
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.Priorities;
4 import javax.ws.rs.ext.Provider;
5 import javax.ws.rs.ext.ReaderInterceptor;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @deprecated Use org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor instead.
10 * @version $Revision: 1 $
11 */
12 @Provider
13 @Priority(Priorities.ENTITY_CODER)
14 @Deprecated
15 public class GZIPDecodingInterceptor extends org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor implements ReaderInterceptor
16 {
17 public GZIPDecodingInterceptor(int maxSize)
18 {
19 super(maxSize);
20 }
21
22 public GZIPDecodingInterceptor()
23 {
24 super();
25 }
26 }
+0
-18
resteasy-legacy/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/GZIPEncodingInterceptor.java less more
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.Priorities;
4 import javax.ws.rs.ext.Provider;
5 import javax.ws.rs.ext.WriterInterceptor;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @deprecated Use org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor instead.
10 * @version $Revision: 1 $
11 */
12 @Provider
13 @Priority(Priorities.ENTITY_CODER)
14 @Deprecated
15 public class GZIPEncodingInterceptor extends org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor implements WriterInterceptor
16 {
17 }
+0
-16
resteasy-legacy/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFeature.java less more
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import javax.ws.rs.ConstrainedTo;
3 import javax.ws.rs.RuntimeType;
4 import javax.ws.rs.container.DynamicFeature;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @deprecated Use org.jboss.resteasy.plugins.interceptors.ServerContentEncodingAnnotationFeature instead.
9 * @version $Revision: 1 $
10 */
11 @ConstrainedTo(RuntimeType.SERVER)
12 @Deprecated
13 public class ServerContentEncodingAnnotationFeature extends org.jboss.resteasy.plugins.interceptors.ServerContentEncodingAnnotationFeature implements DynamicFeature
14 {
15 }
+0
-25
resteasy-legacy/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFilter.java less more
0 package org.jboss.resteasy.plugins.interceptors.encoding;
1
2 import java.util.Set;
3
4 import javax.annotation.Priority;
5 import javax.ws.rs.ConstrainedTo;
6 import javax.ws.rs.Priorities;
7 import javax.ws.rs.RuntimeType;
8 import javax.ws.rs.ext.WriterInterceptor;
9
10 /**
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @deprecated Use org.jboss.resteasy.plugins.interceptors.ServerContentEncodingAnnotationFilter instead.
13 * @version $Revision: 1 $
14 */
15 @ConstrainedTo(RuntimeType.SERVER)
16 @Priority(Priorities.HEADER_DECORATOR)
17 @Deprecated
18 public class ServerContentEncodingAnnotationFilter extends org.jboss.resteasy.plugins.interceptors.ServerContentEncodingAnnotationFilter implements WriterInterceptor
19 {
20 public ServerContentEncodingAnnotationFilter(Set<String> encodings)
21 {
22 super(encodings);
23 }
24 }
+0
-20
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/AcceptedByMethod.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import java.lang.reflect.Method;
3
4 /**
5 * Implemented interface that can trigger the addition of an interceptor
6 *
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 *
10 * @deprecated The Resteasy interceptor facility introduced in release 2.x
11 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
12 *
13 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
14 */
15 @Deprecated
16 public interface AcceptedByMethod
17 {
18 public boolean accept(Class declaring, Method method);
19 }
+0
-21
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/ClientExecutionContext.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
4
5 /**
6 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
7 * @version $Revision: 1 $
8 *
9 * @deprecated The Resteasy interceptor facility introduced in release 2.x
10 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
11 *
12 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
13 */
14 @Deprecated
15 public interface ClientExecutionContext
16 {
17 ClientRequest getRequest();
18
19 ClientResponse proceed() throws Exception;
20 }
+0
-18
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/ClientExecutionInterceptor.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import org.jboss.resteasy.client.ClientResponse;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 *
8 * @deprecated The Resteasy interceptor facility introduced in release 2.x
9 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
10 *
11 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
12 */
13 @Deprecated
14 public interface ClientExecutionInterceptor
15 {
16 ClientResponse execute(ClientExecutionContext ctx) throws Exception;
17 }
+0
-17
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/DecoratorProcessor.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import java.lang.annotation.Annotation;
3
4 /**
5 * Part of a generic decorator framework.
6 * <p/>
7 * Decorate a target. For example, decorate a JAXB Marshaller with property values.
8 *
9 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
10 * @version $Revision: 1 $
11 * @deprecated Use org.jboss.resteasy.spi.DecoratorProcessor instead.
12 */
13 @Deprecated
14 public interface DecoratorProcessor<T, A extends Annotation> extends org.jboss.resteasy.spi.DecoratorProcessor<T, A>
15 {
16 }
+0
-59
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderContext.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.lang.annotation.Annotation;
8 import java.lang.reflect.Type;
9
10 /**
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @version $Revision: 1 $
13 *
14 * @deprecated The Resteasy interceptor facility introduced in release 2.x
15 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
16 *
17 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
18 */
19 @Deprecated
20 public interface MessageBodyReaderContext
21 {
22 Class getType();
23
24 void setType(Class type);
25
26 Type getGenericType();
27
28 void setGenericType(Type genericType);
29
30 Annotation[] getAnnotations();
31
32 void setAnnotations(Annotation[] annotations);
33
34 MediaType getMediaType();
35
36 void setMediaType(MediaType mediaType);
37
38 MultivaluedMap<String, String> getHeaders();
39
40 InputStream getInputStream();
41
42 void setInputStream(InputStream is);
43
44 /**
45 * Allows you to pass values back and forth between interceptors
46 * On the server side, this is the HttpRequest attributes, on the client side, this is the ClientRequest/ClientResponse
47 * attributes.
48 *
49 * @return
50 */
51 Object getAttribute(String attribute);
52
53 void setAttribute(String name, Object value);
54
55 void removeAttribute(String name);
56
57 Object proceed() throws IOException, WebApplicationException;
58 }
+0
-29
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderInterceptor.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import javax.ws.rs.WebApplicationException;
3 import java.io.IOException;
4
5 /**
6 * Wraps around invocations of MessageBodyReader.readFrom().
7 *
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 *
11 * @deprecated The Resteasy interceptor facility introduced in release 2.x
12 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
13 *
14 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
15 * @see javax.ws.rs.ext.ReaderInterceptor
16 */
17 @Deprecated
18 public interface MessageBodyReaderInterceptor
19 {
20 /**
21 * @param context
22 * @return the object read
23 * @throws IOException
24 * @throws WebApplicationException
25 */
26 Object read(MessageBodyReaderContext context) throws IOException, WebApplicationException;
27
28 }
+0
-63
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyWriterContext.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import java.io.IOException;
6 import java.io.OutputStream;
7 import java.lang.annotation.Annotation;
8 import java.lang.reflect.Type;
9
10 /**
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @version $Revision: 1 $
13 *
14 * @deprecated The Resteasy interceptor facility introduced in release 2.x
15 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
16 *
17 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
18 */
19 @Deprecated
20 public interface MessageBodyWriterContext
21 {
22 Object getEntity();
23
24 void setEntity(Object entity);
25
26 Class getType();
27
28 void setType(Class type);
29
30 Type getGenericType();
31
32 void setGenericType(Type genericType);
33
34 Annotation[] getAnnotations();
35
36 void setAnnotations(Annotation[] annotations);
37
38 MediaType getMediaType();
39
40 void setMediaType(MediaType mediaType);
41
42 MultivaluedMap<String, Object> getHeaders();
43
44 OutputStream getOutputStream();
45
46 public void setOutputStream(OutputStream os);
47
48 /**
49 * Allows you to pass values back and forth between interceptors
50 * On the server side, this is the HttpRequest attributes, on the client side, this is the ClientRequest/ClientResponse
51 * attributes.
52 *
53 * @return
54 */
55 Object getAttribute(String attribute);
56
57 void setAttribute(String name, Object value);
58
59 void removeAttribute(String name);
60
61 void proceed() throws IOException, WebApplicationException;
62 }
+0
-23
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyWriterInterceptor.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import javax.ws.rs.WebApplicationException;
3 import java.io.IOException;
4
5 /**
6 * Wraps around invocations of MessageBodyWriter.writeTo()
7 *
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 *
11 * @deprecated The Resteasy interceptor facility introduced in release 2.x
12 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
13 *
14 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
15 * @see javax.ws.rs.ext.WriterInterceptor
16 */
17 @Deprecated
18 public interface MessageBodyWriterInterceptor
19 {
20 void write(MessageBodyWriterContext context) throws IOException, WebApplicationException;
21
22 }
+0
-20
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/PostProcessInterceptor.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import org.jboss.resteasy.core.ServerResponse;
3
4 /**
5 * Invoked in order, gives you access to the response before MessageBodyReader and Writers get invoked.
6 *
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 *
10 * @deprecated The Resteasy interceptor facility introduced in release 2.x
11 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
12 *
13 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
14 */
15 @Deprecated
16 public interface PostProcessInterceptor
17 {
18 void postProcess(ServerResponse response);
19 }
+0
-33
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/PreProcessInterceptor.java less more
0 package org.jboss.resteasy.spi.interception;
1
2 import org.jboss.resteasy.core.ResourceMethodInvoker;
3 import org.jboss.resteasy.core.ServerResponse;
4 import org.jboss.resteasy.spi.Failure;
5 import org.jboss.resteasy.spi.HttpRequest;
6
7 import javax.ws.rs.WebApplicationException;
8
9 /**
10 * Executed before resource method (not resource locator methods though!)
11 * <p/>
12 * The interceptor can decide to return its own response. This will result in not invoking the resource method.
13 *
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 *
17 * @deprecated The Resteasy interceptor facility introduced in release 2.x
18 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
19 *
20 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
21 */
22 @Deprecated
23 public interface PreProcessInterceptor
24 {
25 /**
26 * Preprocess resource method invocation
27 *
28 * @param request
29 * @return null unless the interceptor is returning its own response
30 */
31 ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException;
32 }
+0
-11
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/interception/package-info.java less more
0 /**
1 * JAX-RS specification 1.1 ({@link <a href="https://jcp.org/en/jsr/detail?id=311">https://jcp.org/en/jsr/detail?id=311</a>})
2 * had no interceptor framework, so Resteasy release 2.x provided one.
3 *
4 * However, JAX-RS specification 2.0
5 * ({@link <a href="https://www.jcp.org/aboutJava/communityprocess/final/jsr339/index.html">https://www.jcp.org/aboutJava/communityprocess/final/jsr339/index.html</a>})
6 * introduced an official interceptor/filter framework, so the older Resteasy interceptor framework is now deprecated.
7 *
8 * The relevant interfaces are defined in the javax.ws.rs.ext package of the jaxrs-api module.
9 */
10 package org.jboss.resteasy.spi.interception;
+0
-526
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/old/ResteasyProviderFactory.java less more
0 package org.jboss.resteasy.spi.old;
1
2 import java.lang.reflect.Type;
3 import java.util.List;
4 import java.util.Map;
5 import java.util.concurrent.ConcurrentHashMap;
6 import java.util.concurrent.CopyOnWriteArrayList;
7
8 import javax.ws.rs.Priorities;
9 import javax.ws.rs.client.ClientRequestFilter;
10 import javax.ws.rs.ext.ContextResolver;
11
12 import org.jboss.resteasy.annotations.interception.ClientInterceptor;
13 import org.jboss.resteasy.annotations.interception.DecoderPrecedence;
14 import org.jboss.resteasy.annotations.interception.EncoderPrecedence;
15 import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
16 import org.jboss.resteasy.annotations.interception.RedirectPrecedence;
17 import org.jboss.resteasy.annotations.interception.SecurityPrecedence;
18 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
19 import org.jboss.resteasy.client.core.ClientErrorInterceptor;
20 import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper;
21 import org.jboss.resteasy.core.interception.InterceptorRegistry;
22 import org.jboss.resteasy.core.interception.LegacyPrecedence;
23 import org.jboss.resteasy.core.interception.ClientResponseFilterRegistry;
24 import org.jboss.resteasy.core.interception.ContainerRequestFilterRegistry;
25 import org.jboss.resteasy.core.interception.ContainerResponseFilterRegistry;
26 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
27 import org.jboss.resteasy.core.interception.ReaderInterceptorRegistry;
28 import org.jboss.resteasy.core.interception.WriterInterceptorRegistry;
29 import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
30 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
31 import org.jboss.resteasy.spi.interception.MessageBodyReaderInterceptor;
32 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
33 import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
34 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
35 import org.jboss.resteasy.util.Types;
36
37 /**
38 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
39 * @version $Revision: 1 $
40 */
41 @SuppressWarnings("unchecked")
42 public class ResteasyProviderFactory extends org.jboss.resteasy.spi.ResteasyProviderFactory
43 {
44 protected Map<Class<?>, ClientExceptionMapper> clientExceptionMappers;
45 protected LegacyPrecedence precedence;
46
47 protected InterceptorRegistry<ClientExecutionInterceptor> clientExecutionInterceptorRegistry;
48
49 protected List<ClientErrorInterceptor> clientErrorInterceptors;
50
51 public ResteasyProviderFactory()
52 {
53 super();
54 }
55
56 /**
57 * Copies a specific component registry when a new
58 * provider is added. Otherwise delegates to the parent.
59 *
60 * @param parent
61 */
62 public ResteasyProviderFactory(ResteasyProviderFactory parent)
63 {
64 super(parent, false);
65 }
66
67 /**
68 * If local is true, copies components needed by client configuration,
69 * so that parent is not referenced.
70 * @param parent
71 * @param local
72 */
73 public ResteasyProviderFactory(ResteasyProviderFactory parent, boolean local)
74 {
75 super(parent, local);
76 }
77
78 protected void initialize()
79 {
80 super.initialize();
81 clientExceptionMappers = new ConcurrentHashMap<Class<?>, ClientExceptionMapper>();
82 clientExecutionInterceptorRegistry = new InterceptorRegistry<ClientExecutionInterceptor>(ClientExecutionInterceptor.class, this);
83 clientErrorInterceptors = new CopyOnWriteArrayList<ClientErrorInterceptor>();
84 registerDefaultInterceptorPrecedences();
85 }
86
87 protected void initializeRegistriesAndFilters()
88 {
89 precedence = new LegacyPrecedence();
90 serverReaderInterceptorRegistry = new ReaderInterceptorRegistry(this, precedence);
91 serverWriterInterceptorRegistry = new WriterInterceptorRegistry(this, precedence);
92 containerRequestFilterRegistry = new ContainerRequestFilterRegistry(this, precedence);
93 containerResponseFilterRegistry = new ContainerResponseFilterRegistry(this, precedence);
94
95 clientRequestFilters = new JaxrsInterceptorRegistry<ClientRequestFilter>(this, ClientRequestFilter.class);
96 clientResponseFilters = new ClientResponseFilterRegistry(this);
97 clientReaderInterceptorRegistry = new ReaderInterceptorRegistry(this, precedence);
98 clientWriterInterceptorRegistry = new WriterInterceptorRegistry(this, precedence);
99
100 }
101
102 protected Map<Class<?>, ClientExceptionMapper> getClientExceptionMappers()
103 {
104 if (clientExceptionMappers == null && parent != null && parent instanceof ResteasyProviderFactory) return ((ResteasyProviderFactory)parent).getClientExceptionMappers();
105 return clientExceptionMappers;
106 }
107
108 protected LegacyPrecedence getPrecedence()
109 {
110 if (precedence == null && parent != null) return ((ResteasyProviderFactory)parent).getPrecedence();
111 return precedence;
112 }
113
114 protected void registerDefaultInterceptorPrecedences(InterceptorRegistry registry)
115 {
116 // legacy
117 registry.appendPrecedence(SecurityPrecedence.PRECEDENCE_STRING);
118 registry.appendPrecedence(HeaderDecoratorPrecedence.PRECEDENCE_STRING);
119 registry.appendPrecedence(EncoderPrecedence.PRECEDENCE_STRING);
120 registry.appendPrecedence(RedirectPrecedence.PRECEDENCE_STRING);
121 registry.appendPrecedence(DecoderPrecedence.PRECEDENCE_STRING);
122
123 }
124
125 protected void registerDefaultInterceptorPrecedences()
126 {
127 precedence.addPrecedence(SecurityPrecedence.PRECEDENCE_STRING, Priorities.AUTHENTICATION);
128 precedence.addPrecedence(HeaderDecoratorPrecedence.PRECEDENCE_STRING, Priorities.HEADER_DECORATOR);
129 precedence.addPrecedence(EncoderPrecedence.PRECEDENCE_STRING, Priorities.ENTITY_CODER);
130 precedence.addPrecedence(RedirectPrecedence.PRECEDENCE_STRING, Priorities.ENTITY_CODER + 50);
131 precedence.addPrecedence(DecoderPrecedence.PRECEDENCE_STRING, Priorities.ENTITY_CODER);
132
133 registerDefaultInterceptorPrecedences(getClientExecutionInterceptorRegistry());
134 }
135
136 private boolean isParentSameType() {
137 return parent != null && parent instanceof ResteasyProviderFactory;
138 }
139
140 /**
141 * Append interceptor predence
142 *
143 * @param precedence
144 */
145 public void appendInterceptorPrecedence(String precedence)
146 {
147 if (this.precedence == null)
148 {
149 this.precedence = ((ResteasyProviderFactory)parent).getPrecedence().clone();
150 }
151 if (clientExecutionInterceptorRegistry == null)
152 {
153 clientExecutionInterceptorRegistry = ((ResteasyProviderFactory)parent).getClientExecutionInterceptorRegistry().cloneTo(this);
154 }
155 this.precedence.appendPrecedence(precedence);
156 clientExecutionInterceptorRegistry.appendPrecedence(precedence);
157 }
158
159 /**
160 * @param after put newPrecedence after this
161 * @param newPrecedence
162 */
163 public void insertInterceptorPrecedenceAfter(String after, String newPrecedence)
164 {
165 if (this.precedence == null)
166 {
167 this.precedence = ((ResteasyProviderFactory)parent).getPrecedence().clone();
168 }
169 if (clientExecutionInterceptorRegistry == null)
170 {
171 clientExecutionInterceptorRegistry = ((ResteasyProviderFactory)parent).getClientExecutionInterceptorRegistry().cloneTo(this);
172 }
173 this.precedence.insertPrecedenceAfter(after, newPrecedence);
174
175 getClientExecutionInterceptorRegistry().insertPrecedenceAfter(after, newPrecedence);
176 }
177
178 /**
179 * @param before put newPrecedence before this
180 * @param newPrecedence
181 */
182 public void insertInterceptorPrecedenceBefore(String before, String newPrecedence)
183 {
184 if (this.precedence == null)
185 {
186 this.precedence = ((ResteasyProviderFactory)parent).getPrecedence().clone();
187 }
188 if (clientExecutionInterceptorRegistry == null)
189 {
190 clientExecutionInterceptorRegistry = ((ResteasyProviderFactory)parent).getClientExecutionInterceptorRegistry().cloneTo(this);
191 }
192 this.precedence.insertPrecedenceBefore(before, newPrecedence);
193
194 getClientExecutionInterceptorRegistry().insertPrecedenceBefore(before, newPrecedence);
195 }
196
197 public InterceptorRegistry<ClientExecutionInterceptor> getClientExecutionInterceptorRegistry()
198 {
199 if (clientExecutionInterceptorRegistry == null && parent != null)
200 return ((ResteasyProviderFactory)parent).getClientExecutionInterceptorRegistry();
201 return clientExecutionInterceptorRegistry;
202 }
203
204 @Override
205 public ReaderInterceptorRegistry getServerReaderInterceptorRegistry()
206 {
207 if (serverReaderInterceptorRegistry == null && parent != null) return ((ResteasyProviderFactory)parent).getServerReaderInterceptorRegistry();
208 return (ReaderInterceptorRegistry)serverReaderInterceptorRegistry;
209 }
210
211 @Override
212 public WriterInterceptorRegistry getServerWriterInterceptorRegistry()
213 {
214 if (serverWriterInterceptorRegistry == null && parent != null) return ((ResteasyProviderFactory)parent).getServerWriterInterceptorRegistry();
215 return (WriterInterceptorRegistry)serverWriterInterceptorRegistry;
216 }
217
218 @Override
219 public ContainerRequestFilterRegistry getContainerRequestFilterRegistry()
220 {
221 if (containerRequestFilterRegistry == null && parent != null) return ((ResteasyProviderFactory)parent).getContainerRequestFilterRegistry();
222 return (ContainerRequestFilterRegistry)containerRequestFilterRegistry;
223 }
224
225 @Override
226 public ContainerResponseFilterRegistry getContainerResponseFilterRegistry()
227 {
228 if (containerResponseFilterRegistry == null && parent != null) return ((ResteasyProviderFactory)parent).getContainerResponseFilterRegistry();
229 return (ContainerResponseFilterRegistry)containerResponseFilterRegistry;
230 }
231
232 @Override
233 public ReaderInterceptorRegistry getClientReaderInterceptorRegistry()
234 {
235 if (clientReaderInterceptorRegistry == null && parent != null) return ((ResteasyProviderFactory)parent).getClientReaderInterceptorRegistry();
236 return (ReaderInterceptorRegistry)clientReaderInterceptorRegistry;
237 }
238
239 @Override
240 public WriterInterceptorRegistry getClientWriterInterceptorRegistry()
241 {
242 if (clientWriterInterceptorRegistry == null && parent != null) return ((ResteasyProviderFactory)parent).getClientWriterInterceptorRegistry();
243 return (WriterInterceptorRegistry)clientWriterInterceptorRegistry;
244 }
245
246 @Override
247 public JaxrsInterceptorRegistry<ClientRequestFilter> getClientRequestFilters()
248 {
249 if (clientRequestFilters == null && parent != null) return ((ResteasyProviderFactory)parent).getClientRequestFilters();
250 return (JaxrsInterceptorRegistry<ClientRequestFilter>)clientRequestFilters;
251 }
252
253 @Override
254 public ClientResponseFilterRegistry getClientResponseFilters()
255 {
256 if (clientResponseFilters == null && parent != null) return ((ResteasyProviderFactory)parent).getClientResponseFilters();
257 return (ClientResponseFilterRegistry)clientResponseFilters;
258 }
259
260 public void addClientExceptionMapper(Class<? extends ClientExceptionMapper<?>> providerClass)
261 {
262 ClientExceptionMapper<?> provider = createProviderInstance(providerClass);
263 addClientExceptionMapper(provider, providerClass);
264 }
265
266 public void addClientExceptionMapper(ClientExceptionMapper<?> provider)
267 {
268 addClientExceptionMapper(provider, provider.getClass());
269 }
270
271 public void addClientExceptionMapper(ClientExceptionMapper<?> provider, Class<?> providerClass)
272 {
273 Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(providerClass, ClientExceptionMapper.class)[0];
274 addClientExceptionMapper(provider, exceptionType);
275 }
276
277 public void addClientExceptionMapper(ClientExceptionMapper<?> provider, Type exceptionType)
278 {
279 injectProperties(provider.getClass());
280
281 Class<?> exceptionClass = Types.getRawType(exceptionType);
282 if (!Throwable.class.isAssignableFrom(exceptionClass))
283 {
284 throw new RuntimeException(Messages.MESSAGES.incorrectTypeParameterClientExceptionMapper());
285 }
286 if (clientExceptionMappers == null)
287 {
288 clientExceptionMappers = new ConcurrentHashMap<Class<?>, ClientExceptionMapper>();
289 clientExceptionMappers.putAll(((ResteasyProviderFactory)parent).getClientExceptionMappers());
290 }
291 clientExceptionMappers.put(exceptionClass, provider);
292 }
293
294 /**
295 * Add a {@link ClientErrorInterceptor} to this provider factory instance.
296 * Duplicate handlers are ignored. (For Client Proxy API only)
297 */
298 public void addClientErrorInterceptor(ClientErrorInterceptor handler)
299 {
300 if (clientErrorInterceptors == null)
301 {
302 clientErrorInterceptors = new CopyOnWriteArrayList<ClientErrorInterceptor>(((ResteasyProviderFactory)parent).getClientErrorInterceptors());
303 }
304 if (!clientErrorInterceptors.contains(handler))
305 {
306 clientErrorInterceptors.add(handler);
307 }
308 }
309
310
311 /**
312 * Return the list of currently registered {@link ClientErrorInterceptor} instances.
313 */
314 public List<ClientErrorInterceptor> getClientErrorInterceptors()
315 {
316 if (clientErrorInterceptors == null && parent != null) return ((ResteasyProviderFactory)parent).getClientErrorInterceptors();
317 return clientErrorInterceptors;
318 }
319
320 protected void addContextResolver(Class<? extends ContextResolver> resolver, boolean builtin)
321 {
322 ContextResolver writer = createProviderInstance(resolver);
323 addContextResolver(writer, resolver, builtin);
324 }
325
326 @Override
327 protected void processProviderContracts(Class provider, Integer priorityOverride, boolean isBuiltin,
328 Map<Class<?>, Integer> contracts, Map<Class<?>, Integer> newContracts)
329 {
330 super.processProviderContracts(provider, priorityOverride, isBuiltin, contracts, newContracts);
331 if (isA(provider, ClientExceptionMapper.class, contracts))
332 {
333 try
334 {
335 addClientExceptionMapper(provider);
336 newContracts.put(ClientExceptionMapper.class,
337 getPriority(priorityOverride, contracts, ClientExceptionMapper.class, provider));
338 }
339 catch (Exception e)
340 {
341 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateClientExceptionMapper(), e);
342 }
343 }
344 if (isA(provider, ClientExecutionInterceptor.class, contracts))
345 {
346 if (clientExecutionInterceptorRegistry == null)
347 {
348 clientExecutionInterceptorRegistry = ((ResteasyProviderFactory)parent).getClientExecutionInterceptorRegistry().cloneTo(this);
349 }
350 clientExecutionInterceptorRegistry.register(provider);
351 newContracts.put(ClientExecutionInterceptor.class, 0);
352 }
353 if (isA(provider, PreProcessInterceptor.class, contracts))
354 {
355 if (containerRequestFilterRegistry == null)
356 {
357 containerRequestFilterRegistry = ((ResteasyProviderFactory)parent).getContainerRequestFilterRegistry().clone(this);
358 }
359 ((ContainerRequestFilterRegistry)containerRequestFilterRegistry).registerLegacy(provider);
360 newContracts.put(PreProcessInterceptor.class, 0);
361 }
362 if (isA(provider, PostProcessInterceptor.class, contracts))
363 {
364 if (containerResponseFilterRegistry == null)
365 {
366 containerResponseFilterRegistry = ((ResteasyProviderFactory)parent).getContainerResponseFilterRegistry().clone(this);
367 }
368 ((ContainerResponseFilterRegistry)containerResponseFilterRegistry).registerLegacy(provider);
369 newContracts.put(PostProcessInterceptor.class, 0);
370 }
371 if (isA(provider, MessageBodyWriterInterceptor.class, contracts))
372 {
373 if (provider.isAnnotationPresent(ServerInterceptor.class))
374 {
375 if (serverWriterInterceptorRegistry == null)
376 {
377 serverWriterInterceptorRegistry = ((ResteasyProviderFactory)parent).getServerWriterInterceptorRegistry().clone(this);
378 }
379 ((WriterInterceptorRegistry)serverWriterInterceptorRegistry).registerLegacy(provider);
380 }
381 if (provider.isAnnotationPresent(ClientInterceptor.class))
382 {
383 if (clientWriterInterceptorRegistry == null)
384 {
385 clientWriterInterceptorRegistry = ((ResteasyProviderFactory)parent).getClientWriterInterceptorRegistry().clone(this);
386 }
387 ((WriterInterceptorRegistry)clientWriterInterceptorRegistry).registerLegacy(provider);
388 }
389 if (!provider.isAnnotationPresent(ServerInterceptor.class)
390 && !provider.isAnnotationPresent(ClientInterceptor.class))
391 {
392 throw new RuntimeException(Messages.MESSAGES.interceptorClassMustBeAnnotated());
393 }
394 newContracts.put(MessageBodyWriterInterceptor.class, 0);
395
396 }
397 if (isA(provider, MessageBodyReaderInterceptor.class, contracts))
398 {
399 if (provider.isAnnotationPresent(ServerInterceptor.class))
400 {
401 if (serverReaderInterceptorRegistry == null)
402 {
403 serverReaderInterceptorRegistry = ((ResteasyProviderFactory)parent).getServerReaderInterceptorRegistry().clone(this);
404 }
405 ((ReaderInterceptorRegistry)serverReaderInterceptorRegistry).registerLegacy(provider);
406 }
407 if (provider.isAnnotationPresent(ClientInterceptor.class))
408 {
409 if (clientReaderInterceptorRegistry == null)
410 {
411 clientReaderInterceptorRegistry = ((ResteasyProviderFactory)parent).getClientReaderInterceptorRegistry().clone(this);
412 }
413 ((ReaderInterceptorRegistry)clientReaderInterceptorRegistry).registerLegacy(provider);
414 }
415 if (!provider.isAnnotationPresent(ServerInterceptor.class)
416 && !provider.isAnnotationPresent(ClientInterceptor.class))
417 {
418 throw new RuntimeException(Messages.MESSAGES.interceptorClassMustBeAnnotated());
419 }
420 newContracts.put(MessageBodyReaderInterceptor.class, 0);
421 }
422 }
423
424 @Override
425 protected void processProviderInstanceContracts(Object provider, Map<Class<?>, Integer> contracts,
426 Integer priorityOverride, boolean builtIn, Map<Class<?>, Integer> newContracts)
427 {
428 super.processProviderInstanceContracts(provider, contracts, priorityOverride, builtIn, newContracts);
429 if (isA(provider, ClientExceptionMapper.class, contracts))
430 {
431 try
432 {
433 addClientExceptionMapper((ClientExceptionMapper) provider);
434 newContracts.put(ClientExceptionMapper.class, 0);
435 }
436 catch (Exception e)
437 {
438 throw new RuntimeException(Messages.MESSAGES.unableToInstantiateExceptionMapper(), e);
439 }
440 }
441 if (isA(provider, ClientExecutionInterceptor.class, contracts))
442 {
443 if (clientExecutionInterceptorRegistry == null)
444 {
445 clientExecutionInterceptorRegistry = ((ResteasyProviderFactory)parent).getClientExecutionInterceptorRegistry().cloneTo(this);
446 }
447 clientExecutionInterceptorRegistry.register((ClientExecutionInterceptor) provider);
448 newContracts.put(ClientExecutionInterceptor.class, 0);
449 }
450 if (isA(provider, PreProcessInterceptor.class, contracts))
451 {
452 if (containerRequestFilterRegistry == null)
453 {
454 containerRequestFilterRegistry = ((ResteasyProviderFactory)parent).getContainerRequestFilterRegistry().clone(this);
455 }
456 ((ContainerRequestFilterRegistry)containerRequestFilterRegistry).registerLegacy((PreProcessInterceptor) provider);
457 newContracts.put(PreProcessInterceptor.class, 0);
458 }
459 if (isA(provider, PostProcessInterceptor.class, contracts))
460 {
461 if (containerResponseFilterRegistry == null)
462 {
463 containerResponseFilterRegistry = ((ResteasyProviderFactory)parent).getContainerResponseFilterRegistry().clone(this);
464 }
465 ((ContainerResponseFilterRegistry)containerResponseFilterRegistry).registerLegacy((PostProcessInterceptor) provider);
466 newContracts.put(PostProcessInterceptor.class, 0);
467 }
468 if (isA(provider, MessageBodyWriterInterceptor.class, contracts))
469 {
470 if (provider.getClass().isAnnotationPresent(ServerInterceptor.class))
471 {
472 if (serverWriterInterceptorRegistry == null)
473 {
474 serverWriterInterceptorRegistry = ((ResteasyProviderFactory)parent).getServerWriterInterceptorRegistry().clone(this);
475 }
476 ((WriterInterceptorRegistry)serverWriterInterceptorRegistry).registerLegacy((MessageBodyWriterInterceptor) provider);
477 }
478 if (provider.getClass().isAnnotationPresent(ClientInterceptor.class))
479 {
480 if (clientWriterInterceptorRegistry == null)
481 {
482 clientWriterInterceptorRegistry = ((ResteasyProviderFactory)parent).getClientWriterInterceptorRegistry().clone(this);
483 }
484 ((WriterInterceptorRegistry)clientWriterInterceptorRegistry).registerLegacy((MessageBodyWriterInterceptor) provider);
485 }
486 if (!provider.getClass().isAnnotationPresent(ServerInterceptor.class)
487 && !provider.getClass().isAnnotationPresent(ClientInterceptor.class))
488 {
489 throw new RuntimeException(Messages.MESSAGES.interceptorClassMustBeAnnotatedWithClass(provider.getClass()));
490 }
491 newContracts.put(MessageBodyWriterInterceptor.class, 0);
492 }
493 if (isA(provider, MessageBodyReaderInterceptor.class, contracts))
494 {
495 if (provider.getClass().isAnnotationPresent(ServerInterceptor.class))
496 {
497 if (serverReaderInterceptorRegistry == null)
498 {
499 serverReaderInterceptorRegistry = ((ResteasyProviderFactory)parent).getServerReaderInterceptorRegistry().clone(this);
500 }
501 ((ReaderInterceptorRegistry)serverReaderInterceptorRegistry).registerLegacy((MessageBodyReaderInterceptor) provider);
502 }
503 if (provider.getClass().isAnnotationPresent(ClientInterceptor.class))
504 {
505 if (clientReaderInterceptorRegistry == null)
506 {
507 clientReaderInterceptorRegistry = ((ResteasyProviderFactory)parent).getClientReaderInterceptorRegistry().clone(this);
508 }
509 ((ReaderInterceptorRegistry)clientReaderInterceptorRegistry).registerLegacy((MessageBodyReaderInterceptor) provider);
510 }
511 if (!provider.getClass().isAnnotationPresent(ServerInterceptor.class)
512 && !provider.getClass().isAnnotationPresent(ClientInterceptor.class))
513 {
514 throw new RuntimeException(Messages.MESSAGES.interceptorClassMustBeAnnotatedWithClass(provider.getClass()));
515 }
516 newContracts.put(MessageBodyReaderInterceptor.class, 0);
517
518 }
519 }
520
521 public <T extends Throwable> ClientExceptionMapper<T> getClientExceptionMapper(Class<T> type)
522 {
523 return getClientExceptionMappers().get(type);
524 }
525 }
+0
-655
resteasy-legacy/src/main/java/org/jboss/resteasy/spi/old/ThreadLocalResteasyProviderFactory.java less more
0 package org.jboss.resteasy.spi.old;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4 import java.util.Collection;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.Set;
8
9 import javax.ws.rs.RuntimeType;
10 import javax.ws.rs.client.ClientRequestFilter;
11 import javax.ws.rs.container.DynamicFeature;
12 import javax.ws.rs.core.Application;
13 import javax.ws.rs.core.Configuration;
14 import javax.ws.rs.core.Feature;
15 import javax.ws.rs.core.Link;
16 import javax.ws.rs.core.MediaType;
17 import javax.ws.rs.core.Response;
18 import javax.ws.rs.core.UriBuilder;
19 import javax.ws.rs.core.Variant;
20 import javax.ws.rs.ext.ContextResolver;
21 import javax.ws.rs.ext.ExceptionMapper;
22 import javax.ws.rs.ext.MessageBodyReader;
23 import javax.ws.rs.ext.MessageBodyWriter;
24 import javax.ws.rs.ext.ParamConverter;
25
26 import org.jboss.resteasy.client.core.ClientErrorInterceptor;
27 import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper;
28 import org.jboss.resteasy.core.interception.ClientResponseFilterRegistry;
29 import org.jboss.resteasy.core.interception.ContainerRequestFilterRegistry;
30 import org.jboss.resteasy.core.interception.ContainerResponseFilterRegistry;
31 import org.jboss.resteasy.core.interception.InterceptorRegistry;
32 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
33 import org.jboss.resteasy.core.interception.ReaderInterceptorRegistry;
34 import org.jboss.resteasy.core.interception.WriterInterceptorRegistry;
35 import org.jboss.resteasy.spi.ConstructorInjector;
36 import org.jboss.resteasy.spi.HttpRequest;
37 import org.jboss.resteasy.spi.HttpResponse;
38 import org.jboss.resteasy.spi.InjectorFactory;
39 import org.jboss.resteasy.spi.ProviderFactoryDelegate;
40 import org.jboss.resteasy.spi.ResteasyProviderFactory;
41 import org.jboss.resteasy.spi.StringConverter;
42 import org.jboss.resteasy.spi.StringParameterUnmarshaller;
43 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
44 import org.jboss.resteasy.util.ThreadLocalStack;
45
46 /**
47 * Allow applications to push/pop provider factories onto the stack
48 *
49 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
50 * @version $Revision: 1 $
51 */
52 public class ThreadLocalResteasyProviderFactory extends org.jboss.resteasy.spi.old.ResteasyProviderFactory implements ProviderFactoryDelegate
53 {
54 private static final ThreadLocalStack<ResteasyProviderFactory> delegate = new ThreadLocalStack<ResteasyProviderFactory>();
55
56 private ResteasyProviderFactory defaultFactory;
57
58
59 public ThreadLocalResteasyProviderFactory(ResteasyProviderFactory defaultFactory)
60 {
61 this.defaultFactory = defaultFactory;
62 }
63
64 public ResteasyProviderFactory getDelegate()
65 {
66 ResteasyProviderFactory factory = delegate.get();
67 if (factory == null) return defaultFactory;
68 return factory;
69 }
70
71 private org.jboss.resteasy.spi.old.ResteasyProviderFactory getOldDelegate() {
72 return (org.jboss.resteasy.spi.old.ResteasyProviderFactory)getDelegate();
73 }
74
75 @Override
76 protected void initialize()
77 {
78
79 }
80
81 @Override
82 public MediaType getConcreteMediaTypeFromMessageBodyWriters(Class type, Type genericType, Annotation[] annotations, MediaType mediaType)
83 {
84 return super.getConcreteMediaTypeFromMessageBodyWriters(type, genericType, annotations, mediaType);
85 }
86
87 @Override
88 public HeaderDelegate getHeaderDelegate(Class<?> aClass)
89 {
90 return getDelegate().getHeaderDelegate(aClass);
91 }
92
93 @Override
94 public <T> T injectedInstance(Class<? extends T> clazz, HttpRequest request, HttpResponse response)
95 {
96 return getDelegate().injectedInstance(clazz, request, response);
97 }
98
99 @Override
100 public void injectProperties(Object obj, HttpRequest request, HttpResponse response)
101 {
102 getDelegate().injectProperties(obj, request, response);
103 }
104
105 public static void push(ResteasyProviderFactory factory)
106 {
107 delegate.push(factory);
108 }
109
110 public static void pop()
111 {
112 delegate.pop();
113 }
114
115 @Override
116 public ContainerResponseFilterRegistry getContainerResponseFilterRegistry()
117 {
118 return (ContainerResponseFilterRegistry)getOldDelegate().getContainerResponseFilterRegistry();
119 }
120
121 @Override
122 public ReaderInterceptorRegistry getServerReaderInterceptorRegistry()
123 {
124 return (ReaderInterceptorRegistry)getDelegate().getServerReaderInterceptorRegistry();
125 }
126
127 @Override
128 public Variant.VariantListBuilder createVariantListBuilder()
129 {
130 return getDelegate().createVariantListBuilder();
131 }
132
133 @Override
134 public List<ContextResolver> getContextResolvers(Class<?> clazz, MediaType type)
135 {
136 return getDelegate().getContextResolvers(clazz, type);
137 }
138
139 @Override
140 public boolean isBuiltinsRegistered()
141 {
142 return getDelegate().isBuiltinsRegistered();
143 }
144
145 @Override
146 public <T extends Throwable> ClientExceptionMapper<T> getClientExceptionMapper(Class<T> type)
147 {
148 return getOldDelegate().getClientExceptionMapper(type);
149 }
150
151 @Override
152 public Set<Class<?>> getFeatureClasses()
153 {
154 return getDelegate().getFeatureClasses();
155 }
156
157 @Override
158 public void setBuiltinsRegistered(boolean builtinsRegistered)
159 {
160 getDelegate().setBuiltinsRegistered(builtinsRegistered);
161 }
162
163 @Override
164 public void addClientExceptionMapper(Class<? extends ClientExceptionMapper<?>> providerClass)
165 {
166 getOldDelegate().addClientExceptionMapper(providerClass);
167 }
168
169 @Override
170 public ResteasyProviderFactory register(Class<?> providerClass)
171 {
172 return getDelegate().register(providerClass);
173 }
174
175 @Override
176 public Set<DynamicFeature> getClientDynamicFeatures()
177 {
178 return getDelegate().getClientDynamicFeatures();
179 }
180
181 @Override
182 public ResteasyProviderFactory register(Class<?> componentClass, Map<Class<?>, Integer> contracts)
183 {
184 return getDelegate().register(componentClass, contracts);
185 }
186
187 @Override
188 public Collection<Feature> getEnabledFeatures()
189 {
190 return getDelegate().getEnabledFeatures();
191 }
192
193 @Override
194 public Response.ResponseBuilder createResponseBuilder()
195 {
196 return getDelegate().createResponseBuilder();
197 }
198
199 @Override
200 public void registerProviderInstance(Object provider)
201 {
202 getDelegate().registerProviderInstance(provider);
203 }
204
205 @Override
206 public void addClientExceptionMapper(ClientExceptionMapper<?> provider, Type exceptionType)
207 {
208 getOldDelegate().addClientExceptionMapper(provider, exceptionType);
209 }
210
211 @Override
212 public StringConverter getStringConverter(Class<?> clazz)
213 {
214 return getDelegate().getStringConverter(clazz);
215 }
216
217 @Override
218 public <T> StringParameterUnmarshaller<T> createStringParameterUnmarshaller(Class<T> clazz)
219 {
220 return getDelegate().createStringParameterUnmarshaller(clazz);
221 }
222
223 @Override
224 public Set<Object> getFeatureInstances()
225 {
226 return getDelegate().getFeatureInstances();
227 }
228
229 @Override
230 public void addClientExceptionMapper(ClientExceptionMapper<?> provider)
231 {
232 getOldDelegate().addClientExceptionMapper(provider);
233 }
234
235 @Override
236 public void setInjectorFactory(InjectorFactory injectorFactory)
237 {
238 getDelegate().setInjectorFactory(injectorFactory);
239 }
240
241 @Override
242 public Set<Object> getInstances()
243 {
244 return getDelegate().getInstances();
245 }
246
247 @Override
248 public boolean isRegistered(Object component)
249 {
250 return getDelegate().isRegistered(component);
251 }
252
253 @Override
254 public ResteasyProviderFactory register(Class<?> componentClass, int priority)
255 {
256 return getDelegate().register(componentClass, priority);
257 }
258
259 @Override
260 public <T> ContextResolver<T> getContextResolver(Class<T> contextType, MediaType mediaType)
261 {
262 return getDelegate().getContextResolver(contextType, mediaType);
263 }
264
265 @Override
266 public InterceptorRegistry<ClientExecutionInterceptor> getClientExecutionInterceptorRegistry()
267 {
268 return getOldDelegate().getClientExecutionInterceptorRegistry();
269 }
270
271 @Override
272 public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
273 {
274 return getDelegate().getMessageBodyReader(type, genericType, annotations, mediaType);
275 }
276
277 @Override
278 public void registerProvider(Class provider, Integer priorityOverride, boolean isBuiltin, Map<Class<?>, Integer> contracts)
279 {
280 getDelegate().registerProvider(provider, priorityOverride, isBuiltin, contracts);
281 }
282
283 @Override
284 public Map<Class<?>, Map<Class<?>, Integer>> getClassContracts()
285 {
286 return getDelegate().getClassContracts();
287 }
288
289 @Override
290 public ContainerRequestFilterRegistry getContainerRequestFilterRegistry()
291 {
292 return (ContainerRequestFilterRegistry)getDelegate().getContainerRequestFilterRegistry();
293 }
294
295 @Override
296 public ResteasyProviderFactory register(Object component, Map<Class<?>, Integer> contracts)
297 {
298 return getDelegate().register(component, contracts);
299 }
300
301 @Override
302 public boolean isRegisterBuiltins()
303 {
304 return getDelegate().isRegisterBuiltins();
305 }
306
307 @Override
308 public ReaderInterceptorRegistry getClientReaderInterceptorRegistry()
309 {
310 return (ReaderInterceptorRegistry)getDelegate().getClientReaderInterceptorRegistry();
311 }
312
313 @Override
314 public void setRegisterBuiltins(boolean registerBuiltins)
315 {
316 getDelegate().setRegisterBuiltins(registerBuiltins);
317 }
318
319 @Override
320 public ResteasyProviderFactory register(Object component, int priority)
321 {
322 return getDelegate().register(component, priority);
323 }
324
325 @Override
326 public void addClientErrorInterceptor(ClientErrorInterceptor handler)
327 {
328 getOldDelegate().addClientErrorInterceptor(handler);
329 }
330
331 @Override
332 public void registerProvider(Class provider, boolean isBuiltin)
333 {
334 getDelegate().registerProvider(provider, isBuiltin);
335 }
336
337 @Override
338 public Collection<String> getPropertyNames()
339 {
340 return getDelegate().getPropertyNames();
341 }
342
343 @Override
344 public void addClientExceptionMapper(ClientExceptionMapper<?> provider, Class<?> providerClass)
345 {
346 getOldDelegate().addClientExceptionMapper(provider, providerClass);
347 }
348
349 @Override
350 public void insertInterceptorPrecedenceAfter(String after, String newPrecedence)
351 {
352 getOldDelegate().insertInterceptorPrecedenceAfter(after, newPrecedence);
353 }
354
355 @Override
356 public ResteasyProviderFactory register(Object provider)
357 {
358 return getDelegate().register(provider);
359 }
360
361 @Override
362 public <T> ConstructorInjector createConstructorInjector(Class<? extends T> clazz)
363 {
364 return getDelegate().createConstructorInjector(clazz);
365 }
366
367 @Override
368 public <T> T createProviderInstance(Class<? extends T> clazz)
369 {
370 return getDelegate().createProviderInstance(clazz);
371 }
372
373 @Override
374 public boolean isRegistered(Class<?> componentClass)
375 {
376 return getDelegate().isRegistered(componentClass);
377 }
378
379 @Override
380 public void insertInterceptorPrecedenceBefore(String before, String newPrecedence)
381 {
382 getOldDelegate().insertInterceptorPrecedenceBefore(before, newPrecedence);
383 }
384
385 @Override
386 public <T> T createEndpoint(Application applicationConfig, Class<T> endpointType) throws IllegalArgumentException, UnsupportedOperationException
387 {
388 return getDelegate().createEndpoint(applicationConfig, endpointType);
389 }
390
391 @Override
392 public Map<String, Object> getMutableProperties()
393 {
394 return getDelegate().getMutableProperties();
395 }
396
397 @Override
398 public Set<DynamicFeature> getServerDynamicFeatures()
399 {
400 return getDelegate().getServerDynamicFeatures();
401 }
402
403 @Override
404 public boolean isEnabled(Feature feature)
405 {
406 return getDelegate().isEnabled(feature);
407 }
408
409 @Override
410 public Object getProperty(String name)
411 {
412 return getDelegate().getProperty(name);
413 }
414
415 @Override
416 public WriterInterceptorRegistry getServerWriterInterceptorRegistry()
417 {
418 return (WriterInterceptorRegistry)getDelegate().getServerWriterInterceptorRegistry();
419 }
420
421 @Override
422 public ResteasyProviderFactory setProperties(Map<String, ?> properties)
423 {
424 return getDelegate().setProperties(properties);
425 }
426
427 @Override
428 public List<ClientErrorInterceptor> getClientErrorInterceptors()
429 {
430 return getOldDelegate().getClientErrorInterceptors();
431 }
432
433 @Override
434 public void injectProperties(Class declaring, Object obj)
435 {
436 getDelegate().injectProperties(declaring, obj);
437 }
438
439 @Override
440 public UriBuilder createUriBuilder()
441 {
442 return getDelegate().createUriBuilder();
443 }
444
445 @Override
446 public ResteasyProviderFactory register(Class<?> componentClass, Class<?>... contracts)
447 {
448 return getDelegate().register(componentClass, contracts);
449 }
450
451 @Override
452 public <T> T injectedInstance(Class<? extends T> clazz)
453 {
454 return getDelegate().injectedInstance(clazz);
455 }
456
457 @Override
458 public void appendInterceptorPrecedence(String precedence)
459 {
460 getOldDelegate().appendInterceptorPrecedence(precedence);
461 }
462
463 @Override
464 public ResteasyProviderFactory getParent()
465 {
466 return getDelegate().getParent();
467 }
468
469 @Override
470 public RuntimeType getRuntimeType()
471 {
472 return getDelegate().getRuntimeType();
473 }
474
475 @Override
476 public void injectProperties(Object obj)
477 {
478 getDelegate().injectProperties(obj);
479 }
480
481 @Override
482 public ResteasyProviderFactory property(String name, Object value)
483 {
484 return getDelegate().property(name, value);
485 }
486
487 @Override
488 public WriterInterceptorRegistry getClientWriterInterceptorRegistry()
489 {
490 return (WriterInterceptorRegistry)getDelegate().getClientWriterInterceptorRegistry();
491 }
492
493 @Override
494 public InjectorFactory getInjectorFactory()
495 {
496 return getDelegate().getInjectorFactory();
497 }
498
499 @Override
500 public Map<Class<?>, Integer> getContracts(Class<?> componentClass)
501 {
502 return getDelegate().getContracts(componentClass);
503 }
504
505 @Override
506 public ParamConverter getParamConverter(Class clazz, Type genericType, Annotation[] annotations)
507 {
508 return getDelegate().getParamConverter(clazz, genericType, annotations);
509 }
510
511 @Override
512 public ClientResponseFilterRegistry getClientResponseFilters()
513 {
514 return (ClientResponseFilterRegistry)getDelegate().getClientResponseFilters();
515 }
516
517 @Override
518 public ResteasyProviderFactory register(Object component, Class<?>... contracts)
519 {
520 return getDelegate().register(component, contracts);
521 }
522
523 @Override
524 public Set<Class<?>> getClasses()
525 {
526 return getDelegate().getClasses();
527 }
528
529 @Override
530 public boolean isEnabled(Class<? extends Feature> featureClass)
531 {
532 return getDelegate().isEnabled(featureClass);
533 }
534
535 @Override
536 public void registerProvider(Class provider)
537 {
538 getDelegate().registerProvider(provider);
539 }
540
541 @Override
542 public void addHeaderDelegate(Class clazz, HeaderDelegate header)
543 {
544 getDelegate().addHeaderDelegate(clazz, header);
545 }
546
547 @Override
548 public void registerProviderInstance(Object provider, Map<Class<?>, Integer> contracts, Integer defaultPriority, boolean builtIn)
549 {
550 getDelegate().registerProviderInstance(provider, contracts, defaultPriority, builtIn);
551 }
552
553 @Override
554 public void addStringParameterUnmarshaller(Class<? extends StringParameterUnmarshaller> provider)
555 {
556 getDelegate().addStringParameterUnmarshaller(provider);
557 }
558
559 @Override
560 public Set<Class<?>> getProviderClasses()
561 {
562 return getDelegate().getProviderClasses();
563 }
564
565 @Override
566 public String toString(Object object, Class clazz, Type genericType, Annotation[] annotations)
567 {
568 return getDelegate().toString(object, clazz, genericType, annotations);
569 }
570
571 @Override
572 public JaxrsInterceptorRegistry<ClientRequestFilter> getClientRequestFilters()
573 {
574 return (JaxrsInterceptorRegistry)getDelegate().getClientRequestFilters();
575 }
576
577 @Override
578 public Map<String, Object> getProperties()
579 {
580 return getDelegate().getProperties();
581 }
582
583 @Override
584 public String toHeaderString(Object object)
585 {
586 return getDelegate().toHeaderString(object);
587 }
588
589 @Override
590 public Link.Builder createLinkBuilder()
591 {
592 return getDelegate().createLinkBuilder();
593 }
594
595 @Override
596 public Set<Object> getProviderInstances()
597 {
598 return getDelegate().getProviderInstances();
599 }
600
601 @Override
602 public Configuration getConfiguration()
603 {
604 return getDelegate().getConfiguration();
605 }
606
607 @Override
608 public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
609 {
610 return getDelegate().getMessageBodyWriter(type, genericType, annotations, mediaType);
611 }
612
613 @Override
614 public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type)
615 {
616 return getDelegate().getExceptionMapper(type);
617 }
618
619 @Override
620 public Map<Class<?>, ExceptionMapper> getExceptionMappers()
621 {
622 return getDelegate().getExceptionMappers();
623 }
624
625 @Override
626 public <T> HeaderDelegate<T> createHeaderDelegate(Class<T> tClass)
627 {
628 return getDelegate().createHeaderDelegate(tClass);
629 }
630
631 @Override
632 public <T> MessageBodyWriter<T> getClientMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
633 {
634 return getDelegate().getClientMessageBodyWriter(type, genericType, annotations, mediaType);
635 }
636
637 @Override
638 public <T> MessageBodyReader<T> getClientMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
639 {
640 return getDelegate().getClientMessageBodyReader(type, genericType, annotations, mediaType);
641 }
642
643 @Override
644 public <T> MessageBodyReader<T> getServerMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
645 {
646 return getDelegate().getServerMessageBodyReader(type, genericType, annotations, mediaType);
647 }
648
649 @Override
650 public <T> MessageBodyWriter<T> getServerMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType)
651 {
652 return getDelegate().getServerMessageBodyWriter(type, genericType, annotations, mediaType);
653 }
654 }
+0
-1
resteasy-legacy/src/main/resources/META-INF/services/javax.ws.rs.ext.RuntimeDelegate less more
0 org.jboss.resteasy.spi.old.ResteasyProviderFactory
55 <parent>
66 <artifactId>resteasy-jaxrs-all</artifactId>
77 <groupId>org.jboss.resteasy</groupId>
8 <version>3.1.4.Final</version>
8 <version>3.5.0.Final</version>
99 </parent>
1010
1111 <artifactId>resteasy-links</artifactId>
2020 </dependency>
2121 <dependency>
2222 <groupId>org.jboss.spec.javax.ws.rs</groupId>
23 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
23 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
2424 </dependency>
2525 <dependency>
2626 <groupId>org.hibernate.javax.persistence</groupId>
33 import org.jboss.resteasy.links.AddLinks;
44 import org.jboss.resteasy.spi.Registry;
55 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.spi.DecoratorProcessor;
6 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
77
88 import javax.ws.rs.core.MediaType;
99 import javax.ws.rs.core.UriInfo;
77
88 import org.apache.http.client.HttpClient;
99 import org.apache.http.impl.client.DefaultHttpClient;
10 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
11 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
12 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
10 import org.jboss.resteasy.client.ProxyFactory;
11 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
1312 import org.jboss.resteasy.core.Dispatcher;
1413 import org.jboss.resteasy.links.RESTServiceDiscovery;
1514 import org.jboss.resteasy.links.RESTServiceDiscovery.AtomLink;
6968 POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType);
7069 dispatcher.getRegistry().addResourceFactory(noDefaults);
7170 httpClient = new DefaultHttpClient();
72 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
71 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
7372 url = generateBaseUrl();
74 ResteasyWebTarget target = new ResteasyClientBuilder().httpEngine(engine).build().target(url);
75 client = target.proxy(BookStoreService.class);
73 client = ProxyFactory.create(BookStoreService.class, url,
74 executor);
7675 }
7776
7877 @After
55
66 import org.apache.http.client.HttpClient;
77 import org.apache.http.impl.client.DefaultHttpClient;
8 import org.jboss.resteasy.client.ProxyFactory;
9 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
810 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
911 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
1012 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
114116 Assert.assertEquals("self", link.getRel());
115117 Assert.assertEquals(url + relativeUrl, link.getHref());
116118 }
117 }
119 }
77
88 import org.apache.http.client.HttpClient;
99 import org.apache.http.impl.client.DefaultHttpClient;
10 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
11 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
12 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
10 import org.jboss.resteasy.client.ProxyFactory;
11 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
1312 import org.jboss.resteasy.core.Dispatcher;
1413 import org.jboss.resteasy.links.RESTServiceDiscovery;
1514 import org.jboss.resteasy.links.RESTServiceDiscovery.AtomLink;
6968 POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType);
7069 dispatcher.getRegistry().addResourceFactory(noDefaults);
7170 httpClient = new DefaultHttpClient();
72 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
71 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
7372 url = generateBaseUrl();
74 ResteasyWebTarget target = new ResteasyClientBuilder().httpEngine(engine).build().target(url);
75 client = target.proxy(BookStoreService.class);
73 client = ProxyFactory.create(BookStoreService.class, url,
74 executor);
7675 }
7776
7877 @After
1515 import org.apache.http.impl.client.BasicAuthCache;
1616 import org.apache.http.impl.client.DefaultHttpClient;
1717 import org.apache.http.protocol.BasicHttpContext;
18 import org.apache.http.protocol.HttpContext;
19 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
20 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
21 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
22 import org.jboss.resteasy.client.jaxrs.engines.HttpContextProvider;
18 import org.jboss.resteasy.client.ProxyFactory;
19 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
2320 import org.jboss.resteasy.core.Dispatcher;
2421 import org.jboss.resteasy.links.RESTServiceDiscovery;
2522 import org.jboss.resteasy.plugins.server.embedded.SecurityDomain;
9592 dispatcher.getRegistry().addResourceFactory(noDefaults);
9693 url = generateBaseUrl();
9794
95 // Configure HttpClient to authenticate preemptively
96 // by prepopulating the authentication data cache.
97 // 1. Create AuthCache instance
98 AuthCache authCache = new BasicAuthCache();
99 // 2. Generate BASIC scheme object and add it to the local auth cache
100 BasicScheme basicAuth = new BasicScheme();
101 authCache.put(getHttpHost(url), basicAuth);
102 // 3. Add AuthCache to the execution context
103 BasicHttpContext localContext = new BasicHttpContext();
104 localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
105
98106 httpClient = new DefaultHttpClient();
99 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, new HttpContextProvider() {
100 @Override
101 public HttpContext getContext() {
102 // Configure HttpClient to authenticate preemptively
103 // by prepopulating the authentication data cache.
104 // 1. Create AuthCache instance
105 AuthCache authCache = new BasicAuthCache();
106 // 2. Generate BASIC scheme object and add it to the local auth cache
107 BasicScheme basicAuth = new BasicScheme();
108 authCache.put(getHttpHost(url), basicAuth);
109 // 3. Add AuthCache to the execution context
110 BasicHttpContext localContext = new BasicHttpContext();
111 localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
112 return localContext;
113 }
114 });
115 ResteasyWebTarget target = new ResteasyClientBuilder().httpEngine(engine).build().target(url);
116 client = target.proxy(BookStoreService.class);
107 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient, localContext);
108 client = ProxyFactory.create(BookStoreService.class, url, executor);
117109 }
118110
119111 @After
99
1010 import org.apache.http.client.HttpClient;
1111 import org.apache.http.impl.client.DefaultHttpClient;
12 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
13 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
14 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
12 import org.jboss.resteasy.client.ClientResponseFailure;
13 import org.jboss.resteasy.client.ProxyFactory;
14 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
1515 import org.jboss.resteasy.core.Dispatcher;
1616 import org.jboss.resteasy.links.test.BookStoreService;
1717 import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
7373 POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType);
7474 dispatcher.getRegistry().addResourceFactory(noDefaults);
7575 httpClient = new DefaultHttpClient();
76 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
76 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
7777 url = generateBaseUrl();
78 ResteasyWebTarget target = new ResteasyClientBuilder().httpEngine(engine).build().target(url);
79 client = target.proxy(BookStoreService.class);
78 client = ProxyFactory.create(BookStoreService.class, url,
79 executor);
8080 }
8181
8282 @After
9494 try{
9595 client.getBookXML("foo");
9696 Assert.fail("This should have caused a 500");
97 }catch(InternalServerErrorException x){
98 System.err.println("Failure is "+x.getResponse().readEntity(String.class));
97 }catch(ClientResponseFailure x){
98 System.err.println("Failure is "+x.getResponse().getEntity(String.class));
9999 Assert.assertEquals(500, x.getResponse().getStatus());
100 }catch(Exception x){
101 Assert.fail("Expected InternalServerErrorException");
102 }
100 }
103101 }
104102 @SuppressWarnings("unchecked")
105103 @Test
108106 try{
109107 client.getBookJSON("foo");
110108 Assert.fail("This should have caused a 500");
111 }catch(InternalServerErrorException x){
112 System.err.println("Failure is "+x.getResponse().readEntity(String.class));
109 }catch(ClientResponseFailure x){
110 System.err.println("Failure is "+x.getResponse().getEntity(String.class));
113111 Assert.assertEquals(500, x.getResponse().getStatus());
114 }catch(Exception x){
115 Assert.fail("Expected InternalServerErrorException");
116112 }
117113 }
118 }
114 }
77
88 import org.apache.http.client.HttpClient;
99 import org.apache.http.impl.client.DefaultHttpClient;
10 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
11 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
12 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
10 import org.jboss.resteasy.client.ProxyFactory;
11 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
1312 import org.jboss.resteasy.core.Dispatcher;
1413 import org.jboss.resteasy.links.RESTServiceDiscovery;
1514 import org.jboss.resteasy.links.RESTServiceDiscovery.AtomLink;
7473 POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType);
7574 dispatcher.getRegistry().addResourceFactory(noDefaults);
7675 httpClient = new DefaultHttpClient();
77 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
76 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
7877 url = generateBaseUrl();
79 ResteasyWebTarget target = new ResteasyClientBuilder().httpEngine(engine).build().target(url);
80 client = target.proxy(BookStoreService.class);
78 client = ProxyFactory.create(BookStoreService.class, url,
79 executor);
8180 }
8281
8382 @After
109108 Assert.assertNotNull(atomLink);
110109 Assert.assertEquals(url+"/book/foo", atomLink.getHref());
111110 }
112 }
111 }
0 <?xml version="1.0"?>
1 <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
3 <modelVersion>4.0.0</modelVersion>
4 <parent>
5 <groupId>org.jboss.resteasy</groupId>
6 <artifactId>resteasy-jaxrs-all</artifactId>
7 <version>3.5.0.Final</version>
8 </parent>
9 <artifactId>resteasy-rxjava</artifactId>
10 <name>RESTEasy RxJava integration</name>
11 <url>http://maven.apache.org</url>
12 <properties>
13 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
14 </properties>
15 <dependencies>
16 <dependency>
17 <groupId>junit</groupId>
18 <artifactId>junit</artifactId>
19 <scope>test</scope>
20 </dependency>
21 <dependency>
22 <groupId>org.jboss.resteasy</groupId>
23 <artifactId>resteasy-client</artifactId>
24 <version>${project.version}</version>
25 <scope>test</scope>
26 </dependency>
27 <dependency>
28 <groupId>org.jboss.resteasy</groupId>
29 <artifactId>resteasy-netty4</artifactId>
30 <version>${project.version}</version>
31 <scope>test</scope>
32 </dependency>
33 <dependency>
34 <groupId>org.jboss.resteasy</groupId>
35 <artifactId>resteasy-jackson2-provider</artifactId>
36 <version>${project.version}</version>
37 <scope>test</scope>
38 </dependency>
39 <dependency>
40 <groupId>org.jboss.resteasy</groupId>
41 <artifactId>resteasy-jaxb-provider</artifactId>
42 <version>${project.version}</version>
43 <scope>test</scope>
44 </dependency>
45 <dependency>
46 <groupId>org.jboss.resteasy</groupId>
47 <artifactId>resteasy-jaxrs</artifactId>
48 <version>${project.version}</version>
49 </dependency>
50 <dependency>
51 <groupId>io.reactivex</groupId>
52 <artifactId>rxjava-reactive-streams</artifactId>
53 <version>1.2.1</version>
54 </dependency>
55 <dependency>
56 <groupId>io.reactivex</groupId>
57 <artifactId>rxjava</artifactId>
58 <version>1.3.2</version>
59 </dependency>
60 </dependencies>
61 </project>
0 package org.jboss.resteasy.rxjava;
1
2 import javax.ws.rs.ext.Provider;
3
4 import org.jboss.resteasy.spi.AsyncStreamProvider;
5 import org.reactivestreams.Publisher;
6
7 import rx.Observable;
8 import rx.RxReactiveStreams;
9 import rx.plugins.RxJavaHooks;
10
11 @Provider
12 public class ObservableProvider implements AsyncStreamProvider<Observable<?>>
13 {
14
15 static
16 {
17 RxJavaHooks.setOnObservableCreate(new ResteasyContextPropagatingOnObservableCreateAction());
18 }
19
20 @Override
21 public Publisher<?> toAsyncStream(Observable<?> asyncResponse)
22 {
23 return RxReactiveStreams.toPublisher(asyncResponse);
24 }
25
26 }
0 package org.jboss.resteasy.rxjava;
1
2 import java.util.Map;
3
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import rx.Observable.OnSubscribe;
7 import rx.Subscriber;
8 import rx.functions.Func1;
9
10 @SuppressWarnings("rawtypes")
11 public class ResteasyContextPropagatingOnObservableCreateAction implements Func1<OnSubscribe, OnSubscribe>
12 {
13
14 @SuppressWarnings("unchecked")
15 @Override
16 public OnSubscribe<?> call(OnSubscribe t)
17 {
18 return new ContextCapturerObservable<>(t);
19 }
20
21 final static class ContextCapturerObservable<T> implements OnSubscribe<T>
22 {
23
24 final Map<Class<?>, Object> contextDataMap = ResteasyProviderFactory.getContextDataMap();
25
26 final OnSubscribe<T> source;
27
28 public ContextCapturerObservable(OnSubscribe<T> source)
29 {
30 this.source = source;
31 }
32
33 @Override
34 public void call(Subscriber<? super T> t)
35 {
36 source.call(new OnAssemblyObservableSubscriber<T>(t, contextDataMap));
37 }
38
39 static final class OnAssemblyObservableSubscriber<T> extends Subscriber<T>
40 {
41
42 final Subscriber<? super T> actual;
43
44 final Map<Class<?>, Object> contextDataMap;
45
46 public OnAssemblyObservableSubscriber(Subscriber<? super T> actual, Map<Class<?>, Object> contextDataMap)
47 {
48 this.actual = actual;
49 this.contextDataMap = contextDataMap;
50 actual.add(this);
51 }
52
53 @Override
54 public void onError(Throwable e)
55 {
56 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
57 actual.onError(e);
58 ResteasyProviderFactory.removeContextDataLevel();
59 }
60
61 @Override
62 public void onNext(T t)
63 {
64 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
65 actual.onNext(t);
66 ResteasyProviderFactory.removeContextDataLevel();
67 }
68
69 @Override
70 public void onCompleted()
71 {
72 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
73 actual.onCompleted();
74 ResteasyProviderFactory.removeContextDataLevel();
75 }
76 }
77 }
78
79 }
0 package org.jboss.resteasy.rxjava;
1
2 import java.util.Map;
3
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import rx.Single;
7 import rx.Single.OnSubscribe;
8 import rx.SingleSubscriber;
9 import rx.functions.Func1;
10
11 @SuppressWarnings("rawtypes")
12 public class ResteasyContextPropagatingOnSingleCreateAction implements Func1<OnSubscribe, OnSubscribe>
13 {
14
15 @SuppressWarnings("unchecked")
16 @Override
17 public OnSubscribe<?> call(OnSubscribe t)
18 {
19 return new ContextCapturerSingle<>(t);
20 }
21
22 final static class ContextCapturerSingle<T> implements Single.OnSubscribe<T>
23 {
24
25 final Map<Class<?>, Object> contextDataMap = ResteasyProviderFactory.getContextDataMap();
26
27 final Single.OnSubscribe<T> source;
28
29 public ContextCapturerSingle(Single.OnSubscribe<T> source)
30 {
31 this.source = source;
32 }
33
34 @Override
35 public void call(SingleSubscriber<? super T> t)
36 {
37 source.call(new OnAssemblySingleSubscriber<T>(t, contextDataMap));
38 }
39
40 static final class OnAssemblySingleSubscriber<T> extends SingleSubscriber<T>
41 {
42
43 final SingleSubscriber<? super T> actual;
44
45 final Map<Class<?>, Object> contextDataMap;
46
47 public OnAssemblySingleSubscriber(SingleSubscriber<? super T> actual, Map<Class<?>, Object> contextDataMap)
48 {
49 this.actual = actual;
50 this.contextDataMap = contextDataMap;
51 actual.add(this);
52 }
53
54 @Override
55 public void onError(Throwable e)
56 {
57 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
58 actual.onError(e);
59 ResteasyProviderFactory.removeContextDataLevel();
60 }
61
62 @Override
63 public void onSuccess(T t)
64 {
65 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
66 actual.onSuccess(t);
67 ResteasyProviderFactory.removeContextDataLevel();
68 }
69 }
70 }
71
72 }
0 package org.jboss.resteasy.rxjava;
1
2 import java.util.concurrent.CompletableFuture;
3 import java.util.concurrent.CompletionStage;
4
5 import javax.ws.rs.ext.Provider;
6
7 import org.jboss.resteasy.spi.AsyncResponseProvider;
8
9 import rx.Single;
10 import rx.Subscription;
11 import rx.plugins.RxJavaHooks;
12
13 @Provider
14 public class SingleProvider implements AsyncResponseProvider<Single<?>>
15 {
16
17 static
18 {
19 RxJavaHooks.setOnSingleCreate(new ResteasyContextPropagatingOnSingleCreateAction());
20 }
21
22 private static class SingleAdaptor<T> extends CompletableFuture<T>
23 {
24 private Subscription subscription;
25
26 public SingleAdaptor(Single<T> observable)
27 {
28 this.subscription = observable.subscribe(this::complete, this::completeExceptionally);
29 }
30
31 @Override
32 public boolean cancel(boolean mayInterruptIfRunning)
33 {
34 subscription.unsubscribe();
35 return super.cancel(mayInterruptIfRunning);
36 }
37 }
38
39 @Override
40 public CompletionStage<?> toCompletionStage(Single<?> asyncResponse)
41 {
42 return new SingleAdaptor<>(asyncResponse);
43 }
44
45 }
0 org.jboss.resteasy.rxjava.SingleProvider
1 org.jboss.resteasy.rxjava.ObservableProvider
0 package org.jboss.resteasy.rxjava;
1
2 import java.util.concurrent.ExecutorService;
3 import java.util.concurrent.Executors;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.UriInfo;
11
12 import rx.Emitter.BackpressureMode;
13 import rx.Observable;
14 import rx.Single;
15
16 @Path("/")
17 public class RxResource
18 {
19
20 @Path("single")
21 @GET
22 public Single<String> single()
23 {
24 return Single.just("got it");
25 }
26
27 @Produces(MediaType.APPLICATION_JSON)
28 @Path("observable")
29 @GET
30 public Observable<String> observable()
31 {
32 return Observable.from(new String[]
33 {"one", "two"});
34 }
35
36 @Path("context/single")
37 @GET
38 public Single<String> contextSingle(@Context UriInfo uriInfo)
39 {
40 return Single.<String>fromEmitter(foo -> {
41 ExecutorService executor = Executors.newSingleThreadExecutor();
42 executor.submit(new Runnable()
43 {
44 public void run()
45 {
46 foo.onSuccess("got it");
47 }
48 });
49 }).map(str -> {
50 uriInfo.getAbsolutePath();
51 return str;
52 });
53 }
54
55 @Produces(MediaType.APPLICATION_JSON)
56 @Path("context/observable")
57 @GET
58 public Observable<String> contextObservable(@Context UriInfo uriInfo)
59 {
60 return Observable.<String>create(foo -> {
61 ExecutorService executor = Executors.newSingleThreadExecutor();
62 executor.submit(new Runnable()
63 {
64 public void run()
65 {
66 foo.onNext("one");
67 foo.onNext("two");
68 foo.onCompleted();
69 }
70 });
71 }, BackpressureMode.BUFFER).map(str -> {
72 uriInfo.getAbsolutePath();
73 return str;
74 });
75 }
76 }
0 package org.jboss.resteasy.rxjava;
1
2 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
3 import static org.junit.Assert.*;
4
5 import java.util.concurrent.TimeUnit;
6
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.core.Dispatcher;
10 import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
11 import org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory;
12 import org.jboss.resteasy.test.TestPortProvider;
13 import org.junit.After;
14 import org.junit.AfterClass;
15 import org.junit.Before;
16 import org.junit.BeforeClass;
17 import org.junit.Test;
18
19 public class RxTest
20 {
21 private static NettyJaxrsServer server;
22
23 private static Dispatcher dispatcher;
24
25 @BeforeClass
26 public static void beforeClass() throws Exception
27 {
28 server = new NettyJaxrsServer();
29 server.setPort(TestPortProvider.getPort());
30 server.setRootResourcePath("/");
31 server.start();
32 dispatcher = server.getDeployment().getDispatcher();
33 POJOResourceFactory noDefaults = new POJOResourceFactory(RxResource.class);
34 dispatcher.getRegistry().addResourceFactory(noDefaults);
35 }
36
37 @AfterClass
38 public static void afterClass() throws Exception
39 {
40 server.stop();
41 server = null;
42 dispatcher = null;
43 }
44
45 private ResteasyClient client;
46
47 @Before
48 public void before()
49 {
50 client = new ResteasyClientBuilder()
51 .readTimeout(5, TimeUnit.SECONDS)
52 .connectionCheckoutTimeout(5, TimeUnit.SECONDS)
53 .connectTimeout(5, TimeUnit.SECONDS)
54 .build();
55 }
56
57 @After
58 public void after()
59 {
60 client.close();
61 }
62
63 @Test
64 public void testSingle()
65 {
66 String data = client.target(generateURL("/single")).request().get(String.class);
67 assertEquals("got it", data);
68
69 String[] data2 = client.target(generateURL("/observable")).request().get(String[].class);
70 assertArrayEquals(new String[] {"one", "two"}, data2);
71
72 data = client.target(generateURL("/context/single")).request().get(String.class);
73 assertEquals("got it", data);
74
75 data2 = client.target(generateURL("/context/observable")).request().get(String[].class);
76 assertArrayEquals(new String[] {"one", "two"}, data2);
77 }
78 }
0 <?xml version="1.0"?>
1 <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
3 <modelVersion>4.0.0</modelVersion>
4 <parent>
5 <groupId>org.jboss.resteasy</groupId>
6 <artifactId>resteasy-jaxrs-all</artifactId>
7 <version>3.5.0.Final</version>
8 </parent>
9 <artifactId>resteasy-rxjava2</artifactId>
10 <name>RESTEasy RxJava 2 integration</name>
11 <url>http://maven.apache.org</url>
12 <properties>
13 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
14 </properties>
15 <dependencies>
16 <dependency>
17 <groupId>junit</groupId>
18 <artifactId>junit</artifactId>
19 <scope>test</scope>
20 </dependency>
21 <dependency>
22 <groupId>org.jboss.resteasy</groupId>
23 <artifactId>resteasy-client</artifactId>
24 <version>${project.version}</version>
25 <scope>test</scope>
26 </dependency>
27 <dependency>
28 <groupId>org.jboss.resteasy</groupId>
29 <artifactId>resteasy-netty4</artifactId>
30 <version>${project.version}</version>
31 <scope>test</scope>
32 </dependency>
33 <dependency>
34 <groupId>org.jboss.resteasy</groupId>
35 <artifactId>resteasy-jackson2-provider</artifactId>
36 <version>${project.version}</version>
37 <scope>test</scope>
38 </dependency>
39 <dependency>
40 <groupId>org.jboss.resteasy</groupId>
41 <artifactId>resteasy-jaxb-provider</artifactId>
42 <version>${project.version}</version>
43 <scope>test</scope>
44 </dependency>
45 <dependency>
46 <groupId>org.jboss.resteasy</groupId>
47 <artifactId>resteasy-jaxrs</artifactId>
48 <version>${project.version}</version>
49 </dependency>
50 <dependency>
51 <groupId>io.reactivex.rxjava2</groupId>
52 <artifactId>rxjava</artifactId>
53 <version>2.1.5</version>
54 </dependency>
55 </dependencies>
56 </project>
0 package org.jboss.resteasy.rxjava2;
1
2 import javax.ws.rs.ext.Provider;
3
4 import org.jboss.resteasy.spi.AsyncStreamProvider;
5 import org.reactivestreams.Publisher;
6
7 import io.reactivex.Flowable;
8 import io.reactivex.plugins.RxJavaPlugins;
9
10 @Provider
11 public class FlowableProvider implements AsyncStreamProvider<Flowable<?>>
12 {
13
14 static
15 {
16 RxJavaPlugins.setOnFlowableSubscribe(new ResteasyContextPropagatingOnFlowableCreateAction());
17 }
18
19 @Override
20 public Publisher<?> toAsyncStream(Flowable<?> asyncResponse)
21 {
22 return asyncResponse;
23 }
24
25 }
0 package org.jboss.resteasy.rxjava2;
1
2 import javax.ws.rs.ext.Provider;
3
4 import org.jboss.resteasy.spi.AsyncStreamProvider;
5 import org.reactivestreams.Publisher;
6
7 import io.reactivex.BackpressureStrategy;
8 import io.reactivex.Observable;
9 import io.reactivex.plugins.RxJavaPlugins;
10
11 @Provider
12 public class ObservableProvider implements AsyncStreamProvider<Observable<?>>
13 {
14
15 static
16 {
17 RxJavaPlugins.setOnObservableSubscribe(new ResteasyContextPropagatingOnObservableCreateAction());
18 }
19
20 @Override
21 public Publisher<?> toAsyncStream(Observable<?> asyncResponse)
22 {
23 return asyncResponse.toFlowable(BackpressureStrategy.BUFFER);
24 }
25
26 }
0 package org.jboss.resteasy.rxjava2;
1
2 import java.util.Map;
3
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.reactivestreams.Subscriber;
6 import org.reactivestreams.Subscription;
7
8 import io.reactivex.Flowable;
9 import io.reactivex.functions.BiFunction;
10
11 @SuppressWarnings("rawtypes")
12 public class ResteasyContextPropagatingOnFlowableCreateAction implements BiFunction<Flowable, Subscriber, Subscriber>
13 {
14
15 @SuppressWarnings("unchecked")
16 @Override
17 public Subscriber apply(Flowable t1, Subscriber t2) throws Exception
18 {
19 return new ContextCapturerSubscriber<>(t2);
20 }
21
22 final static class ContextCapturerSubscriber<T> implements Subscriber<T>
23 {
24
25 final Map<Class<?>, Object> contextDataMap = ResteasyProviderFactory.getContextDataMap();
26
27 final Subscriber<T> actual;
28
29 public ContextCapturerSubscriber(Subscriber<T> actual)
30 {
31 this.actual = actual;
32 }
33
34 @Override
35 public void onError(Throwable e)
36 {
37 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
38 actual.onError(e);
39 ResteasyProviderFactory.removeContextDataLevel();
40 }
41
42 @Override
43 public void onNext(T t)
44 {
45 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
46 actual.onNext(t);
47 ResteasyProviderFactory.removeContextDataLevel();
48 }
49
50 @Override
51 public void onComplete()
52 {
53 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
54 actual.onComplete();
55 ResteasyProviderFactory.removeContextDataLevel();
56 }
57
58 @Override
59 public void onSubscribe(Subscription d)
60 {
61 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
62 actual.onSubscribe(d);
63 ResteasyProviderFactory.removeContextDataLevel();
64 }
65 }
66 }
0 package org.jboss.resteasy.rxjava2;
1
2 import java.util.Map;
3
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import io.reactivex.Observable;
7 import io.reactivex.Observer;
8 import io.reactivex.disposables.Disposable;
9 import io.reactivex.functions.BiFunction;
10
11 @SuppressWarnings("rawtypes")
12 public class ResteasyContextPropagatingOnObservableCreateAction implements BiFunction<Observable, Observer, Observer>
13 {
14
15 @SuppressWarnings("unchecked")
16 @Override
17 public Observer apply(Observable t1, Observer t2) throws Exception
18 {
19 return new ContextCapturerObserver<>(t2);
20 }
21
22 final static class ContextCapturerObserver<T> implements Observer<T>
23 {
24
25 final Map<Class<?>, Object> contextDataMap = ResteasyProviderFactory.getContextDataMap();
26
27 final Observer<T> actual;
28
29 public ContextCapturerObserver(Observer<T> actual)
30 {
31 this.actual = actual;
32 }
33
34 @Override
35 public void onError(Throwable e)
36 {
37 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
38 actual.onError(e);
39 ResteasyProviderFactory.removeContextDataLevel();
40 }
41
42 @Override
43 public void onNext(T t)
44 {
45 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
46 actual.onNext(t);
47 ResteasyProviderFactory.removeContextDataLevel();
48 }
49
50 @Override
51 public void onComplete()
52 {
53 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
54 actual.onComplete();
55 ResteasyProviderFactory.removeContextDataLevel();
56 }
57
58 @Override
59 public void onSubscribe(Disposable d)
60 {
61 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
62 actual.onSubscribe(d);
63 ResteasyProviderFactory.removeContextDataLevel();
64 }
65 }
66 }
0 package org.jboss.resteasy.rxjava2;
1
2 import java.util.Map;
3
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5
6 import io.reactivex.Single;
7 import io.reactivex.SingleObserver;
8 import io.reactivex.disposables.Disposable;
9 import io.reactivex.functions.BiFunction;
10
11 @SuppressWarnings("rawtypes")
12 public class ResteasyContextPropagatingOnSingleCreateAction implements BiFunction<Single, SingleObserver, SingleObserver>
13 {
14 @SuppressWarnings("unchecked")
15 @Override
16 public SingleObserver apply(Single t1, SingleObserver t2) throws Exception
17 {
18 return new ContextCapturerObserver<>(t2);
19 }
20
21 final static class ContextCapturerObserver<T> implements SingleObserver<T>
22 {
23
24 final Map<Class<?>, Object> contextDataMap = ResteasyProviderFactory.getContextDataMap();
25
26 final SingleObserver<T> actual;
27
28 public ContextCapturerObserver(SingleObserver<T> actual)
29 {
30 this.actual = actual;
31 }
32
33 @Override
34 public void onError(Throwable e)
35 {
36 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
37 actual.onError(e);
38 ResteasyProviderFactory.removeContextDataLevel();
39 }
40
41 @Override
42 public void onSuccess(T value)
43 {
44 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
45 actual.onSuccess(value);
46 ResteasyProviderFactory.removeContextDataLevel();
47 }
48
49 @Override
50 public void onSubscribe(Disposable d)
51 {
52 ResteasyProviderFactory.pushContextDataMap(contextDataMap);
53 actual.onSubscribe(d);
54 ResteasyProviderFactory.removeContextDataLevel();
55 }
56 }
57 }
0 package org.jboss.resteasy.rxjava2;
1
2 import java.util.concurrent.CompletableFuture;
3 import java.util.concurrent.CompletionStage;
4
5 import javax.ws.rs.ext.Provider;
6
7 import org.jboss.resteasy.spi.AsyncResponseProvider;
8
9 import io.reactivex.Single;
10 import io.reactivex.disposables.Disposable;
11 import io.reactivex.plugins.RxJavaPlugins;
12
13 @Provider
14 public class SingleProvider implements AsyncResponseProvider<Single<?>>
15 {
16 static
17 {
18 RxJavaPlugins.setOnSingleSubscribe(new ResteasyContextPropagatingOnSingleCreateAction());
19 }
20
21 private static class SingleAdaptor<T> extends CompletableFuture<T>
22 {
23 private Disposable subscription;
24
25 public SingleAdaptor(Single<T> observable)
26 {
27 this.subscription = observable.subscribe(this::complete, this::completeExceptionally);
28 }
29
30 @Override
31 public boolean cancel(boolean mayInterruptIfRunning)
32 {
33 subscription.dispose();
34 return super.cancel(mayInterruptIfRunning);
35 }
36 }
37
38 @Override
39 public CompletionStage<?> toCompletionStage(Single<?> asyncResponse)
40 {
41 return new SingleAdaptor<>(asyncResponse);
42 }
43
44 }
0 org.jboss.resteasy.rxjava2.SingleProvider
1 org.jboss.resteasy.rxjava2.ObservableProvider
2 org.jboss.resteasy.rxjava2.FlowableProvider
0 package org.jboss.resteasy.rxjava2;
1
2 import java.util.concurrent.ExecutorService;
3 import java.util.concurrent.Executors;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.UriInfo;
11
12 import io.reactivex.BackpressureStrategy;
13 import io.reactivex.Flowable;
14 import io.reactivex.Observable;
15 import io.reactivex.Single;
16
17 @Path("/")
18 public class RxResource
19 {
20 @Path("single")
21 @GET
22 public Single<String> single()
23 {
24 return Single.just("got it");
25 }
26
27 @Produces(MediaType.APPLICATION_JSON)
28 @Path("observable")
29 @GET
30 public Observable<String> observable()
31 {
32 return Observable.fromArray("one", "two");
33 }
34
35 @Produces(MediaType.APPLICATION_JSON)
36 @Path("flowable")
37 @GET
38 public Flowable<String> flowable()
39 {
40 return Flowable.fromArray("one", "two");
41 }
42
43 @Path("context/single")
44 @GET
45 public Single<String> contextSingle(@Context UriInfo uriInfo)
46 {
47 return Single.<String>create(foo -> {
48 ExecutorService executor = Executors.newSingleThreadExecutor();
49 executor.submit(new Runnable()
50 {
51 public void run()
52 {
53 foo.onSuccess("got it");
54 }
55 });
56 }).map(str -> {
57 uriInfo.getAbsolutePath();
58 return str;
59 });
60 }
61
62 @Produces(MediaType.APPLICATION_JSON)
63 @Path("context/observable")
64 @GET
65 public Observable<String> contextObservable(@Context UriInfo uriInfo)
66 {
67 return Observable.<String>create(foo -> {
68 ExecutorService executor = Executors.newSingleThreadExecutor();
69 executor.submit(new Runnable()
70 {
71 public void run()
72 {
73 foo.onNext("one");
74 foo.onNext("two");
75 foo.onComplete();
76 }
77 });
78 }).map(str -> {
79 uriInfo.getAbsolutePath();
80 return str;
81 });
82 }
83
84 @Produces(MediaType.APPLICATION_JSON)
85 @Path("context/flowable")
86 @GET
87 public Flowable<String> contextFlowable(@Context UriInfo uriInfo)
88 {
89 return Flowable.<String>create(foo -> {
90 ExecutorService executor = Executors.newSingleThreadExecutor();
91 executor.submit(new Runnable()
92 {
93 public void run()
94 {
95 foo.onNext("one");
96 foo.onNext("two");
97 foo.onComplete();
98 }
99 });
100 }, BackpressureStrategy.BUFFER).map(str -> {
101 uriInfo.getAbsolutePath();
102 return str;
103 });
104 }
105 }
0 package org.jboss.resteasy.rxjava2;
1
2 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
3 import static org.junit.Assert.*;
4
5 import java.util.concurrent.TimeUnit;
6
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.core.Dispatcher;
10 import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
11 import org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory;
12 import org.jboss.resteasy.test.TestPortProvider;
13 import org.junit.After;
14 import org.junit.AfterClass;
15 import org.junit.Before;
16 import org.junit.BeforeClass;
17 import org.junit.Test;
18
19 public class RxTest
20 {
21 private static NettyJaxrsServer server;
22
23 private static Dispatcher dispatcher;
24
25 @BeforeClass
26 public static void beforeClass() throws Exception
27 {
28 server = new NettyJaxrsServer();
29 server.setPort(TestPortProvider.getPort());
30 server.setRootResourcePath("/");
31 server.start();
32 dispatcher = server.getDeployment().getDispatcher();
33 POJOResourceFactory noDefaults = new POJOResourceFactory(RxResource.class);
34 dispatcher.getRegistry().addResourceFactory(noDefaults);
35 }
36
37 @AfterClass
38 public static void afterClass() throws Exception
39 {
40 server.stop();
41 server = null;
42 dispatcher = null;
43 }
44
45 private ResteasyClient client;
46
47 @Before
48 public void before()
49 {
50 client = new ResteasyClientBuilder()
51 .readTimeout(5, TimeUnit.SECONDS)
52 .connectionCheckoutTimeout(5, TimeUnit.SECONDS)
53 .connectTimeout(5, TimeUnit.SECONDS)
54 .build();
55 }
56
57 @After
58 public void after()
59 {
60 client.close();
61 }
62
63 @Test
64 public void testSingle()
65 {
66 String data = client.target(generateURL("/single")).request().get(String.class);
67 assertEquals("got it", data);
68
69 String[] data2 = client.target(generateURL("/observable")).request().get(String[].class);
70 assertArrayEquals(new String[] {"one", "two"}, data2);
71
72 data2 = client.target(generateURL("/flowable")).request().get(String[].class);
73 assertArrayEquals(new String[] {"one", "two"}, data2);
74
75 data = client.target(generateURL("/context/single")).request().get(String.class);
76 assertEquals("got it", data);
77
78 data2 = client.target(generateURL("/context/observable")).request().get(String[].class);
79 assertArrayEquals(new String[] {"one", "two"}, data2);
80
81 data2 = client.target(generateURL("/context/flowable")).request().get(String[].class);
82 assertArrayEquals(new String[] {"one", "two"}, data2);
83 }
84 }
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../pom.xml</relativePath>
88 </parent>
99 <artifactId>resteasy-servlet-initializer</artifactId>
2323 </dependency>
2424 <dependency>
2525 <groupId>org.jboss.spec.javax.ws.rs</groupId>
26 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
26 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
2727 </dependency>
2828 <dependency>
2929 <groupId>org.jboss.spec.javax.servlet</groupId>
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 </parent>
88 <artifactId>resteasy-spring</artifactId>
99 <packaging>jar</packaging>
4545 <version>${project.version}</version>
4646 </dependency>
4747 <dependency>
48 <groupId>org.jboss.resteasy</groupId>
49 <artifactId>resteasy-client</artifactId>
50 <version>${project.version}</version>
51 </dependency>
52 <dependency>
5348 <groupId>org.jboss.spec.javax.ws.rs</groupId>
54 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
49 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
5550 </dependency>
5651 <dependency>
5752 <groupId>org.jboss.resteasy</groupId>
9085 <dependency>
9186 <groupId>org.jboss.spec.javax.servlet</groupId>
9287 <artifactId>jboss-servlet-api_3.1_spec</artifactId>
93 </dependency>
94 <dependency>
95 <groupId>org.apache.httpcomponents</groupId>
96 <artifactId>httpclient</artifactId>
9788 </dependency>
9889 <dependency>
9990 <groupId>httpunit</groupId>
143134 <scope>test</scope>
144135 </dependency>
145136
146 <dependency>
147 <groupId>commons-io</groupId>
148 <artifactId>commons-io</artifactId>
149 </dependency>
150
151137 <!-- Used by org.jboss.resteasy.plugins.server.tjws.* -->
152138 <dependency>
153139 <groupId>org.jboss.resteasy</groupId>
00 package org.jboss.resteasy.client.spring;
11
22 import org.apache.http.client.HttpClient;
3 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
4 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
5 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
6 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
3 import org.jboss.resteasy.client.ClientExecutor;
4 import org.jboss.resteasy.client.ProxyFactory;
5 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
76 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
87 import org.jboss.resteasy.spi.ResteasyProviderFactory;
98 import org.springframework.beans.factory.FactoryBean;
3736 private URI baseUri;
3837 private T client;
3938 private HttpClient httpClient;
40 private ClientHttpEngine clientEngine;
39 private ClientExecutor clientExecutor;
4140 private ResteasyProviderFactory resteasyProviderFactory;
4241
4342 /*
8180 if (resteasyProviderFactory == null)
8281 resteasyProviderFactory = ResteasyProviderFactory.getInstance();
8382 RegisterBuiltin.register(resteasyProviderFactory);
84 ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder();
85 clientBuilder.providerFactory(resteasyProviderFactory);
86
87 if (clientEngine == null)
83
84 if (clientExecutor == null)
8885 {
8986 if (httpClient == null)
9087 {
91 clientEngine = new ApacheHttpClient4Engine();
88 clientExecutor = new ApacheHttpClient4Executor();
9289 }
9390 else
9491 {
95 clientEngine = new ApacheHttpClient4Engine(httpClient);
92 clientExecutor = new ApacheHttpClient4Executor(httpClient);
9693 }
94 client = ProxyFactory.create(serviceInterface, baseUri, clientExecutor,
95 resteasyProviderFactory);
9796 }
98 ResteasyWebTarget target = clientBuilder.httpEngine(clientEngine).build().target(baseUri);
99 client = target.proxy(serviceInterface);
97 else
98 client = ProxyFactory.create(serviceInterface, baseUri,
99 clientExecutor, resteasyProviderFactory);
100100 }
101101
102102 public Class<T> getServiceInterface()
135135 }
136136
137137 /**
138 * Optional property. If this property is set and {@link #clientEngine} is
138 * Optional property. If this property is set and {@link #clientExecutor} is
139139 * null, this will be used by proxy generation. This could be useful for
140140 * example when you want to use a
141141 * {@link org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager}
151151 this.httpClient = httpClient;
152152 }
153153
154 public ClientHttpEngine getClientEngine()
154 public ClientExecutor getClientExecutor()
155155 {
156 return clientEngine;
156 return clientExecutor;
157157 }
158158
159159 /**
165165 * @see ProxyFactory#create(Class, URI, ClientExecutor,
166166 * ResteasyProviderFactory)
167167 */
168 public void setClientExecutor(ClientHttpEngine clientEngine)
168 public void setClientExecutor(ClientExecutor clientExecutor)
169169 {
170 this.clientEngine = clientEngine;
170 this.clientExecutor = clientExecutor;
171171 }
172172
173173 public ResteasyProviderFactory getResteasyProviderFactory()
6565 }
6666 if (requestWrapper.getAbortedResponse() != null)
6767 {
68 ServerResponseWriter.writeNomapResponse(((BuiltResponse) requestWrapper.getAbortedResponse()), requestWrapper.getHttpRequest(), response, dispatcher.getProviderFactory());
68 ServerResponseWriter.writeNomapResponse(((BuiltResponse) requestWrapper.getAbortedResponse()), requestWrapper.getHttpRequest(), response, dispatcher.getProviderFactory(), t -> {});
6969 return null;
7070 }
7171 HttpRequest request = requestWrapper.getHttpRequest();
9696 }
9797 catch (Exception e)
9898 {
99 dispatcher.writeException(request, response, e);
99 dispatcher.writeException(request, response, e, t -> {});
100100 }
101101
102102 if (jaxrsResponse == null)
114114 }
115115 catch (Exception e)
116116 {
117 dispatcher.writeException(request, response, e);
117 dispatcher.writeException(request, response, e, t -> {});
118118 return null;
119119 }
120120 }
3939 HttpResponse response) throws Exception
4040 {
4141 SynchronousDispatcher dispatcher = (SynchronousDispatcher)deployment.getDispatcher();
42 dispatcher.writeException(requestWrapper.getHttpRequest(), response, failure);
42 dispatcher.writeException(requestWrapper.getHttpRequest(), response, failure, t -> {});
4343 return null;
4444 }
4545
9595 BuiltResponse responseInvoker = getResponse(model, resolvedContentType);
9696 if (responseInvoker != null)
9797 {
98 ServerResponseWriter.writeNomapResponse(responseInvoker, httpRequest, response, dispatcher.getProviderFactory());
98 ServerResponseWriter.writeNomapResponse(responseInvoker, httpRequest, response, dispatcher.getProviderFactory(), t -> {
99 if(t != null)
100 dispatcher.writeException(httpRequest, response, t, t2 -> {});
101 });
99102 }
100103 }
101104 catch (Exception e)
102105 {
103 dispatcher.writeException(httpRequest, response, e);
106 dispatcher.writeException(httpRequest, response, e, t -> {});
104107 }
105108 return null;
106109 }
00 package org.jboss.resteasy.springmvc.test.client;
11
2 import org.jboss.resteasy.client.ClientResponse;
23 import org.jboss.resteasy.springmvc.test.jaxb.BasicJaxbObject;
34
45 import javax.ws.rs.GET;
56 import javax.ws.rs.Path;
67 import javax.ws.rs.Produces;
78 import javax.ws.rs.QueryParam;
8 import javax.ws.rs.core.Response;
99
1010 @Path("/basic")
1111 public interface BasicResource
2424 @GET
2525 @Produces("application/json")
2626 @Path("object")
27 public Response getWrongContentTypeBasicObject();
27 public ClientResponse<BasicJaxbObject> getWrongContentTypeBasicObject();
2828
2929 /** test Spring MVC ModelAndView **/
3030 @GET
7979 @GET
8080 @Produces("text/plain")
8181 @Path("bogus-rul-test")
82 public Response testBogusUrl();
82 public ClientResponse<String> testBogusUrl();
8383
8484 @GET
8585 @Produces("application/xml")
00 package org.jboss.resteasy.springmvc.test.spring;
11
2 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
2 import org.jboss.resteasy.client.ClientRequest;
3 import org.jboss.resteasy.client.ClientResponse;
34 import org.jboss.resteasy.core.AsynchronousDispatcher;
45 import org.jboss.resteasy.spi.ResteasyDeployment;
56 import org.jboss.resteasy.springmvc.tjws.TJWSEmbeddedSpringMVCServerBean;
1516 import javax.ws.rs.POST;
1617 import javax.ws.rs.PUT;
1718 import javax.ws.rs.Path;
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.Entity;
20 import javax.ws.rs.client.Invocation.Builder;
21 import javax.ws.rs.client.WebTarget;
2219 import javax.ws.rs.core.HttpHeaders;
23 import javax.ws.rs.core.Response;
24
2520 import java.net.URI;
2621 import java.util.concurrent.CountDownLatch;
2722 import java.util.concurrent.TimeUnit;
7772 public void testOneway() throws Exception
7873 {
7974 latch = new CountDownLatch(1);
80 Client client = ResteasyClientBuilder.newClient();
81 WebTarget target = client.target("http://localhost:9091?oneway=true");
75 ClientRequest request = new ClientRequest("http://localhost:9091?oneway=true");
76 request.body("text/plain", "content");
8277 long start = System.currentTimeMillis();
83 Response response = target.request().put(Entity.entity("content", "text/plain"));
78 ClientResponse<?> response = request.put();
8479 long end = System.currentTimeMillis() - start;
8580 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
8681 Assert.assertTrue(end < 1000);
8782 Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
88 response.close();
83 response.releaseConnection();
8984 }
9085
9186 @Test
9287 public void testAsynch() throws Exception
9388 {
94 Client client = ResteasyClientBuilder.newClient();
95 Response response = null;
96 {
97 latch = new CountDownLatch(1);
89 ClientRequest request = null;
90 ClientResponse<?> response = null;
91 {
92 latch = new CountDownLatch(1);
93 request = new ClientRequest("http://localhost:9091?asynch=true");
94 request.body("text/plain", "content");
9895 long start = System.currentTimeMillis();
99 response = client.target("http://localhost:9091?asynch=true").request().post(Entity.entity("content", "text/plain"));
96 response = request.post();
97 @SuppressWarnings("unused")
10098 long end = System.currentTimeMillis() - start;
10199 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
102 String jobUrl = response.getHeaderString(HttpHeaders.LOCATION);
100 String jobUrl = response.getResponseHeaders().getFirst(HttpHeaders.LOCATION);
103101 System.out.println("JOB: " + jobUrl);
104 response.close();
105
106 Builder jobBuilder = client.target(jobUrl).request();
107 response = jobBuilder.get();
108 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
109 Assert.assertTrue(latch.await(3, TimeUnit.SECONDS));
110 response.close();
102 response.releaseConnection();
103
104 request = new ClientRequest(jobUrl);
105 response = request.get();
106 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
107 Assert.assertTrue(latch.await(3, TimeUnit.SECONDS));
108 response.releaseConnection();
111109 // there's a lag between when the latch completes and the executor
112110 // registers the completion of the call
113 URI oldUri = new URI(jobUrl);
111 URI oldUri = new URI(request.getUri());
114112 String existingQueryString = oldUri.getQuery();
115113 String newQuery = (existingQueryString == null ? "" : "&") + "wait=1000";
116114 URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), newQuery, oldUri.getFragment());
117 response = client.target(newUri).request().get();
118 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
119 Assert.assertEquals("content", response.readEntity(String.class));
115 request = new ClientRequest(newUri.toString());
116 response = request.get();
117 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
118 Assert.assertEquals("content", response.getEntity(String.class));
120119
121120 // test its still there
122 response = jobBuilder.get();
123 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
124 Assert.assertEquals("content", response.readEntity(String.class));
121 response = request.get();
122 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
123 Assert.assertEquals("content", response.getEntity(String.class));
125124
126125 // delete and test delete
127 response = jobBuilder.delete();
126 request = new ClientRequest(jobUrl);
127 response = request.delete();
128128 Assert.assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
129129
130 response = jobBuilder.get();
131 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
132 response.close();
130 response = request.get();
131 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
132 response.releaseConnection();
133133 }
134134
135135 {
136136 dispatcher.setMaxCacheSize(1);
137137 latch = new CountDownLatch(1);
138 Builder builder = client.target("http://localhost:9091?asynch=true").request();
139 response = builder.post(Entity.entity("content", "text/plain"));
140 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
141 String jobUrl1 = response.getHeaderString(HttpHeaders.LOCATION);
142 System.out.println("JOB: " + jobUrl1);
143 Assert.assertTrue(latch.await(3, TimeUnit.SECONDS));
144 response.close();
145
146 latch = new CountDownLatch(1);
147 response = builder.post(Entity.entity("content", "text/plain"));
148 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
149 String jobUrl2 = response.getHeaderString(HttpHeaders.LOCATION);
138 request = new ClientRequest("http://localhost:9091?asynch=true");
139 request.body("text/plain", "content");
140 response = request.post();
141 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
142 String jobUrl1 = response.getResponseHeaders().getFirst(HttpHeaders.LOCATION);
143 Assert.assertTrue(latch.await(3, TimeUnit.SECONDS));
144 response.releaseConnection();
145
146 latch = new CountDownLatch(1);
147 response = request.post();
148 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
149 String jobUrl2 = response.getResponseHeaders().getFirst(HttpHeaders.LOCATION);
150150 Assert.assertTrue(latch.await(3, TimeUnit.SECONDS));
151151 Assert.assertTrue(!jobUrl1.equals(jobUrl2));
152 response.close();
153
154 builder = client.target(jobUrl1).request();
155 response = builder.get();
156 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
157 response.close();
152 response.releaseConnection();
153
154 request = new ClientRequest(jobUrl1);
155 response = request.get();
156 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
157 response.releaseConnection();
158158
159159 // test its still there
160160 Thread.sleep(1000);
161 builder = client.target(jobUrl2).request();
162 response = builder.get();
163 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
164 Assert.assertEquals("content", response.readEntity(String.class));
161 request = new ClientRequest(jobUrl2);
162 response = request.get();
163 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
164 Assert.assertEquals("content", response.getEntity(String.class));
165165
166166 // delete and test delete
167 response = builder.delete();
167 response = request.delete();
168168 Assert.assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
169169
170 response = builder.get();
171 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
172 response.close();
170 response = request.get();
171 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
172 response.releaseConnection();
173173 }
174174
175175 // test readAndRemove
176176 {
177177 dispatcher.setMaxCacheSize(10);
178178 latch = new CountDownLatch(1);
179 Builder builder = client.target("http://localhost:9091?asynch=true").request();
180 response = builder.post(Entity.entity("content", "text/plain"));
181 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
182 String jobUrl2 = response.getHeaderString(HttpHeaders.LOCATION);
183 System.out.println("JOB: " + jobUrl2);
184 Assert.assertTrue(latch.await(3, TimeUnit.SECONDS));
185 response.close();
179 request = new ClientRequest("http://localhost:9091?asynch=true");
180 request.body("text/plain", "content");
181 response = request.post();
182 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
183 String jobUrl2 = response.getResponseHeaders().getFirst(HttpHeaders.LOCATION);
184 Assert.assertTrue(latch.await(3, TimeUnit.SECONDS));
185 response.releaseConnection();
186186
187187 Thread.sleep(1000);
188188 // test its still there
189 builder = client.target(jobUrl2).request();
190 response = builder.post(Entity.entity("content", "text/plain"));
191 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
192 Assert.assertEquals("content", response.readEntity(String.class));
193
194 builder = client.target(jobUrl2).request();
195 response = builder.get();
196 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
197 response.close();
189 request = new ClientRequest(jobUrl2);
190 response = request.post();
191 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
192 Assert.assertEquals("content", response.getEntity(String.class));
193
194 response = request.get();
195 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
196 response.releaseConnection();
198197 }
199198 }
200199 }
44 <bean class="org.jboss.resteasy.springmvc.tjws.TJWSEmbeddedSpringMVCServerBean"
55 p:port="9092" p:applicationContextConfiguration="classpath:spring-test-server.xml" />
66
7 <bean class="org.jboss.resteasy.test.TestPortProvider" factory-method="createProxy">
8 <constructor-arg value="org.jboss.resteasy.springmvc.test.client.BasicResource" />
9 <constructor-arg value="http://localhost:9092/" />
7 <bean class="org.jboss.resteasy.client.ProxyFactory"
8 factory-method="create">
9 <constructor-arg value="org.jboss.resteasy.springmvc.test.client.BasicResource" />
10 <constructor-arg value="http://localhost:9092/" />
1011 </bean>
1112 </beans>
55
66 <groupId>org.jboss.resteasy</groupId>
77 <artifactId>resteasy-upgrade-guide-${translation}</artifactId>
8 <version>3.1.4.Final</version>
8 <version>3.5.0.Final</version>
99 <packaging>jdocbook</packaging>
1010 <name>RESTEasy Upgrade Guide (${translation})</name>
1111 <description/>
0 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
1 "http://www.docbook.org/xml/4.4/docbookx.dtd"
2 [
3 <!ENTITY Client_Framework SYSTEM "modules/Client_Framework.xml">
4 <!ENTITY Interceptors SYSTEM "modules/Interceptors.xml">
5 <!ENTITY Asynchronous SYSTEM "modules/Asynchronous.xml">
6 <!ENTITY Asynchronous "modules/Asynchronous.xml">
7 <!ENTITY Validation SYSTEM "modules/Validation.xml">
8 <!ENTITY Cache SYSTEM "modules/Cache.xml">
9 <!ENTITY Miscellaneous SYSTEM "modules/Miscellaneous.xml">
10 ]>
11
12 <book>
13
14 <bookinfo>
15 <title>Upgrading from Resteasy 2 to Resteasy 3</title>
16 <releaseinfo>3.1.0.Final</releaseinfo>
17 </bookinfo>
18
19 <toc/>
20
21 <preface id="preface" revision="1">
22
23 <para>
24 A number of API classes in Resteasy 2, which is based on the JAX-RS 1.1 specification
25 (<ulink url="https://jcp.org/en/jsr/detail?id=311">https://jcp.org/en/jsr/detail?id=311</ulink>),
26 have been deprecated in, and will eventually be removed from, Resteasy 3, which is based on JAX-RS 2.0
27 (<ulink url="https://jcp.org/aboutJava/communityprocess/final/jsr339/index.html">https://jcp.org/aboutJava/communityprocess/final/jsr339/index.html</ulink>).
28 For the most part, these changes are due to the fact that a number
29 of facilities specific to Resteasy were introduced in Resteasy 2 and then formalized, in somewhat different
30 form, in JAX-RS 2.0. A few other facilities in Resteasy simply were not carried over to Resteasy 3.
31 </para>
32
33 <para>
34 This short document describes the principal changes from Resteasy 2 to Resteasy 3 and gives some
35 hints about upgrading code from the Resteasy 2 API to Resteasy 3. Additional information can be found in the
36 Resteasy Users Guides (<ulink url="http://resteasy.jboss.org/docs.html">http://resteasy.jboss.org/docs.html</ulink>).
37 A more extensive treatment may be found in the O'Reilly book <emphasis>RESTful Java with JAX-RS 2.0, 2nd Edition</emphasis>,
38 by Bill Burke.
39 </para>
40
41 </preface>
42
43 &Client_Framework;
44 &Interceptors;
45 &Asynchronous;
46 &Validation;
47 &Cache;
48 &Miscellaneous;
49
50 </book>
51
0 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
1 "http://www.docbook.org/xml/4.4/docbookx.dtd"
2 [
3 <!ENTITY Client_Framework SYSTEM "modules/Client_Framework.xml">
4 <!ENTITY Interceptors SYSTEM "modules/Interceptors.xml">
5 <!ENTITY Asynchronous SYSTEM "modules/Asynchronous.xml">
6 <!ENTITY Asynchronous "modules/Asynchronous.xml">
7 <!ENTITY Validation SYSTEM "modules/Validation.xml">
8 <!ENTITY Cache SYSTEM "modules/Cache.xml">
9 <!ENTITY Miscellaneous SYSTEM "modules/Miscellaneous.xml">
10 ]>
11
12 <book>
13
14 <bookinfo>
15 <title>Upgrading from Resteasy 2 to Resteasy 3</title>
16 <releaseinfo>3.1.0.Final</releaseinfo>
17 </bookinfo>
18
19 <toc/>
20
21 <preface id="preface" revision="1">
22
23 <para>
24 A number of API classes in Resteasy 2, which is based on the JAX-RS 1.1 specification
25 (<ulink url="https://jcp.org/en/jsr/detail?id=311">https://jcp.org/en/jsr/detail?id=311</ulink>),
26 have been deprecated in, and will eventually be removed from, Resteasy 3, which is based on JAX-RS 2.0
27 (<ulink url="https://jcp.org/aboutJava/communityprocess/final/jsr339/index.html">https://jcp.org/aboutJava/communityprocess/final/jsr339/index.html</ulink>).
28 For the most part, these changes are due to the fact that a number
29 of facilities specific to Resteasy were introduced in Resteasy 2 and then formalized, in somewhat different
30 form, in JAX-RS 2.0. A few other facilities in Resteasy simply were not carried over to Resteasy 3.
31 </para>
32
33 <para>
34 This short document describes the principal changes from Resteasy 2 to Resteasy 3 and gives some
35 hints about upgrading code from the Resteasy 2 API to Resteasy 3. Additional information can be found in the
36 Resteasy Users Guides (<ulink url="http://resteasy.jboss.org/docs.html">http://resteasy.jboss.org/docs.html</ulink>).
37 A more extensive treatment may be found in the O'Reilly book <emphasis>RESTful Java with JAX-RS 2.0, 2nd Edition</emphasis>,
38 by Bill Burke.
39 </para>
40
41 </preface>
42
43 &Client_Framework;
44 &Interceptors;
45 &Asynchronous;
46 &Validation;
47 &Cache;
48 &Miscellaneous;
49
50 </book>
51
00 <chapter id="Miscellaneous">
11 <title>Miscellaneous changes</title>
22
3 <para>
4 In addition to the various updated frameworks discussed in previous sections, a few individual
5 classes have been updated or discarded.
6 </para>
3 <section>
4 <title>Matching Requests to Resource Methods</title>
75
8 <section>
9 <title>Link</title>
10
11 <para>
12 <classname>org.jboss.resteasy.spi.Link</classname> has been replaced by
13 the abstract class <classname>javax.ws.rs.core.Link</classname> and its implementation
14 <classname>org.jboss.resteasy.specimpl.LinkImpl</classname>. They both represent links as
15 described in <ulink url="https://tools.ietf.org/html/rfc5988">RFC 5988</ulink>, with slight
16 variations. For example, there is now <methodname>javax.ws.rs.core.Link.getRel()</methodname>
17 instead of <methodname>org.jboss.resteasy.spi.Link.getRelationship()</methodname>. Also, they
18 are constructed differently. For example,
19 </para>
20
6 <para>
7 Improvements and corrections have been made in Resteasy 3 to the implementation of
8 the matching rules as defined in the JAX-RS 2.0 specification. In particular
9 a change for handling an ambiguous URI on a sub-resource method and
10 sub-resource locator was made. In Resteasy 2 it was possible for a
11 sub-resource locator to execute successfully even when there was also a sub-resource
12 with the same URI. This was incorrect behavior according to the specification.
13 </para>
14 <para>
15 A sub-resource method is associated with a @Path annotation and a REST verb (e.g. @GET, @POST);
16 it handles a HTTP request directly. A sub-resource locator method is annotated with a @Path
17 annotation but returns an object that handles the HTTP request. The presence or absence of a
18 REST verb on the resource method differentiates the two. In the situation where a sub-resource
19 and sub-resource locator method share the same URI, the sub-resource is selected.
20 </para>
21 <para>
22 Here are two scenarios of an ambiguous uri on a sub-resource method and sub-resource locator.
23 </para>
24 <para>
25 In the first scenario the sub-resource method, subResource, resides in class TestResource1,
26 and the sub-resource locator method, subResourceLocator, resides in a different class,
27 TestResource2. Both resources are declared to use the same path, "test/x". The matching rules
28 declare this as an uri ambiguity. In such a case the method with the REST verb is selected
29 (i.e. subResource).
30 </para>
31
32 <programlisting>
33 @Path("test")
34 public class TestResource1 {
35
36 @GET
37 @Path("x")
38 @Produces("text/plain")
39 public Response subResource() {
40 return Response.ok("ok").build();
41 }
42 }
43
44 @Path("test")
45 public class TestResource2 {
46
47 @Path("x")
48 @Produces("text/plain")
49 public SubResource subResourceLocator() {
50 return new SubResource();
51 }
52 }
53
54 public class SubResource {
55
56 @POST
57 @Path("")
58 public String sub(String s) {
59 return "sub(" + s + ")";
60 }
61 }
62 </programlisting>
63 <para>
64 In the second scenario the sub-resource method, anotherResource, and sub-resource locator method,
65 anotherResourceLocator, reside in the same class, TestResource3. Both resources are declared
66 to use the same path, "anotherTest/y". As in the previous case, because the REST verb
67 "POST" is declared on method anotherResource, and method anotherResourceLocator is defined as
68 a sub-resource locator, the endpoint anotherResource is the one selected by the matching rules.
69 </para>
2170 <programlisting>
22 @GET
23 @Path("/link-header")
24 public Response getWithHeader(@Context UriInfo uri)
25 {
26 URI subUri = uri.getAbsolutePathBuilder().path("next-link").build();
27 Link link = new Link();
28 link.setHref(subUri.toASCIIString());
29 link.setRelationship("nextLink");
30 return Response.noContent().header("Link", link.toString()).build();
71 @Path("anotherTest")
72 public class TestResource3 {
73
74 @POST
75 @Path("y")
76 @Produces("text/plain")
77 public Response anotherResource(String text) {
78 return Response.ok("ok").build();
79 }
80
81 @Path("y")
82 @Produces("text/plain")
83 public SubResource anotherResourceLocator() {
84 return new SubResource();
85 }
3186 }
32 </programlisting>
33
34 <para>
35 would now be written
36 </para>
37
38 <programlisting>
39 @GET
40 @Path("/link-header")
41 public Response getWithHeader(@Context UriInfo uri)
42 {
43 URI subUri = uri.getAbsolutePathBuilder().path("next-link").build();
44 Link link = new LinkBuilderImpl().uri(subUri).rel("nextLink").build();
45 return Response.noContent().header("Link", link.toString()).build();
46 }
47 </programlisting>
48 </section>
87 </programlisting>
4988
50 <section>
51 <title>GenericType</title>
52
53 <para>
54 <classname>org.jboss.resteasy.util.GenericType</classname>, which allows the creation of
55 parameterized type objects at runtime, is now replaced by
56 <classname>javax.ws.rs.core.GenericType</classname>. They are essentially the same class, with
57 minor method name changes. In particular, <methodname>getGenericType()</methodname> becomes
58 <methodname>getType()</methodname> and <methodname>getType()</methodname> becomes
59 <methodname>getRawType()</methodname>.
60 </para>
61
62 </section>
63
64 <section>
65 <title>StringConverter</title>
66
67 <para>
68 Implementations of the <classname>org.jboss.resteasy.spi.StringConverter</classname> interface in
69 Resteasy 2 are providers that can marshal and unmarshal string-based parameters labelled with @HeaderParam,
70 @MatrixParam, @QueryParam, or @PathParam. JAX-RS 2.0 introduces a similar interface,
71 <classname>javax.ws.rs.ext.ParamConverter</classname>, but implementations of
72 <classname>ParamConverter</classname> are not recognized as providers. Rather, a provider
73 that implements <classname>javax.ws.rs.ext.ParamConverterProvider</classname>, which produces a
74 <classname>ParamConverter</classname>, may be registered. For example,
75 </para>
76
77 <programlisting>
78 public static class POJO { ... }
79
80 public static class POJOConverter implements ParamConverter&lt;POJO&gt;
81 {
82 public POJO fromString(String str)
83 {
84 POJO pojo = new POJO();
85 return pojo;
86 }
87
88 public String toString(POJO value)
89 {
90 return value.getName();
91 }
92 }
93
94 public static class POJOConverterProvider implements ParamConverterProvider
95 {
96 @Override
97 public &lt;T&gt; ParamConverter&lt;T&gt; getConverter(Class&lt;T&gt; rawType, Type genericType, Annotation[] annotations)
98 {
99 if (!POJO.class.equals(rawType)) return null;
100 return (ParamConverter&lt;T&gt;)new POJOConverter();
101 }
102 }
103
104 ...
105 ResteasyProviderFactory.getInstance().registerProvider(POJOConverterProvider.class);
106 ...
107 </programlisting>
108 </section>
109
110 <section>
111 <title>Logger</title>
112
113 <para>
114 Resteasy 2 comes with a logging abstraction called <classname>org.jboss.resteasy.logging.Logger</classname>,
115 extensions of which delegate to logging frameworks such as log4j and slf4j. Resteasy 3 no longer uses its
116 own logging abstraction but rather adopts the JBoss Logging framework, a brief description of which can
117 be found at
118 <ulink url="http://docs.jboss.org/hibernate/orm/4.3/topical/html/logging/Logging.html">http://docs.jboss.org/hibernate/orm/4.3/topical/html/logging/Logging.html</ulink>.
119 JBoss Logging was chosen for its internationalization and localization support.
120 </para>
121
12289 </section>
12390 </chapter>
55 <parent>
66 <groupId>org.jboss.resteasy</groupId>
77 <artifactId>resteasy-jaxrs-all</artifactId>
8 <version>3.1.4.Final</version>
8 <version>3.5.0.Final</version>
99 <relativePath>../pom.xml</relativePath>
1010 </parent>
1111
2121 </dependency>
2222 <dependency>
2323 <groupId>org.jboss.spec.javax.ws.rs</groupId>
24 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
24 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
2525 </dependency>
2626 <dependency>
2727 <groupId>junit</groupId>
00 package org.jboss.resteasy.wadl;
11
2 import org.jboss.resteasy.wadl.i18n.LogMessages;
2 import org.jboss.resteasy.logging.Logger;
33 import org.jboss.resteasy.wadl.i18n.Messages;
44
55 import javax.ws.rs.GET;
1818 private final static ResteasyWadlWriter apiWriter = new ResteasyWadlServletWriter();
1919 private final static Map<String, ResteasyWadlServiceRegistry> services = new HashMap<>();
2020
21 private final static Logger LOG = Logger.getLogger(ResteasyWadlDefaultResource.class);
22
2123 public static Map<String, ResteasyWadlServiceRegistry> getServices() {
2224 return services;
2325 }
2830 try {
2931 return this.apiWriter.getStringWriter("", services).toString();
3032 } catch (JAXBException e) {
31 LogMessages.LOGGER.error(Messages.MESSAGES.cantProcessWadl(), e);
33 LOG.error(Messages.MESSAGES.cantProcessWadl(), e);
3234 }
3335 return null;
3436 }
55 <parent>
66 <groupId>org.jboss.resteasy</groupId>
77 <artifactId>resteasy-jaxrs-all</artifactId>
8 <version>3.1.4.Final</version>
8 <version>3.5.0.Final</version>
99 <relativePath>../pom.xml</relativePath>
1010 </parent>
1111
4747 </dependency>
4848 <dependency>
4949 <groupId>org.jboss.spec.javax.ws.rs</groupId>
50 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
50 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
5151 </dependency>
5252 <dependency>
5353 <groupId>junit</groupId>
22 <parent>
33 <artifactId>resteasy-jaxrs-all</artifactId>
44 <groupId>org.jboss.resteasy</groupId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../../pom.xml</relativePath>
77 </parent>
88 <modelVersion>4.0.0</modelVersion>
22 <parent>
33 <groupId>org.jboss.resteasy</groupId>
44 <artifactId>resteasy-jaxrs-all</artifactId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../pom.xml</relativePath>
77 </parent>
88 <name>RESTEasy Security</name>
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
0 package org.jboss.resteasy.security.doseta;
1
2 import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
3 import org.jboss.resteasy.annotations.security.doseta.Signed;
4 import org.jboss.resteasy.client.ClientResponse;
5 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
7 import org.jboss.resteasy.spi.interception.ClientExecutionContext;
8 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
9
10 import javax.ws.rs.ext.Provider;
11 import java.lang.reflect.Method;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 */
17 @Provider
18 @HeaderDecoratorPrecedence
19 public class DigitalSigningHeaderDecoratorClientExecutionInterceptor extends AbstractDigitalSigningHeaderDecorator implements ClientExecutionInterceptor, AcceptedByMethod
20 {
21
22 public boolean accept(Class declaring, Method method)
23 {
24 signed = method.getAnnotation(Signed.class);
25 if (signed == null)
26 {
27 signed = (Signed) declaring.getAnnotation(Signed.class);
28 }
29 return signed != null;
30 }
31
32 @Override
33 public ClientResponse execute(ClientExecutionContext ctx) throws Exception
34 {
35 KeyRepository repository = (KeyRepository) ctx.getRequest().getAttributes().get(KeyRepository.class.getName());
36 if (repository == null)
37 {
38 repository = ResteasyProviderFactory.getContextData(KeyRepository.class);
39 }
40 DKIMSignature header = createHeader(repository);
41 ctx.getRequest().header(DKIMSignature.DKIM_SIGNATURE, header);
42 return ctx.proceed();
43 }
44
45 }
00 package org.jboss.resteasy.security.doseta;
11
2 import org.jboss.resteasy.annotations.interception.DecoderPrecedence;
3 import org.jboss.resteasy.client.ClientResponse;
24 import org.jboss.resteasy.security.doseta.i18n.*;
35 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.spi.interception.ClientExecutionContext;
7 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
48
59 import javax.annotation.Priority;
610 import javax.ws.rs.Priorities;
3236 * @version $Revision: 1 $
3337 */
3438 @Provider
39 @DecoderPrecedence
3540 @Priority(Priorities.ENTITY_CODER)
36 public class DigitalSigningInterceptor implements WriterInterceptor, ContainerResponseFilter, ClientRequestFilter
41 public class DigitalSigningInterceptor implements WriterInterceptor, ClientExecutionInterceptor, ContainerResponseFilter, ClientRequestFilter
3742 {
3843
3944 protected List<DKIMSignature> getHeaders(MultivaluedMap<String, Object> headers)
8085 }
8186 }
8287
88 }
89
90 @Override
91 public ClientResponse execute(ClientExecutionContext context) throws Exception
92 {
93 if (context.getRequest().getBody() != null)
94 {
95 return context.proceed(); // let WriterInterceptor handle this
96
97 }
98
99 MultivaluedMap<String, Object> headers = context.getRequest().getHeadersAsObjects();
100 List<DKIMSignature> list = getHeaders(headers);
101
102 for (DKIMSignature dosetaSignature : list)
103 {
104 KeyRepository repository = (KeyRepository) context.getRequest().getAttributes().get(KeyRepository.class.getName());
105 sign(repository, headers, null, dosetaSignature);
106 }
107
108 return context.proceed();
83109 }
84110
85111 @Override
0 package org.jboss.resteasy.security.doseta;
1
2 import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
3 import org.jboss.resteasy.annotations.security.doseta.Verifications;
4 import org.jboss.resteasy.annotations.security.doseta.Verify;
5 import org.jboss.resteasy.client.ClientResponse;
6 import org.jboss.resteasy.spi.interception.AcceptedByMethod;
7 import org.jboss.resteasy.spi.interception.ClientExecutionContext;
8 import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor;
9
10 import javax.ws.rs.ext.Provider;
11 import java.lang.reflect.Method;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 */
17 @Provider
18 @HeaderDecoratorPrecedence
19 public class DigitalVerificationHeaderDecoratorClientExecutionInterceptor extends AbstractDigitalVerificationHeaderDecorator implements ClientExecutionInterceptor, AcceptedByMethod
20 {
21
22 @SuppressWarnings("rawtypes")
23 public boolean accept(Class declaring, Method method)
24 {
25 verify = (Verify) method.getAnnotation(Verify.class);
26 verifications = (Verifications) method.getAnnotation(Verifications.class);
27
28 return verify != null || verifications != null;
29 }
30
31 @SuppressWarnings({"rawtypes", "unchecked"})
32 @Override
33 public ClientResponse execute(ClientExecutionContext ctx) throws Exception
34 {
35 ClientResponse response = ctx.proceed();
36 response.getAttributes().put(Verifier.class.getName(), create());
37 return response;
38 }
39
40 }
0 org.jboss.resteasy.security.doseta.DigitalSigningHeaderDecoratorClientExecutionInterceptor
01 org.jboss.resteasy.security.doseta.ServerDigitalSigningHeaderDecoratorFeature
12 org.jboss.resteasy.security.doseta.ClientDigitalSigningHeaderDecoratorFeature
3 org.jboss.resteasy.security.doseta.DigitalSigningInterceptor
4 org.jboss.resteasy.security.doseta.DigitalVerificationHeaderDecoratorClientExecutionInterceptor
25 org.jboss.resteasy.security.doseta.ClientDigitalVerificationHeaderDecoratorFeature
36 org.jboss.resteasy.security.doseta.ServerDigitalVerificationHeaderDecoratorFeature
4 org.jboss.resteasy.security.doseta.DigitalSigningInterceptor
57 org.jboss.resteasy.security.doseta.DigitalVerificationInterceptor
68 org.jboss.resteasy.security.smime.EnvelopedReader
79 org.jboss.resteasy.security.smime.EnvelopedWriter
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
2929 <parent>
3030 <groupId>org.jboss.resteasy</groupId>
3131 <artifactId>resteasy-jaxrs-all</artifactId>
32 <version>3.1.4.Final</version>
32 <version>3.5.0.Final</version>
3333 <relativePath>../../../pom.xml</relativePath>
3434 </parent>
3535
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
9393 <artifactId>jboss-annotations-api_1.2_spec</artifactId>
9494 </dependency>
9595 <dependency>
96 <groupId>org.jboss.spec.javax.transaction</groupId>
97 <artifactId>jboss-transaction-api_1.1_spec</artifactId>
98 <version>1.0.1.Final</version>
99 </dependency>
100 <dependency>
10196 <groupId>org.jboss.logging</groupId>
10297 <artifactId>jboss-logging</artifactId>
10398 </dependency>
22 <parent>
33 <artifactId>resteasy-jaxrs-all</artifactId>
44 <groupId>org.jboss.resteasy</groupId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../../pom.xml</relativePath>
77 </parent>
88 <modelVersion>4.0.0</modelVersion>
22 <parent>
33 <groupId>org.jboss.resteasy</groupId>
44 <artifactId>resteasy-jaxrs-all</artifactId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../pom.xml</relativePath>
77 </parent>
88 <name>RESTEasy Security Legacy Modules</name>
44 <parent>
55 <artifactId>resteasy-jaxrs-all</artifactId>
66 <groupId>org.jboss.resteasy</groupId>
7 <version>3.1.4.Final</version>
7 <version>3.5.0.Final</version>
88 <relativePath>../../pom.xml</relativePath>
99 </parent>
1010
22 <parent>
33 <groupId>org.jboss.resteasy</groupId>
44 <artifactId>resteasy-jaxrs-all</artifactId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../../pom.xml</relativePath>
77 </parent>
88 <name>RESTEasy Security: Skeleton Key POM</name>
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
22 <parent>
33 <artifactId>resteasy-jaxrs-all</artifactId>
44 <groupId>org.jboss.resteasy</groupId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../../../pom.xml</relativePath>
77 </parent>
88 <modelVersion>4.0.0</modelVersion>
3636 </dependency>
3737 <dependency>
3838 <groupId>com.sun.xml.bind</groupId>
39 <artifactId>jaxb-core</artifactId>
40 </dependency>
41 <dependency>
42 <groupId>com.sun.xml.bind</groupId>
3943 <artifactId>jaxb-impl</artifactId>
4044 </dependency>
4145 <dependency>
5963 <dependency>
6064 <groupId>org.jboss.spec.javax.annotation</groupId>
6165 <artifactId>jboss-annotations-api_1.2_spec</artifactId>
66 </dependency>
67 <dependency>
68 <groupId>org.jboss.spec.javax.xml.bind</groupId>
69 <artifactId>jboss-jaxb-api_2.3_spec</artifactId>
6270 </dependency>
6371 <dependency>
6472 <groupId>org.jboss.logging</groupId>
00 package org.jboss.resteasy.skeleton.key;
11
22 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
3 import org.jboss.resteasy.skeleton.key.i18n.LogMessages;
3 import org.jboss.resteasy.logging.Logger;
44 import org.jboss.resteasy.skeleton.key.i18n.Messages;
55 import org.jboss.resteasy.skeleton.key.representations.AccessTokenResponse;
66 import org.jboss.resteasy.util.BasicAuthHelper;
2424 */
2525 public class AbstractOAuthClient
2626 {
27 private static final Logger LOG = Logger.getLogger(AbstractOAuthClient.class);
28
2729 protected String clientId;
2830 protected String password;
2931 protected KeyStore truststore;
154156
155157 protected String stripOauthParametersFromRedirect(String uri)
156158 {
157 LogMessages.LOGGER.info(Messages.MESSAGES.redirectUri(uri));
159 LOG.info(Messages.MESSAGES.redirectUri(uri));
158160 UriBuilder builder = UriBuilder.fromUri(uri)
159161 .replaceQueryParam("code", null)
160162 .replaceQueryParam("state", null);
22 <parent>
33 <artifactId>resteasy-jaxrs-all</artifactId>
44 <groupId>org.jboss.resteasy</groupId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../../../pom.xml</relativePath>
77 </parent>
88 <modelVersion>4.0.0</modelVersion>
3434 </dependency>
3535 <dependency>
3636 <groupId>org.jboss.spec.javax.ws.rs</groupId>
37 <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
37 <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
3838 </dependency>
3939 <dependency>
4040 <groupId>org.jboss.resteasy</groupId>
44 import org.jboss.resteasy.jose.jws.JWSInput;
55 import org.jboss.resteasy.jose.jws.crypto.RSAProvider;
66 import org.jboss.resteasy.jwt.JsonSerialization;
7 import org.jboss.resteasy.logging.Logger;
78 import org.jboss.resteasy.skeleton.key.idm.IdentityManager;
89 import org.jboss.resteasy.skeleton.key.idm.i18n.LogMessages;
910 import org.jboss.resteasy.skeleton.key.idm.i18n.Messages;
114115 }
115116
116117 protected IdentityManager identityManager;
118 protected Logger logger = Logger.getLogger(TokenManagement.class);
117119 protected Map<String, AccessCode> accessCodeMap = new HashMap<String, AccessCode>();
118120 @Context
119121 protected UriInfo uriInfo;
22 <parent>
33 <groupId>org.jboss.resteasy</groupId>
44 <artifactId>resteasy-jaxrs-all</artifactId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 </parent>
77 <name>RESTEasy Http Adapter Plugins</name>
88 <description/>
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
162162 {
163163 outputHeaders.clear();
164164 }
165
166 @Override
167 public void flushBuffer() throws IOException {
168 commitHeaders();
169 exchange.getResponseBody().flush();
170 }
165171 }
00 package org.jboss.resteasy.test;
11
22 import com.sun.net.httpserver.HttpServer;
3 import org.jboss.resteasy.client.ClientRequest;
4 import org.jboss.resteasy.client.ClientResponse;
35 import org.jboss.resteasy.plugins.server.sun.http.HttpContextBuilder;
46 import org.junit.AfterClass;
57 import org.junit.Assert;
79 import org.junit.Test;
810
911 import java.net.InetSocketAddress;
10
11 import javax.ws.rs.client.Client;
12 import javax.ws.rs.client.ClientBuilder;
13 import javax.ws.rs.client.Entity;
14 import javax.ws.rs.core.Response;
1512
1613 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
1714
4946 @Test
5047 public void testNoDefaultsResource() throws Exception
5148 {
52 Client client = ClientBuilder.newClient();
53
5449 {
55 Response response = client.target(generateURL("/basic")).request().get();
50 ClientRequest request = new ClientRequest(generateURL("/basic"));
51 ClientResponse<String> response = request.get(String.class);
5652 Assert.assertEquals(200, response.getStatus());
57 Assert.assertEquals("basic", response.readEntity(String.class));
53 Assert.assertEquals("basic", response.getEntity());
5854 }
5955
6056 {
61 Response response = client.target(generateURL("/basic")).request().put(Entity.entity("basic", "text/plain"));
57 ClientRequest request = new ClientRequest(generateURL("/basic"));
58 request.body("text/plain", "basic");
59 ClientResponse<?> response = request.put();
6260 Assert.assertEquals(204, response.getStatus());
63 response.close();
6461 }
6562
6663 {
67 Response response = client.target(generateURL("/queryParam")).queryParam("param", "hello world").request().get();
64 ClientRequest request = new ClientRequest(generateURL("/queryParam"));
65 request.queryParameter("param", "hello world");
66 ClientResponse<String> response = request.get(String.class);
6867 Assert.assertEquals(200, response.getStatus());
69 Assert.assertEquals("hello world", response.readEntity(String.class));
68 Assert.assertEquals("hello world", response.getEntity());
7069 }
7170
7271 {
73 Response response = client.target(generateURL("/uriParam/1234")).request().get();
72 ClientRequest request = new ClientRequest(generateURL("/uriParam/1234"));
73 ClientResponse<String> response = request.get(String.class);
7474 Assert.assertEquals(200, response.getStatus());
75 Assert.assertEquals("1234", response.readEntity(String.class));
75 Assert.assertEquals("1234", response.getEntity());
7676 }
7777 }
7878
1010 import org.apache.http.impl.client.BasicAuthCache;
1111 import org.apache.http.impl.client.DefaultHttpClient;
1212 import org.apache.http.protocol.BasicHttpContext;
13 import org.apache.http.protocol.HttpContext;
1413 import org.apache.http.util.EntityUtils;
15 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
16 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
17 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
18 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
19 import org.jboss.resteasy.client.jaxrs.engines.HttpContextProvider;
14 import org.jboss.resteasy.client.ClientExecutor;
15 import org.jboss.resteasy.client.ClientRequest;
16 import org.jboss.resteasy.client.ClientResponse;
17 import org.jboss.resteasy.client.ClientResponseFailure;
18 import org.jboss.resteasy.client.ProxyFactory;
19 import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
2020 import org.jboss.resteasy.core.Dispatcher;
2121 import org.jboss.resteasy.plugins.server.embedded.SimpleSecurityDomain;
2222 import org.jboss.resteasy.plugins.server.sun.http.HttpServerContainer;
3030 import javax.annotation.security.DenyAll;
3131 import javax.annotation.security.RolesAllowed;
3232 import javax.ws.rs.GET;
33 import javax.ws.rs.NotAuthorizedException;
3433 import javax.ws.rs.Path;
3534 import javax.ws.rs.WebApplicationException;
36 import javax.ws.rs.client.Client;
37 import javax.ws.rs.client.Invocation.Builder;
3835 import javax.ws.rs.core.Context;
39 import javax.ws.rs.core.Response;
4036 import javax.ws.rs.core.SecurityContext;
4137 import java.util.List;
4238
43 import static org.jboss.resteasy.test.TestPortProvider.createProxy;
4439 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
4540
4641 /**
158153 @Test
159154 public void testProxy() throws Exception
160155 {
161 DefaultHttpClient httpClient = new DefaultHttpClient();
156 DefaultHttpClient client = new DefaultHttpClient();
162157 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("bill", "password");
163 httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
164 ClientHttpEngine engine = createAuthenticatingEngine(httpClient);
165 Client client = new ResteasyClientBuilder().httpEngine(engine).build();
166 ResteasyWebTarget target = (ResteasyWebTarget) client.target(generateURL(""));
167 BaseProxy proxy = target.proxy(BaseProxy.class);
158 client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
159 ClientExecutor executor = createAuthenticatingExecutor(client);
160 BaseProxy proxy = ProxyFactory.create(BaseProxy.class, generateURL(""), executor);
168161 String val = proxy.get();
169162 Assert.assertEquals(val, "hello");
170163 val = proxy.getAuthorized();
174167 @Test
175168 public void testProxyFailure() throws Exception
176169 {
177 BaseProxy proxy = createProxy(BaseProxy.class, TestPortProvider.generateBaseUrl());
170 BaseProxy proxy = ProxyFactory.create(BaseProxy.class, generateURL(""));
178171 try
179172 {
180173 proxy.getFailure();
181174 }
182 catch (NotAuthorizedException e)
175 catch (ClientResponseFailure e)
183176 {
184177 Assert.assertEquals(e.getResponse().getStatus(), 401);
185 e.getResponse().close();
186178 }
187179 }
188180
189181 @Test
190182 public void testSecurity() throws Exception
191183 {
192 DefaultHttpClient httpClient = new DefaultHttpClient();
184 DefaultHttpClient client = new DefaultHttpClient();
193185 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("bill", "password");
194 httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
195 ClientHttpEngine engine = createAuthenticatingEngine(httpClient);
196 Client client = new ResteasyClientBuilder().httpEngine(engine).build();
186 client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
187 ClientExecutor executor = createAuthenticatingExecutor(client);
197188
198189 {
199 Builder request = client.target(generateURL("/secured")).request();
200 Response response = request.get();
190 ClientRequest request = new ClientRequest(generateURL("/secured"), executor);
191 ClientResponse<String> response = request.get(String.class);
201192 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
202 Assert.assertEquals("hello", response.readEntity(String.class));
203 }
204
205 {
206 Builder request = client.target(generateURL("/secured/authorized")).request();
207 Response response = request.get();
193 Assert.assertEquals("hello", response.getEntity());
194 }
195
196 {
197 ClientRequest request = new ClientRequest(generateURL("/secured/authorized"), executor);
198 ClientResponse<String> response = request.get(String.class);
208199 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
209 Assert.assertEquals("authorized", response.readEntity(String.class));
210 }
211
212 {
213 Builder request = client.target(generateURL("/secured/deny")).request();
214 Response response = request.get();
200 Assert.assertEquals("authorized", response.getEntity());
201 }
202
203 {
204 ClientRequest request = new ClientRequest(generateURL("/secured/deny"), executor);
205 ClientResponse<String> response = request.get(String.class);
215206 Assert.assertEquals(HttpResponseCodes.SC_FORBIDDEN, response.getStatus());
216207 }
217208 }
226217 @Test
227218 public void test579() throws Exception
228219 {
229 DefaultHttpClient httpClient = new DefaultHttpClient();
220 DefaultHttpClient client = new DefaultHttpClient();
230221 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("bill", "password");
231 httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
232 ClientHttpEngine engine = createAuthenticatingEngine(httpClient);
233 Client client = new ResteasyClientBuilder().httpEngine(engine).build();
234 Response response = client.target(generateURL("/secured2")).request().get();
222 client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
223 ClientExecutor executor = createAuthenticatingExecutor(client);
224 ClientRequest request = new ClientRequest(generateURL("/secured2"), executor);
225 ClientResponse<?> response = request.get();
235226 Assert.assertEquals(404, response.getStatus());
236 response.close();
227 response.releaseConnection();
237228 }
238229
239230 @Test
240231 public void testSecurityFailure() throws Exception
241232 {
242 DefaultHttpClient httpClient = new DefaultHttpClient();
233 DefaultHttpClient client = new DefaultHttpClient();
243234
244235 {
245236 HttpGet method = new HttpGet(generateURL("/secured"));
246 HttpResponse response = httpClient.execute(method);
237 HttpResponse response = client.execute(method);
247238 Assert.assertEquals(401, response.getStatusLine().getStatusCode());
248239 EntityUtils.consume(response.getEntity());
249240 }
250241
251 ClientHttpEngine engine = createAuthenticatingEngine(httpClient);
252 Client client = new ResteasyClientBuilder().httpEngine(engine).build();
242 ClientExecutor executor = createAuthenticatingExecutor(client);
253243
254244 {
255245 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("bill", "password");
256 httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
257 Response response = client.target(generateURL("/secured/authorized")).request().get();
246 client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
247 ClientRequest request = new ClientRequest(generateURL("/secured/authorized"), executor);
248 ClientResponse<String> response = request.get(String.class);
258249 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
259 Assert.assertEquals("authorized", response.readEntity(String.class));
250 Assert.assertEquals("authorized", response.getEntity());
260251 }
261252
262253 {
263254 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("mo", "password");
264 httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
265 Response response = client.target(generateURL("/secured/authorized")).request().get();
255 client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
256 ClientRequest request = new ClientRequest(generateURL("/secured/authorized"), executor);
257 ClientResponse<?> response = request.get();
266258 Assert.assertEquals(HttpResponseCodes.SC_FORBIDDEN, response.getStatus());
267 response.close();
259 response.releaseConnection();
268260 }
269261 }
270262
272264 * Create a ClientExecutor which does preemptive authentication.
273265 */
274266
275 static private ClientHttpEngine createAuthenticatingEngine(DefaultHttpClient client)
267 static private ClientExecutor createAuthenticatingExecutor(DefaultHttpClient client)
276268 {
277269 // Create AuthCache instance
278270 AuthCache authCache = new BasicAuthCache();
279271
272 // Generate BASIC scheme object and add it to the local auth cache
273 BasicScheme basicAuth = new BasicScheme();
274 HttpHost targetHost = new HttpHost("localhost", 8081);
275 authCache.put(targetHost, basicAuth);
276
277 // Add AuthCache to the execution context
278 BasicHttpContext localContext = new BasicHttpContext();
279 localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
280
280281 // Create ClientExecutor.
281 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(client, new HttpContextProvider()
282 {
283 @Override
284 public HttpContext getContext()
285 {
286 // Generate BASIC scheme object and add it to the local auth cache
287 BasicScheme basicAuth = new BasicScheme();
288 HttpHost targetHost = new HttpHost("localhost", 8081);
289 authCache.put(targetHost, basicAuth);
290
291 // Add AuthCache to the execution context
292 BasicHttpContext localContext = new BasicHttpContext();
293 localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
294 return localContext;
295 }
296 });
297 return engine;
282 ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);
283 return executor;
298284 }
299285 }
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
3131 <groupId>org.jboss.resteasy</groupId>
3232 <artifactId>resteasy-client</artifactId>
3333 <version>${project.version}</version>
34 <scope>test</scope>
3435 </dependency>
3536 <dependency>
3637 <groupId>org.jboss.logging</groupId>
152152 return method;
153153 }
154154
155 @Override
156 public void flushBuffer() throws IOException {
157 underlyingOutputStream.flush();
158 }
159
155160 }
1414 import org.jboss.resteasy.spi.ResteasyDeployment;
1515
1616 import javax.net.ssl.SSLContext;
17 import javax.ws.rs.ApplicationPath;
18
1719 import java.net.InetSocketAddress;
1820 import java.util.Collections;
1921 import java.util.List;
160162 public void start()
161163 {
162164 deployment.start();
165 // dynamically set the root path (the user can rewrite it by calling setRootResourcePath)
166 if (deployment.getApplication() != null) {
167 ApplicationPath appPath = deployment.getApplication().getClass().getAnnotation(ApplicationPath.class);
168 if (appPath != null && (root == null || "".equals(root))) {
169 // annotation is present and original root is not set
170 String path = appPath.value();
171 setRootResourcePath(path);
172 }
173 }
163174 RequestDispatcher dispatcher = new RequestDispatcher((SynchronousDispatcher)deployment.getDispatcher(), deployment.getProviderFactory(), domain);
164175
165176 // Configure the server.
1010 import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
1111 import org.jboss.netty.handler.codec.http.HttpResponse;
1212 import org.jboss.netty.handler.codec.http.HttpResponseStatus;
13 import org.jboss.resteasy.logging.Logger;
1314 import org.jboss.resteasy.plugins.server.netty.i18n.LogMessages;
1415 import org.jboss.resteasy.plugins.server.netty.i18n.Messages;
1516 import org.jboss.resteasy.spi.Failure;
0 package org.jboss.resteasy.test;
1
2 import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
3 import org.jboss.resteasy.spi.ResteasyDeployment;
4 import org.jboss.resteasy.util.HttpResponseCodes;
5 import org.junit.Test;
6
7 import static org.junit.Assert.assertEquals;
8 import static org.junit.Assert.assertTrue;
9
10 import java.util.HashSet;
11 import java.util.Set;
12
13 import javax.ws.rs.ApplicationPath;
14 import javax.ws.rs.GET;
15 import javax.ws.rs.Path;
16 import javax.ws.rs.Produces;
17 import javax.ws.rs.QueryParam;
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.core.Application;
21 import javax.ws.rs.core.Response;
22
23 /**
24 * Fetching root path from ApplicationPath annotation related tests.
25 * @see https://issues.jboss.org/browse/RESTEASY-1657
26 */
27 public class NettyApplicationPathTest
28 {
29 private static final String ECHO = "hello";
30
31 @ApplicationPath("/rest-test")
32 public static class TestApplication extends Application
33 {
34 private final Set<Object> singletons = new HashSet<>();
35
36 public TestApplication()
37 {
38 singletons.add(new EchoService());
39 }
40
41 @Override
42 public Set<Object> getSingletons()
43 {
44 return singletons;
45 }
46 }
47
48 @Path("/")
49 public static class EchoService
50 {
51 @GET
52 @Path("/echo")
53 @Produces("text/plain")
54 public String echo(@QueryParam("text") final String echo)
55 {
56 return echo;
57 }
58 }
59
60 @Test
61 public void testWithClass() throws Exception
62 {
63 NettyJaxrsServer server = null;
64 Client client = null;
65 try
66 {
67 ResteasyDeployment deployment = new ResteasyDeployment();
68 deployment.setApplicationClass(TestApplication.class.getName());
69 server = new NettyJaxrsServer();
70 server.setDeployment(deployment);
71 server.setHostname("localhost");
72 server.setPort(8080);
73 server.start();
74
75 // call resource
76 final String path = "/rest-test/echo";
77 client = ClientBuilder.newClient();
78 String url = String.format("http://%s:%d%s", server.getHostname(), server.getPort(), path);
79 Response response = client.target(url).queryParam("text", ECHO).request().get();
80 assertTrue(response.getStatus() == HttpResponseCodes.SC_OK);
81 String msg = response.readEntity(String.class);
82 assertEquals(ECHO, msg);
83 }
84 finally
85 {
86 if (client != null)
87 {
88 client.close();
89 }
90 if (server != null)
91 {
92 server.stop();
93 }
94 }
95 }
96
97 @Test
98 public void testWithApplication() throws Exception
99 {
100 NettyJaxrsServer server = null;
101 Client client = null;
102 try
103 {
104 ResteasyDeployment deployment = new ResteasyDeployment();
105 Application app = new TestApplication();
106 deployment.setApplication(app);
107 server = new NettyJaxrsServer();
108 server.setDeployment(deployment);
109 server.setHostname("localhost");
110 server.setPort(8080);
111 server.start();
112
113 // call resource
114 final String path = "/rest-test/echo";
115 client = ClientBuilder.newClient();
116 String url = String.format("http://%s:%d%s", server.getHostname(), server.getPort(), path);
117 Response response = client.target(url).queryParam("text", ECHO).request().get();
118 assertTrue(response.getStatus() == HttpResponseCodes.SC_OK);
119 String msg = response.readEntity(String.class);
120 assertEquals(ECHO, msg);
121 }
122 finally
123 {
124 if (client != null)
125 {
126 client.close();
127 }
128 if (server != null)
129 {
130 server.stop();
131 }
132 }
133 }
134
135 @Test
136 public void testWithManualRootPath() throws Exception
137 {
138 NettyJaxrsServer server = null;
139 Client client = null;
140 try
141 {
142 ResteasyDeployment deployment = new ResteasyDeployment();
143 deployment.setApplicationClass(TestApplication.class.getName());
144 server = new NettyJaxrsServer();
145 server.setRootResourcePath("/new-rest-test");
146 server.setDeployment(deployment);
147 server.setHostname("localhost");
148 server.setPort(8080);
149 server.start();
150
151 // call resource
152 // root resource should be taken from setRootResourcePath method
153 final String path = "/new-rest-test/echo";
154 client = ClientBuilder.newClient();
155 String url = String.format("http://%s:%d%s", server.getHostname(), server.getPort(), path);
156 Response response = client.target(url).queryParam("text", ECHO).request().get();
157 assertTrue(response.getStatus() == HttpResponseCodes.SC_OK);
158 String msg = response.readEntity(String.class);
159 assertEquals(ECHO, msg);
160 }
161 finally
162 {
163 if (client != null)
164 {
165 client.close();
166 }
167 if (server != null)
168 {
169 server.stop();
170 }
171 }
172 }
173 }
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
2222 <groupId>org.jboss.resteasy</groupId>
2323 <artifactId>resteasy-client</artifactId>
2424 <version>${project.version}</version>
25 <scope>compile</scope>
25 <scope>test</scope>
2626 </dependency>
2727 <dependency>
2828 <groupId>org.jboss.resteasy</groupId>
262262 }
263263
264264 @Override
265 public void complete() {
266 synchronized (responseLock)
267 {
268 if (done) return;
269 if (cancelled) return;
270 done = true;
271 nettyFlush();
272 }
273 }
274
275
276 @Override
265277 public boolean resume(Object entity) {
266278 synchronized (responseLock)
267279 {
268280 if (done) return false;
269281 if (cancelled) return false;
270 try
271 {
272 return internalResume(entity);
273 }
274 finally
275 {
276 done = true;
277 nettyFlush();
278 }
282 done = true;
283 return internalResume(entity, t -> nettyFlush());
279284 }
280285 }
281286
285290 {
286291 if (done) return false;
287292 if (cancelled) return false;
288 try
289 {
290 return internalResume(ex);
291 }
292 catch (UnhandledException unhandled)
293 {
294 return internalResume(Response.status(500).build());
295 }
296 finally
297 {
298 done = true;
299 nettyFlush();
300 }
293 done = true;
294 return internalResume(ex, t -> {
295 if(t instanceof UnhandledException)
296 {
297 internalResume(Response.status(500).build(), t2 -> nettyFlush());
298 }
299 else
300 {
301 nettyFlush();
302 }
303 });
301304 }
302305 }
303306
313316 }
314317 done = true;
315318 cancelled = true;
316 try
317 {
318 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).build());
319 }
320 finally
321 {
322 nettyFlush();
323 }
319 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).build(), t -> nettyFlush());
324320 }
325321 }
326322
332328 if (done) return false;
333329 done = true;
334330 cancelled = true;
335 try
336 {
337 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build());
338 }
339 finally
340 {
341 nettyFlush();
342 }
331 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(),
332 t -> nettyFlush());
343333 }
344334 }
345335
364354 if (done) return false;
365355 done = true;
366356 cancelled = true;
367 try
368 {
369 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build());
370 }
371 finally
372 {
373 nettyFlush();
374 }
357 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(),
358 t -> nettyFlush());
375359 }
376360 }
377361
210210
211211 }
212212
213
213 @Override
214 public void flushBuffer() throws IOException {
215 if(os != null)
216 os.flush();
217 ctx.flush();
218 }
214219 }
2323
2424 import javax.net.ssl.SSLContext;
2525 import javax.net.ssl.SSLEngine;
26 import javax.ws.rs.ApplicationPath;
27
2628 import java.net.InetSocketAddress;
2729 import java.util.Collections;
2830 import java.util.List;
238240 eventLoopGroup = new NioEventLoopGroup(ioWorkerCount);
239241 eventExecutor = new NioEventLoopGroup(executorThreadCount);
240242 deployment.start();
243 // dynamically set the root path (the user can rewrite it by calling setRootResourcePath)
244 if (deployment.getApplication() != null) {
245 ApplicationPath appPath = deployment.getApplication().getClass().getAnnotation(ApplicationPath.class);
246 if (appPath != null && (root == null || "".equals(root))) {
247 // annotation is present and original root is not set
248 String path = appPath.value();
249 setRootResourcePath(path);
250 }
251 }
241252 // Configure the server.
242253 bootstrap.group(eventLoopGroup)
243254 .channel(NioServerSocketChannel.class)
4141 try {
4242
4343 // Not necessary, since io.netty.handler.codec.MessageAggregator has already done it.
44 // if (request.is100ContinueExpected()) {
45 // send100Continue(ctx);
46 // }
44 // if (request.is100ContinueExpected()) {
45 // send100Continue(ctx);
46 // }
4747
4848 NettyHttpResponse response = request.getResponse();
4949 try {
6767 }
6868 }
6969
70 // No longer called. However, note that if it is called, it should write a
71 // io.netty.handler.codec.http.DefaultFullHttpResponse rather
72 // than a io.netty.handler.codec.http.DefaultHttpResponse. The latter doesn't leave
73 // io.netty.handler.codec.http.HttpObjectEncoder in state ST_INIT, so that the next
74 // message going into HttpObjectEncoder causes it to throw an exception.
75 //
76 // private void send100Continue(ChannelHandlerContext ctx)
77 // {
78 // HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE);
79 // ctx.writeAndFlush(response);
80 // }
70 // No longer called. However, note that if it is called, it should write a
71 // io.netty.handler.codec.http.DefaultFullHttpResponse rather
72 // than a io.netty.handler.codec.http.DefaultHttpResponse. The latter doesn't leave
73 // io.netty.handler.codec.http.HttpObjectEncoder in state ST_INIT, so that the next
74 // message going into HttpObjectEncoder causes it to throw an exception.
75 //
76 // private void send100Continue(ChannelHandlerContext ctx)
77 // {
78 // HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE);
79 // ctx.writeAndFlush(response);
80 // }
8181
8282 @Override
8383 public void exceptionCaught(ChannelHandlerContext ctx, Throwable e)
33 import io.netty.buffer.ByteBuf;
44 import io.netty.channel.ChannelHandler.Sharable;
55 import io.netty.channel.ChannelHandlerContext;
6 import io.netty.handler.codec.DecoderResult;
67 import io.netty.handler.codec.MessageToMessageDecoder;
78 import io.netty.handler.codec.http.HttpContent;
89 import io.netty.handler.codec.http.HttpHeaders;
5657 {
5758 boolean keepAlive = HttpHeaders.isKeepAlive(request);
5859 final NettyHttpResponse response = new NettyHttpResponse(ctx, keepAlive, dispatcher.getProviderFactory(), request.method());
60
61 DecoderResult decoderResult = request.decoderResult();
62 if (decoderResult.isFailure())
63 {
64 Throwable t = decoderResult.cause();
65 if (t != null && t.getLocalizedMessage() != null)
66 {
67 response.sendError(400, t.getLocalizedMessage());
68 }
69 else
70 {
71 response.sendError(400);
72 }
73 return;
74 }
75
5976 final ResteasyHttpHeaders headers;
6077 final ResteasyUriInfo uriInfo;
6178 try
00 package org.jboss.resteasy.test;
1
2 import org.jboss.logging.Logger;
13
24 import javax.ws.rs.ForbiddenException;
35 import javax.ws.rs.GET;
2022 public class AsyncJaxrsResource
2123 {
2224 protected boolean cancelled;
25 private final static Logger logger = Logger.getLogger(AsyncJaxrsResource.class);
2326
2427 @GET
2528 @Path("resume/object")
4750 @GET
4851 @Path("injection-failure/{param}")
4952 public void injectionFailure(@Suspended final AsyncResponse response, @PathParam("param") int id) {
50 System.out.println("injectionFailure: " + id);
53 logger.debug("injectionFailure: " + id);
5154 throw new ForbiddenException("Should be unreachable");
5255 }
5356
9093 }
9194 catch (Exception e)
9295 {
93 e.printStackTrace();
96 logger.error(e.getMessage(), e);
9497 }
9598 }
9699 };
115118 }
116119 catch (Exception e)
117120 {
118 e.printStackTrace();
121 logger.error(e.getMessage(), e);
119122 }
120123 }
121124 };
141144 }
142145 catch (Exception e)
143146 {
144 e.printStackTrace();
147 logger.error(e.getMessage(), e);
145148 }
146149 }
147150 };
153156 @Produces("text/plain")
154157 public void cancel(@Suspended final AsyncResponse response) throws Exception
155158 {
156 System.out.println("entering cancel()");
159 logger.debug("entering cancel()");
157160 response.setTimeout(10000, TimeUnit.MILLISECONDS);
158161 final CountDownLatch sync = new CountDownLatch(1);
159162 final CountDownLatch ready = new CountDownLatch(1);
164167 {
165168 try
166169 {
167 System.out.println("cancel(): starting thread");
170 logger.debug("cancel(): starting thread");
168171 sync.countDown();
169172 ready.await();
170173 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
171 System.out.println("SETTING CANCELLED");
174 logger.debug("SETTING CANCELLED");
172175 cancelled = !response.resume(jaxrs);
173 System.out.println("cancelled: " + cancelled);
176 logger.debug("cancelled: " + cancelled);
174177 }
175178 catch (Exception e)
176179 {
177 e.printStackTrace();
180 logger.error(e.getMessage(), e);
178181 }
179182 }
180183 };
181184 t.start();
182185
183186 sync.await();
184 System.out.println("cancel(): cancelling response");
187 logger.debug("cancel(): cancelling response");
185188 response.cancel();
186189 ready.countDown();
187190 Thread.sleep(1000);
0 package org.jboss.resteasy.test;
1
2 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.client.Client;
7 import javax.ws.rs.client.ClientBuilder;
8 import javax.ws.rs.client.WebTarget;
9 import javax.ws.rs.core.Context;
10 import javax.ws.rs.core.HttpHeaders;
11 import javax.ws.rs.core.Response;
12
13 import org.jboss.resteasy.plugins.server.netty.NettyContainer;
14 import org.junit.AfterClass;
15 import org.junit.Assert;
16 import org.junit.BeforeClass;
17 import org.junit.Test;
18
19 /**
20 * @author <a href="mailto:rsigal@redhat.com">Ron Sigal</a>
21 * RESTEASY-1244
22 *
23 * @version $Revision: 1 $
24 */
25 public class HeaderTooLongTest
26 {
27 static String longString = "abcdefghijklmnopqrstuvwxyz";
28 static
29 {
30 for (int i = 0; i < 10; i++)
31 {
32 longString += longString;
33 }
34 }
35
36 @Path("/")
37 public static class Resource
38 {
39 @GET
40 @Path("/test")
41 public String hello(@Context HttpHeaders headers)
42 {
43 return "hello world";
44 }
45 }
46
47 static Client client;
48
49 @BeforeClass
50 public static void setup() throws Exception
51 {
52 NettyContainer.start().getRegistry().addPerRequestResource(Resource.class);
53 client = ClientBuilder.newClient();
54 }
55
56 @AfterClass
57 public static void end() throws Exception
58 {
59 client.close();
60 NettyContainer.stop();
61 }
62
63 @Test
64 public void testLongHeader() throws Exception
65 {
66 WebTarget target = client.target(generateURL("/test"));
67 Response response = target.request().header("xheader", longString).get();
68 Assert.assertEquals(400, response.getStatus());
69 }
70 }
0 package org.jboss.resteasy.test;
1
2 import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
3 import org.jboss.resteasy.spi.ResteasyDeployment;
4 import org.jboss.resteasy.util.HttpResponseCodes;
5 import org.junit.Test;
6
7 import static org.junit.Assert.assertEquals;
8 import static org.junit.Assert.assertTrue;
9
10 import java.util.HashSet;
11 import java.util.Set;
12
13 import javax.ws.rs.ApplicationPath;
14 import javax.ws.rs.GET;
15 import javax.ws.rs.Path;
16 import javax.ws.rs.Produces;
17 import javax.ws.rs.QueryParam;
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.core.Application;
21 import javax.ws.rs.core.Response;
22
23 /**
24 * Fetching root path from ApplicationPath annotation related tests.
25 * @see https://issues.jboss.org/browse/RESTEASY-1657
26 */
27 public class Netty4ApplicationPathTest
28 {
29 private static final String ECHO = "hello";
30
31 @ApplicationPath("/rest-test")
32 public static class TestApplication extends Application
33 {
34 private final Set<Object> singletons = new HashSet<>();
35
36 public TestApplication()
37 {
38 singletons.add(new EchoService());
39 }
40
41 @Override
42 public Set<Object> getSingletons()
43 {
44 return singletons;
45 }
46 }
47
48 @Path("/")
49 public static class EchoService
50 {
51 @GET
52 @Path("/echo")
53 @Produces("text/plain")
54 public String echo(@QueryParam("text") final String echo)
55 {
56 return echo;
57 }
58 }
59
60 @Test
61 public void testWithClass() throws Exception
62 {
63 NettyJaxrsServer server = null;
64 Client client = null;
65 try
66 {
67 ResteasyDeployment deployment = new ResteasyDeployment();
68 deployment.setApplicationClass(TestApplication.class.getName());
69 server = new NettyJaxrsServer();
70 server.setDeployment(deployment);
71 server.setHostname("localhost");
72 server.setPort(8080);
73 server.start();
74
75 // call resource
76 final String path = "/rest-test/echo";
77 client = ClientBuilder.newClient();
78 String url = String.format("http://%s:%d%s", server.getHostname(), server.getPort(), path);
79 Response response = client.target(url).queryParam("text", ECHO).request().get();
80 assertTrue(response.getStatus() == HttpResponseCodes.SC_OK);
81 String msg = response.readEntity(String.class);
82 assertEquals(ECHO, msg);
83 }
84 finally
85 {
86 if (client != null)
87 {
88 client.close();
89 }
90 if (server != null)
91 {
92 server.stop();
93 }
94 }
95 }
96
97 @Test
98 public void testWithApplication() throws Exception
99 {
100 NettyJaxrsServer server = null;
101 Client client = null;
102 try
103 {
104 ResteasyDeployment deployment = new ResteasyDeployment();
105 Application app = new TestApplication();
106 deployment.setApplication(app);
107 server = new NettyJaxrsServer();
108 server.setDeployment(deployment);
109 server.setHostname("localhost");
110 server.setPort(8080);
111 server.start();
112
113 // call resource
114 final String path = "/rest-test/echo";
115 client = ClientBuilder.newClient();
116 String url = String.format("http://%s:%d%s", server.getHostname(), server.getPort(), path);
117 Response response = client.target(url).queryParam("text", ECHO).request().get();
118 assertTrue(response.getStatus() == HttpResponseCodes.SC_OK);
119 String msg = response.readEntity(String.class);
120 assertEquals(ECHO, msg);
121 }
122 finally
123 {
124 if (client != null)
125 {
126 client.close();
127 }
128 if (server != null)
129 {
130 server.stop();
131 }
132 }
133 }
134
135 @Test
136 public void testWithManualRootPath() throws Exception
137 {
138 NettyJaxrsServer server = null;
139 Client client = null;
140 try
141 {
142 ResteasyDeployment deployment = new ResteasyDeployment();
143 deployment.setApplicationClass(TestApplication.class.getName());
144 server = new NettyJaxrsServer();
145 server.setRootResourcePath("/new-rest-test");
146 server.setDeployment(deployment);
147 server.setHostname("localhost");
148 server.setPort(8080);
149 server.start();
150
151 // call resource
152 // root resource should be taken from setRootResourcePath method
153 final String path = "/new-rest-test/echo";
154 client = ClientBuilder.newClient();
155 String url = String.format("http://%s:%d%s", server.getHostname(), server.getPort(), path);
156 Response response = client.target(url).queryParam("text", ECHO).request().get();
157 assertTrue(response.getStatus() == HttpResponseCodes.SC_OK);
158 String msg = response.readEntity(String.class);
159 assertEquals(ECHO, msg);
160 }
161 finally
162 {
163 if (client != null)
164 {
165 client.close();
166 }
167 if (server != null)
168 {
169 server.stop();
170 }
171 }
172 }
173 }
0 package org.jboss.resteasy.test;
1
2 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.client.Client;
8 import javax.ws.rs.client.ClientBuilder;
9 import javax.ws.rs.client.WebTarget;
10
11 import org.jboss.resteasy.plugins.server.netty.NettyContainer;
12 import org.junit.AfterClass;
13 import org.junit.Assert;
14 import org.junit.BeforeClass;
15 import org.junit.Test;
16
17 /**
18 * Created by weinanli on 16/06/2017.
19 */
20 public class SubresourceClassInjectionTest {
21 public static class SubResource {
22
23 public SubResource() {
24 }
25
26 @GET
27 public String get(@PathParam("val") String val) {
28 return val;
29 }
30 }
31
32 @Path("/")
33 public static class Resource {
34
35 @Path("/sub/{val}")
36 public Class<SubResource> sub2(@PathParam("val") String val) {
37 return SubResource.class;
38 }
39 }
40
41 static Client client;
42
43 @BeforeClass
44 public static void setup() throws Exception {
45 NettyContainer.start().getRegistry().addPerRequestResource(SubresourceClassInjectionTest.Resource.class);
46 client = ClientBuilder.newClient();
47 }
48
49 @AfterClass
50 public static void end() throws Exception {
51 try {
52 client.close();
53 } catch (Exception e) {
54
55 }
56 NettyContainer.stop();
57 }
58
59 @Test
60 public void testQuery() throws Exception
61 {
62 WebTarget target = client.target(generateURL("/sub/val"));
63 String val = target.request().get(String.class);
64 Assert.assertEquals("val", val);
65 }
66 }
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
2626
2727 /**
2828 * RESTEASY-1629
29 * Since RESTEasy 3.1.2.Final
29 * Since RESTEasy 3.0.22.Final
3030 */
3131 public class UndertowParameterTest {
3232
33 <parent>
44 <artifactId>resteasy-jaxrs-all</artifactId>
55 <groupId>org.jboss.resteasy</groupId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../../pom.xml</relativePath>
88 </parent>
99 <modelVersion>4.0.0</modelVersion>
5656 <dependency>
5757 <groupId>org.jboss.logging</groupId>
5858 <artifactId>jboss-logging-processor</artifactId>
59 </dependency>
59 </dependency>
60 <dependency>
61 <groupId>org.jboss.spec.javax.annotation</groupId>
62 <artifactId>jboss-annotations-api_1.2_spec</artifactId>
63 <scope>test</scope>
64 </dependency>
6065 </dependencies>
6166 <profiles>
6267 <profile>
3838 throw new IllegalArgumentException(Messages.MESSAGES.chunkSizeMustBeAtLeastOne());
3939 }
4040 this.chunkSize = chunksize;
41 this.buffer = Buffer.buffer(chunksize);
41 this.buffer = Buffer.factory.buffer(chunksize);
4242 }
4343
4444 @Override
5454 public void reset()
5555 {
5656 if (response.isCommitted()) throw new IllegalStateException(Messages.MESSAGES.responseIsCommitted());
57 buffer = Buffer.buffer(chunkSize);
57 buffer = Buffer.factory.buffer(chunkSize);
5858 }
5959
6060 @Override
9090 int readable = buffer.length();
9191 if (readable == 0) return;
9292 if (!response.isCommitted()) response.prepareChunkStream();
93 response.checkException();
9394 response.response.write(buffer);
94 buffer = Buffer.buffer();
95 buffer = Buffer.factory.buffer();
9596 super.flush();
9697 }
9798
00 package org.jboss.resteasy.plugins.server.vertx;
11
22 import io.vertx.core.Context;
3 import io.vertx.core.Handler;
4
35 import org.jboss.resteasy.core.AbstractAsynchronousResponse;
46 import org.jboss.resteasy.core.AbstractExecutionContext;
57 import org.jboss.resteasy.core.SynchronousDispatcher;
248250 }
249251
250252 @Override
253 public void complete()
254 {
255 synchronized (responseLock)
256 {
257 if (done) return;
258 if (cancelled) return;
259 done = true;
260 vertxFlush();
261 }
262 }
263
264 @Override
251265 public boolean resume(Object entity)
252266 {
253267 synchronized (responseLock)
254268 {
255269 if (done) return false;
256270 if (cancelled) return false;
257 try
258 {
259 return internalResume(entity);
260 } finally
261 {
262 done = true;
263 vertxFlush();
264 }
271 done = true;
272 return internalResume(entity, t -> vertxFlush());
265273 }
266274 }
267275
272280 {
273281 if (done) return false;
274282 if (cancelled) return false;
275 try
276 {
277 return internalResume(ex);
278 } catch (UnhandledException unhandled)
279 {
280 return internalResume(Response.status(500).build());
281 } finally
282 {
283 done = true;
284 vertxFlush();
285 }
283 done = true;
284 return internalResume(ex, t -> {
285 if(t instanceof UnhandledException) {
286 internalResume(Response.status(500).build(), t2 -> vertxFlush());
287 }
288 else
289 {
290 vertxFlush();
291 }
292 });
286293 }
287294 }
288295
301308 }
302309 done = true;
303310 cancelled = true;
304 try
305 {
306 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).build());
307 } finally
308 {
309 vertxFlush();
310 }
311 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).build(), t -> vertxFlush());
311312 }
312313 }
313314
320321 if (done) return false;
321322 done = true;
322323 cancelled = true;
323 try
324 {
325 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build());
326 } finally
327 {
328 vertxFlush();
329 }
324 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(),
325 t -> vertxFlush());
330326 }
331327 }
332328
351347 if (done) return false;
352348 done = true;
353349 cancelled = true;
354 try
355 {
356 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build());
357 } finally
358 {
359 vertxFlush();
360 }
350 return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(),
351 t -> vertxFlush());
361352 }
362353 }
363354
389380 {
390381 return false;
391382 }
392 timerID = context.owner().setTimer(unit.toMillis(time), v -> handleTimeout());
383 timerID = context.owner().setTimer(unit.toMillis(time), new Handler<Long>()
384 {
385 @Override
386 public void handle(Long v)
387 {
388 handleTimeout();
389 }
390 });
393391 }
394392 return true;
395393 }
00 package org.jboss.resteasy.plugins.server.vertx;
11
2 import io.vertx.core.Handler;
23 import io.vertx.core.http.HttpHeaders;
34 import io.vertx.core.http.HttpMethod;
45 import io.vertx.core.http.HttpServerResponse;
2526 private boolean committed;
2627 private ResteasyProviderFactory providerFactory;
2728 private final HttpMethod method;
29 private Throwable vertxException;
2830
2931 public VertxHttpResponse(HttpServerResponse response, ResteasyProviderFactory providerFactory)
3032 {
3840 os = (method == null || !method.equals(HttpMethod.HEAD)) ? new ChunkOutputStream(this, 1000) : null;
3941 this.response = response;
4042 this.providerFactory = providerFactory;
43 response.exceptionHandler(t -> vertxException = t);
44 response.closeHandler(v -> vertxException = new IOException("Connection closed"));
4145 }
4246
4347 @Override
7680 outputHeaders.add(javax.ws.rs.core.HttpHeaders.SET_COOKIE, cookie);
7781 }
7882
83 void checkException() throws IOException
84 {
85 if(vertxException instanceof IOException)
86 throw (IOException)vertxException;
87 if(vertxException != null)
88 throw new IOException(vertxException);
89 }
90
7991 @Override
8092 public void sendError(int status) throws IOException
8193 {
94 checkException();
8295 sendError(status, null);
8396 }
8497
8598 @Override
8699 public void sendError(int status, String message) throws IOException
87100 {
101 checkException();
88102 if (committed)
89103 {
90104 throw new IllegalStateException();
149163 committed = true;
150164 response.setStatusCode(getStatus());
151165 transformHeaders(this, response, providerFactory);
152 response.headersEndHandler(h -> {
153 response.headers().remove(HttpHeaders.CONTENT_LENGTH);
154 response.headers().set(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE);
166 response.headersEndHandler(new Handler<Void>()
167 {
168 @Override
169 public void handle(Void event)
170 {
171 response.headers().remove(HttpHeaders.CONTENT_LENGTH);
172 response.headers().set(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE);
173 }
155174 });
156175 }
157176
158177 public void finish() throws IOException
159178 {
179 checkException();
160180 if (os != null) {
161181 os.flush();
162182 if (!isCommitted())
168188 }
169189 response.end();
170190 }
191
192 @Override
193 public void flushBuffer() throws IOException {
194 checkException();
195 if(os != null) {
196 os.flush();
197 }
198 }
171199 }
88 import java.util.concurrent.TimeoutException;
99
1010 import io.vertx.core.AbstractVerticle;
11 import io.vertx.core.AsyncResult;
1112 import io.vertx.core.DeploymentOptions;
1213 import io.vertx.core.Future;
1314 import io.vertx.core.Handler;
124125 @Override
125126 public void start()
126127 {
127 vertx = Vertx.vertx(vertxOptions);
128 vertx = Vertx.factory.vertx(vertxOptions);
128129 deployment.start();
129 String key = UUID.randomUUID().toString();
130 final String key = UUID.randomUUID().toString();
130131 deploymentMap.put(key, new Helper(root, serverOptions, deployment, domain));
131132 // Configure the server.
132 CompletableFuture<String> fut = new CompletableFuture<>();
133 final CompletableFuture<String> fut = new CompletableFuture<>();
133134 DeploymentOptions deploymentOptions = new DeploymentOptions()
134135 .setInstances(vertxOptions.getEventLoopPoolSize())
135136 .setConfig(new JsonObject().put("helper", key));
136 vertx.deployVerticle(Verticle.class.getName(), deploymentOptions, ar -> {
137 deploymentMap.remove(key);
138 if (ar.succeeded())
139 {
140 fut.complete(ar.result());
141 } else
142 {
143 fut.completeExceptionally(ar.cause());
137
138 vertx.deployVerticle(Verticle.class.getName(), deploymentOptions, new Handler<AsyncResult<String>>()
139 {
140 @Override
141 public void handle(AsyncResult<String> ar)
142 {
143 deploymentMap.remove(key);
144 if (ar.succeeded())
145 {
146 fut.complete(ar.result());
147 }
148 else
149 {
150 fut.completeExceptionally(ar.cause());
151 }
152
144153 }
145154 });
146155 try
163172 {
164173 if (deploymentID != null)
165174 {
166 CompletableFuture<Void> fut = new CompletableFuture<>();
167 vertx.close(ar ->
168 {
169 fut.complete(null);
175 final CompletableFuture<Void> fut = new CompletableFuture<>();
176 vertx.close(new Handler<AsyncResult<Void>>()
177 {
178 @Override
179 public void handle(AsyncResult<Void> ar)
180 {
181 fut.complete(null);
182 }
170183 });
171184 deploymentID = null;
172185 try
208221 protected HttpServer server;
209222
210223 @Override
211 public void start(Future<Void> startFuture) throws Exception
224 public void start(final Future<Void> startFuture) throws Exception
212225 {
213226 Helper helper = deploymentMap.get(config().getString("helper"));
214227 server = vertx.createHttpServer(helper.serverOptions);
215228 server.requestHandler(new VertxRequestHandler(vertx, helper.deployment, helper.root, helper.domain));
216 server.listen(ar -> {
217 if (ar.succeeded())
218 {
219 startFuture.complete();
220 } else
221 {
222 startFuture.fail(ar.cause());
229 server.listen(new Handler<AsyncResult<HttpServer>>()
230 {
231 @Override
232 public void handle(AsyncResult<HttpServer> ar)
233 {
234 if (ar.succeeded())
235 {
236 startFuture.complete();
237 } else
238 {
239 startFuture.fail(ar.cause());
240 }
223241 }
224242 });
225243 }
171171 {
172172 delegate.addJndiResource(jndiName, resourceClass, basePath);
173173 }
174
175 @Override
176 public void checkAmbiguousUri()
177 {
178 //no-op
179 }
174180 }
33 import io.vertx.core.Context;
44 import io.vertx.core.Handler;
55 import io.vertx.core.Vertx;
6 import io.vertx.core.buffer.Buffer;
67 import io.vertx.core.http.HttpServerRequest;
78 import io.vertx.core.http.HttpServerResponse;
89 import org.jboss.resteasy.core.SynchronousDispatcher;
4445 }
4546
4647 @Override
47 public void handle(HttpServerRequest request)
48 public void handle(final HttpServerRequest request)
4849 {
49 request.bodyHandler(buff -> {
50 Context ctx = vertx.getOrCreateContext();
51 ResteasyUriInfo uriInfo = VertxUtil.extractUriInfo(request, servletMappingPrefix);
52 ResteasyHttpHeaders headers = VertxUtil.extractHttpHeaders(request);
53 HttpServerResponse response = request.response();
54 VertxHttpResponse vertxResponse = new VertxHttpResponse(response, dispatcher.getProviderFactory(), request.method());
55 VertxHttpRequest vertxRequest = new VertxHttpRequest(ctx, headers, uriInfo, request.rawMethod(), dispatcher.getDispatcher(), vertxResponse, false);
56 if (buff.length() > 0)
50 request.bodyHandler(new Handler<Buffer>()
51 {
52 @Override
53 public void handle(Buffer buff)
5754 {
58 ByteBufInputStream in = new ByteBufInputStream(buff.getByteBuf());
59 vertxRequest.setInputStream(in);
60 }
55 Context ctx = vertx.getOrCreateContext();
56 ResteasyUriInfo uriInfo = VertxUtil.extractUriInfo(request, servletMappingPrefix);
57 ResteasyHttpHeaders headers = VertxUtil.extractHttpHeaders(request);
58 HttpServerResponse response = request.response();
59 VertxHttpResponse vertxResponse = new VertxHttpResponse(response, dispatcher.getProviderFactory(), request.method());
60 VertxHttpRequest vertxRequest = new VertxHttpRequest(ctx, headers, uriInfo, request.rawMethod(), dispatcher.getDispatcher(), vertxResponse, false);
61 if (buff.length() > 0)
62 {
63 ByteBufInputStream in = new ByteBufInputStream(buff.getByteBuf());
64 vertxRequest.setInputStream(in);
65 }
6166
62 try
63 {
64 dispatcher.service(ctx, request, response, vertxRequest, vertxResponse, true);
65 } catch (Failure e1)
66 {
67 vertxResponse.setStatus(e1.getErrorCode());
68 } catch (Exception ex)
69 {
70 vertxResponse.setStatus(500);
71 LogMessages.LOGGER.error(Messages.MESSAGES.unexpected(), ex);
72 }
73
74 if (!vertxRequest.getAsyncContext().isSuspended())
75 {
7667 try
7768 {
78 vertxResponse.finish();
79 } catch (IOException e)
69 dispatcher.service(ctx, request, response, vertxRequest, vertxResponse, true);
70 } catch (Failure e1)
8071 {
81 e.printStackTrace();
72 vertxResponse.setStatus(e1.getErrorCode());
73 } catch (Exception ex)
74 {
75 vertxResponse.setStatus(500);
76 LogMessages.LOGGER.error(Messages.MESSAGES.unexpected(), ex);
8277 }
78
79 if (!vertxRequest.getAsyncContext().isSuspended())
80 {
81 try
82 {
83 vertxResponse.finish();
84 } catch (IOException e)
85 {
86 LogMessages.LOGGER.error(Messages.MESSAGES.unexpected(), e);
87 }
88 }
89
8390 }
8491 });
8592 }
3737 @Override
3838 public Object createResource(HttpRequest request, HttpResponse response, ResteasyProviderFactory factory)
3939 {
40 Context ctx = Vertx.currentContext();
40 Context ctx = Vertx.factory.context();
4141 if (ctx != null)
4242 {
4343 Object resource = ctx.get(id);
00 package org.jboss.resteasy.test;
11
22 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
3
4 import io.vertx.core.AsyncResult;
5 import io.vertx.core.Handler;
36 import io.vertx.core.Vertx;
47 import io.vertx.core.VertxOptions;
58 import io.vertx.core.http.HttpServer;
9194 VertxResteasyDeployment deployment = new VertxResteasyDeployment();
9295 deployment.start();
9396 deployment.getRegistry().addPerInstanceResource(Resource.class);
94 Vertx vertx = Vertx.vertx();
97 Vertx vertx = Vertx.factory.vertx();
9598 Client client = ClientBuilder.newClient();
9699 try
97100 {
98101 HttpServer server = vertx.createHttpServer();
99102 server.requestHandler(new VertxRequestHandler(vertx, deployment));
100 CompletableFuture<Void> listenLatch = new CompletableFuture<>();
101 server.listen(TestPortProvider.getPort(), ar -> {
102 if (ar.succeeded())
103 final CompletableFuture<Void> listenLatch = new CompletableFuture<>();
104 server.listen(TestPortProvider.getPort(), new Handler<AsyncResult<HttpServer>>()
105 {
106 @Override
107 public void handle(AsyncResult<HttpServer> ar)
103108 {
104 listenLatch.complete(null);
105 } else
106 {
107 listenLatch.completeExceptionally(ar.cause());
109 if (ar.succeeded())
110 {
111 listenLatch.complete(null);
112 } else
113 {
114 listenLatch.completeExceptionally(ar.cause());
115 }
108116 }
109117 });
110118 listenLatch.get(10, TimeUnit.SECONDS);
3434 Resteasy version for unit-tests and for client side of integration tests can be specified with ``-Dversion.resteasy.testsuite=RESTEASY_VERSION``
3535
3636 > mvn clean verify -Dserver.home=PATH_TO_WIDLFLY_HOME -Dversion.resteasy.testsuite=RESTEASY_VERSION
37
38 ### Jax-rs 2.0 mode
39 By default integration tests run with jax-rs 2.1 implementation enabled on the server side.
40 To run jax-rs 2.0 compatible mode use:
41 > mvn clean verify -Djaxrs20
3742
3843 ### IPv6 testing
3944 Use ``ipv6`` property and specify IP address for EAP binding for IPv6 testing. Example:
66 <parent>
77 <groupId>org.jboss.resteasy</groupId>
88 <artifactId>resteasy-testsuite</artifactId>
9 <version>3.1.4.Final</version>
9 <version>3.5.0.Final</version>
1010 <relativePath>../pom.xml</relativePath>
1111 </parent>
1212
7373
7474 <dependency>
7575 <groupId>org.jboss.resteasy</groupId>
76 <artifactId>resteasy-client</artifactId>
77 <version>${version.resteasy.testsuite}</version>
78 </dependency>
79
80 <dependency>
81 <groupId>org.jboss.resteasy</groupId>
8276 <artifactId>resteasy-validator-provider-11</artifactId>
8377 <version>${version.resteasy.testsuite}</version>
8478 </dependency>
0 package org.jboss.resteasy.category;
1
2 /**
3 * Marker interface for tests which are expected pass only with jax-rs 2.1
4 */
5 public class Jaxrs21 {
6 }
00 package org.jboss.resteasy.utils;
11
2 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
3 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
2 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Method for testing deprecated ClientRequest)
3 import org.jboss.resteasy.client.ClientRequestFactory;
4 import org.jboss.resteasy.client.ProxyFactory;
45
56 import java.net.MalformedURLException;
67 import java.net.URI;
5657 }
5758 }
5859
59 // /**
60 // * Create a Resteasy deprecated ClientRequest object using the configured port.
61 // *
62 // * @param path the request path
63 // * @return the ClientRequest object
64 // */
65 // public static ClientRequest createClientRequest(String path, String testName) {
66 // return new ClientRequest(generateURL(path, testName));
67 // }
68 //
69 // public static ClientRequest createClientRequest(ClientRequestFactory factory, String path, String testName) {
70 // return factory.createRequest(generateURL(path, testName));
71 // }
60 /**
61 * Create a Resteasy deprecated ClientRequest object using the configured port.
62 *
63 * @param path the request path
64 * @return the ClientRequest object
65 */
66 public static ClientRequest createClientRequest(String path, String testName) {
67 return new ClientRequest(generateURL(path, testName));
68 }
69
70 public static ClientRequest createClientRequest(ClientRequestFactory factory, String path, String testName) {
71 return factory.createRequest(generateURL(path, testName));
72 }
7273
7374 /**
7475 * Create a Resteasy client proxy with an empty base request path.
8889 * @path the base request path
8990 */
9091 public static <T> T createProxy(Class<T> clazz, String path, String testName) {
91 ResteasyWebTarget target = (ResteasyWebTarget) ResteasyClientBuilder.newClient().target(generateURL(path, testName));
92 return target.proxy(clazz);
92 return ProxyFactory.create(clazz, generateURL(path, testName));
9393 }
9494
9595 /**
66 <parent>
77 <groupId>org.jboss.resteasy</groupId>
88 <artifactId>resteasy-testsuite</artifactId>
9 <version>3.1.4.Final</version>
9 <version>3.5.0.Final</version>
1010 <relativePath>../pom.xml</relativePath>
1111 </parent>
1212
166166
167167 <dependency>
168168 <groupId>org.jboss.resteasy</groupId>
169 <artifactId>resteasy-json-binding-provider</artifactId>
170 <version>${version.resteasy.testsuite}</version>
171 <scope>provided</scope>
172 </dependency>
173
174 <dependency>
175 <groupId>org.jboss.resteasy</groupId>
169176 <artifactId>resteasy-yaml-provider</artifactId>
170177 <version>${version.resteasy.testsuite}</version>
171178 <scope>provided</scope>
227234 <artifactId>resteasy-wadl-undertow-connector</artifactId>
228235 <version>${project.version}</version>
229236 </dependency>
230
237
231238 <dependency>
232239 <groupId>org.jboss.resteasy</groupId>
233240 <artifactId>resteasy-html</artifactId>
234241 <version>${project.version}</version>
235242 </dependency>
236
243
237244 <dependency>
238245 <groupId>org.apache.logging.log4j</groupId>
239246 <artifactId>log4j-api</artifactId>
285292 <artifactId>httpclient</artifactId>
286293 <scope>provided</scope>
287294 </dependency>
288
295 <dependency>
296 <groupId>org.apache.httpcomponents</groupId>
297 <artifactId>httpasyncclient</artifactId>
298 </dependency>
289299 <dependency>
290300 <groupId>org.hamcrest</groupId>
291301 <artifactId>hamcrest-all</artifactId>
302 </dependency>
303
304 <dependency>
305 <groupId>org.glassfish</groupId>
306 <artifactId>javax.el</artifactId>
307 <scope>test</scope>
292308 </dependency>
293309
294310 <dependency>
322338 <artifactId>wildfly-cli</artifactId>
323339 </dependency>
324340
341 <dependency>
342 <groupId>io.reactivex.rxjava2</groupId>
343 <artifactId>rxjava</artifactId>
344 <version>2.1.3</version>
345 </dependency>
325346 </dependencies>
326347
327348 <build>
340361 </excludes>
341362 </testResource>
342363 </testResources>
364 <plugins>
365 <plugin>
366 <artifactId>maven-surefire-plugin</artifactId>
367 <executions>
368 <execution>
369 <id>default-test</id>
370 <phase>test</phase>
371 <goals>
372 <goal>test</goal>
373 </goals>
374 <configuration>
375 <excludes>
376 <!-- Tests requires excluding JsonBindingProvider-->
377 <exclude>**/JsonBindingTest.java</exclude>
378 </excludes>
379 <classpathDependencyExcludes>
380 <classpathDependencyExcludes>org.jboss.resteasy:resteasy-json-binding-provider</classpathDependencyExcludes>
381 </classpathDependencyExcludes>
382 </configuration>
383 </execution>
384 <execution>
385 <!-- Add JsonBindingProvider tests here-->
386 <id>jsonb-test</id>
387 <phase>test</phase>
388 <goals>
389 <goal>test</goal>
390 </goals>
391 <configuration>
392 <includes>
393 <include>**/JsonBindingTest.java</include>
394 </includes>
395 </configuration>
396 </execution>
397 </executions>
398 </plugin>
399 </plugins>
343400 </build>
344401
345402 </project>
2222
2323 import javax.ws.rs.core.Response;
2424 import java.lang.reflect.ReflectPermission;
25 import java.net.SocketPermission;
26 import java.security.SecurityPermission;
2527 import java.util.PropertyPermission;
28 import java.util.logging.LoggingPermission;
2629
2730 /**
2831 * @tpSubChapter Asynchronous RESTEasy
4346 war.addAsWebInfResource(AsyncPostProcessingTest.class.getPackage(), "AsyncPostProcessingTestWeb.xml", "web.xml");
4447 // Arquillian in the deployment
4548 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
49 new LoggingPermission("control", ""),
50 new PropertyPermission("arquillian.*", "read"),
51 new PropertyPermission("ipv6", "read"),
52 new PropertyPermission("node", "read"),
53 new PropertyPermission("org.jboss.resteasy.port", "read"),
4654 new RuntimePermission("accessDeclaredMembers"),
47 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
55 new RuntimePermission("getenv.RESTEASY_PORT"),
56 new SecurityPermission("insertProvider"),
57 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
58 ), "permissions.xml");
4859 return TestUtil.finishContainerPrepare(war, null, AsyncPostProcessingResource.class,
4960 AsyncPostProcessingMsgBodyWriterInterceptor.class, AsyncPostProcessingInterceptor.class);
5061 }
0 package org.jboss.resteasy.test.asynch;
1
2 import static org.junit.Assert.assertEquals;
3
4 import javax.ws.rs.client.Client;
5 import javax.ws.rs.client.ClientBuilder;
6 import javax.ws.rs.client.WebTarget;
7 import javax.ws.rs.core.Response;
8
9 import org.apache.logging.log4j.LogManager;
10 import org.apache.logging.log4j.Logger;
11 import org.jboss.arquillian.container.test.api.Deployment;
12 import org.jboss.arquillian.container.test.api.RunAsClient;
13 import org.jboss.arquillian.junit.Arquillian;
14 import org.jboss.resteasy.test.asynch.resource.AsyncPreMatchRequestFilter1;
15 import org.jboss.resteasy.test.asynch.resource.AsyncPreMatchRequestFilter2;
16 import org.jboss.resteasy.test.asynch.resource.AsyncPreMatchRequestFilter3;
17 import org.jboss.resteasy.test.asynch.resource.AsyncRequestFilter;
18 import org.jboss.resteasy.test.asynch.resource.AsyncRequestFilter1;
19 import org.jboss.resteasy.test.asynch.resource.AsyncRequestFilter2;
20 import org.jboss.resteasy.test.asynch.resource.AsyncRequestFilter3;
21 import org.jboss.resteasy.test.asynch.resource.AsyncRequestFilterResource;
22 import org.jboss.resteasy.test.asynch.resource.AsyncResponseFilter;
23 import org.jboss.resteasy.test.asynch.resource.AsyncResponseFilter1;
24 import org.jboss.resteasy.test.asynch.resource.AsyncResponseFilter2;
25 import org.jboss.resteasy.test.asynch.resource.AsyncResponseFilter3;
26 import org.jboss.resteasy.utils.PortProviderUtil;
27 import org.jboss.resteasy.utils.TestUtil;
28 import org.jboss.shrinkwrap.api.Archive;
29 import org.jboss.shrinkwrap.api.spec.WebArchive;
30 import org.junit.Test;
31 import org.junit.runner.RunWith;
32
33 /**
34 * @tpSubChapter CDI
35 * @tpChapter Integration tests
36 * @tpTestCaseDetails Async Request Filter test.
37 * @tpSince RESTEasy 3.5
38 */
39 @RunWith(Arquillian.class)
40 @RunAsClient
41 public class AsyncRequestFilterTest {
42 protected static final Logger log = LogManager.getLogger(AsyncRequestFilterTest.class.getName());
43
44 @Deployment
45 public static Archive<?> createTestArchive() {
46
47 WebArchive war = TestUtil.prepareArchive(AsyncRequestFilterTest.class.getSimpleName());
48 war.addClasses(AsyncRequestFilterResource.class, AsyncRequestFilter.class, AsyncResponseFilter.class,
49 AsyncRequestFilter1.class, AsyncRequestFilter2.class, AsyncRequestFilter3.class,
50 AsyncPreMatchRequestFilter1.class, AsyncPreMatchRequestFilter2.class, AsyncPreMatchRequestFilter3.class,
51 AsyncResponseFilter1.class, AsyncResponseFilter2.class, AsyncResponseFilter3.class);
52 return war;
53 }
54
55 private String generateURL(String path) {
56 return PortProviderUtil.generateURL(path, AsyncRequestFilterTest.class.getSimpleName());
57 }
58
59 /**
60 * @tpTestDetails Interceptors work
61 * @tpSince RESTEasy 3.5
62 */
63 @Test
64 public void testRequestFilters() throws Exception {
65 Client client = ClientBuilder.newClient();
66
67 // Create book.
68 WebTarget base = client.target(generateURL("/"));
69
70 // all sync
71
72 Response response = base.request()
73 .header("Filter1", "sync-pass")
74 .header("Filter2", "sync-pass")
75 .header("Filter3", "sync-pass")
76 .get();
77 assertEquals(200, response.getStatus());
78 assertEquals("resource", response.readEntity(String.class));
79
80 response = base.request()
81 .header("Filter1", "sync-fail")
82 .header("Filter2", "sync-fail")
83 .header("Filter3", "sync-fail")
84 .get();
85 assertEquals(200, response.getStatus());
86 assertEquals("Filter1", response.readEntity(String.class));
87
88 response = base.request()
89 .header("Filter1", "sync-pass")
90 .header("Filter2", "sync-fail")
91 .header("Filter3", "sync-fail")
92 .get();
93 assertEquals(200, response.getStatus());
94 assertEquals("Filter2", response.readEntity(String.class));
95
96 response = base.request()
97 .header("Filter1", "sync-pass")
98 .header("Filter2", "sync-pass")
99 .header("Filter3", "sync-fail")
100 .get();
101 assertEquals(200, response.getStatus());
102 assertEquals("Filter3", response.readEntity(String.class));
103
104 // async
105 response = base.request()
106 .header("Filter1", "async-pass")
107 .header("Filter2", "sync-pass")
108 .header("Filter3", "sync-pass")
109 .get();
110 assertEquals(200, response.getStatus());
111 assertEquals("resource", response.readEntity(String.class));
112
113 response = base.request()
114 .header("Filter1", "async-pass")
115 .header("Filter2", "async-pass")
116 .header("Filter3", "sync-pass")
117 .get();
118 assertEquals(200, response.getStatus());
119 assertEquals("resource", response.readEntity(String.class));
120
121 response = base.request()
122 .header("Filter1", "async-pass")
123 .header("Filter2", "async-pass")
124 .header("Filter3", "async-pass")
125 .get();
126 assertEquals(200, response.getStatus());
127 assertEquals("resource", response.readEntity(String.class));
128
129 response = base.request()
130 .header("Filter1", "async-pass")
131 .header("Filter2", "sync-pass")
132 .header("Filter3", "async-pass")
133 .get();
134 assertEquals(200, response.getStatus());
135 assertEquals("resource", response.readEntity(String.class));
136
137 response = base.request()
138 .header("Filter1", "sync-pass")
139 .header("Filter2", "async-pass")
140 .header("Filter3", "sync-pass")
141 .get();
142 assertEquals(200, response.getStatus());
143 assertEquals("resource", response.readEntity(String.class));
144
145 // async failures
146
147 response = base.request()
148 .header("Filter1", "async-fail")
149 .header("Filter2", "sync-fail")
150 .header("Filter3", "sync-fail")
151 .get();
152 assertEquals(200, response.getStatus());
153 assertEquals("Filter1", response.readEntity(String.class));
154
155 response = base.request()
156 .header("Filter1", "async-pass")
157 .header("Filter2", "sync-fail")
158 .header("Filter3", "sync-pass")
159 .get();
160 assertEquals(200, response.getStatus());
161 assertEquals("Filter2", response.readEntity(String.class));
162
163 response = base.request()
164 .header("Filter1", "async-pass")
165 .header("Filter2", "async-fail")
166 .header("Filter3", "sync-pass")
167 .get();
168 assertEquals(200, response.getStatus());
169 assertEquals("Filter2", response.readEntity(String.class));
170
171 // async instantaneous
172 response = base.request()
173 .header("Filter1", "async-pass-instant")
174 .header("Filter2", "sync-pass")
175 .header("Filter3", "sync-pass")
176 .get();
177 assertEquals(200, response.getStatus());
178 assertEquals("resource", response.readEntity(String.class));
179
180 response = base.request()
181 .header("Filter1", "async-fail-instant")
182 .header("Filter2", "sync-pass")
183 .header("Filter3", "sync-pass")
184 .get();
185 assertEquals(200, response.getStatus());
186 assertEquals("Filter1", response.readEntity(String.class));
187
188 client.close();
189 }
190
191 /**
192 * @tpTestDetails Interceptors work
193 * @tpSince RESTEasy 3.5
194 */
195 @Test
196 public void testPreMatchRequestFilters() throws Exception {
197 Client client = ClientBuilder.newClient();
198
199 // Create book.
200 WebTarget base = client.target(generateURL("/"));
201
202 // all sync
203
204 Response response = base.request()
205 .header("PreMatchFilter1", "sync-pass")
206 .header("PreMatchFilter2", "sync-pass")
207 .header("PreMatchFilter3", "sync-pass")
208 .get();
209 assertEquals(200, response.getStatus());
210 assertEquals("resource", response.readEntity(String.class));
211
212 response = base.request()
213 .header("PreMatchFilter1", "sync-fail")
214 .header("PreMatchFilter2", "sync-fail")
215 .header("PreMatchFilter3", "sync-fail")
216 .get();
217 assertEquals(200, response.getStatus());
218 assertEquals("PreMatchFilter1", response.readEntity(String.class));
219
220 response = base.request()
221 .header("PreMatchFilter1", "sync-pass")
222 .header("PreMatchFilter2", "sync-fail")
223 .header("PreMatchFilter3", "sync-fail")
224 .get();
225 assertEquals(200, response.getStatus());
226 assertEquals("PreMatchFilter2", response.readEntity(String.class));
227
228 response = base.request()
229 .header("PreMatchFilter1", "sync-pass")
230 .header("PreMatchFilter2", "sync-pass")
231 .header("PreMatchFilter3", "sync-fail")
232 .get();
233 assertEquals(200, response.getStatus());
234 assertEquals("PreMatchFilter3", response.readEntity(String.class));
235
236 // async
237 response = base.request()
238 .header("PreMatchFilter1", "async-pass")
239 .header("PreMatchFilter2", "sync-pass")
240 .header("PreMatchFilter3", "sync-pass")
241 .get();
242 assertEquals("resource", response.readEntity(String.class));
243 assertEquals(200, response.getStatus());
244
245 response = base.request()
246 .header("PreMatchFilter1", "async-pass")
247 .header("PreMatchFilter2", "async-pass")
248 .header("PreMatchFilter3", "sync-pass")
249 .get();
250 assertEquals(200, response.getStatus());
251 assertEquals("resource", response.readEntity(String.class));
252
253 response = base.request()
254 .header("PreMatchFilter1", "async-pass")
255 .header("PreMatchFilter2", "async-pass")
256 .header("PreMatchFilter3", "async-pass")
257 .get();
258 assertEquals(200, response.getStatus());
259 assertEquals("resource", response.readEntity(String.class));
260
261 response = base.request()
262 .header("PreMatchFilter1", "async-pass")
263 .header("PreMatchFilter2", "sync-pass")
264 .header("PreMatchFilter3", "async-pass")
265 .get();
266 assertEquals(200, response.getStatus());
267 assertEquals("resource", response.readEntity(String.class));
268
269 response = base.request()
270 .header("PreMatchFilter1", "sync-pass")
271 .header("PreMatchFilter2", "async-pass")
272 .header("PreMatchFilter3", "sync-pass")
273 .get();
274 assertEquals(200, response.getStatus());
275 assertEquals("resource", response.readEntity(String.class));
276
277 // async failures
278
279 response = base.request()
280 .header("PreMatchFilter1", "async-fail")
281 .header("PreMatchFilter2", "sync-fail")
282 .header("PreMatchFilter3", "sync-fail")
283 .get();
284 assertEquals(200, response.getStatus());
285 assertEquals("PreMatchFilter1", response.readEntity(String.class));
286
287 response = base.request()
288 .header("PreMatchFilter1", "async-pass")
289 .header("PreMatchFilter2", "sync-fail")
290 .header("PreMatchFilter3", "sync-pass")
291 .get();
292 assertEquals(200, response.getStatus());
293 assertEquals("PreMatchFilter2", response.readEntity(String.class));
294
295 response = base.request()
296 .header("PreMatchFilter1", "async-pass")
297 .header("PreMatchFilter2", "async-fail")
298 .header("PreMatchFilter3", "sync-pass")
299 .get();
300 assertEquals(200, response.getStatus());
301 assertEquals("PreMatchFilter2", response.readEntity(String.class));
302
303 client.close();
304 }
305
306 /**
307 * @tpTestDetails Interceptors work
308 * @tpSince RESTEasy 3.5
309 */
310 @Test
311 public void testResponseFilters() throws Exception {
312 Client client = ClientBuilder.newClient();
313
314 // Create book.
315 WebTarget base = client.target(generateURL("/"));
316
317 // all sync
318
319 Response response = base.request()
320 .header("ResponseFilter1", "sync-pass")
321 .header("ResponseFilter2", "sync-pass")
322 .header("ResponseFilter3", "sync-pass")
323 .get();
324 assertEquals(200, response.getStatus());
325 assertEquals("resource", response.readEntity(String.class));
326
327 response = base.request()
328 .header("ResponseFilter1", "sync-fail")
329 .header("ResponseFilter2", "sync-pass")
330 .header("ResponseFilter3", "sync-pass")
331 .get();
332 assertEquals(200, response.getStatus());
333 assertEquals("ResponseFilter1", response.readEntity(String.class));
334
335 response = base.request()
336 .header("ResponseFilter1", "sync-pass")
337 .header("ResponseFilter2", "sync-fail")
338 .header("ResponseFilter3", "sync-pass")
339 .get();
340 assertEquals(200, response.getStatus());
341 assertEquals("ResponseFilter2", response.readEntity(String.class));
342
343 response = base.request()
344 .header("ResponseFilter1", "sync-pass")
345 .header("ResponseFilter2", "sync-pass")
346 .header("ResponseFilter3", "sync-fail")
347 .get();
348 assertEquals(200, response.getStatus());
349 assertEquals("ResponseFilter3", response.readEntity(String.class));
350
351 // async
352 response = base.request()
353 .header("ResponseFilter1", "async-pass")
354 .header("ResponseFilter2", "sync-pass")
355 .header("ResponseFilter3", "sync-pass")
356 .get();
357 assertEquals("resource", response.readEntity(String.class));
358 assertEquals(200, response.getStatus());
359
360 response = base.request()
361 .header("ResponseFilter1", "async-pass")
362 .header("ResponseFilter2", "async-pass")
363 .header("ResponseFilter3", "sync-pass")
364 .get();
365 assertEquals(200, response.getStatus());
366 assertEquals("resource", response.readEntity(String.class));
367
368 response = base.request()
369 .header("ResponseFilter1", "async-pass")
370 .header("ResponseFilter2", "async-pass")
371 .header("ResponseFilter3", "async-pass")
372 .get();
373 assertEquals(200, response.getStatus());
374 assertEquals("resource", response.readEntity(String.class));
375
376 response = base.request()
377 .header("ResponseFilter1", "async-pass")
378 .header("ResponseFilter2", "sync-pass")
379 .header("ResponseFilter3", "async-pass")
380 .get();
381 assertEquals(200, response.getStatus());
382 assertEquals("resource", response.readEntity(String.class));
383
384 response = base.request()
385 .header("ResponseFilter1", "sync-pass")
386 .header("ResponseFilter2", "async-pass")
387 .header("ResponseFilter3", "sync-pass")
388 .get();
389 assertEquals(200, response.getStatus());
390 assertEquals("resource", response.readEntity(String.class));
391
392 // async failures
393
394 response = base.request()
395 .header("ResponseFilter1", "async-fail")
396 .header("ResponseFilter2", "sync-pass")
397 .header("ResponseFilter3", "sync-pass")
398 .get();
399 assertEquals(200, response.getStatus());
400 assertEquals("ResponseFilter1", response.readEntity(String.class));
401
402 response = base.request()
403 .header("ResponseFilter1", "async-pass")
404 .header("ResponseFilter2", "sync-fail")
405 .header("ResponseFilter3", "sync-pass")
406 .get();
407 assertEquals(200, response.getStatus());
408 assertEquals("ResponseFilter2", response.readEntity(String.class));
409
410 response = base.request()
411 .header("ResponseFilter1", "async-pass")
412 .header("ResponseFilter2", "async-fail")
413 .header("ResponseFilter3", "sync-pass")
414 .get();
415 assertEquals(200, response.getStatus());
416 assertEquals("ResponseFilter2", response.readEntity(String.class));
417
418 // async instantaneous
419 response = base.request()
420 .header("ResponseFilter1", "async-pass-instant")
421 .header("ResponseFilter2", "sync-pass")
422 .header("ResponseFilter3", "sync-pass")
423 .get();
424 assertEquals(200, response.getStatus());
425 assertEquals("resource", response.readEntity(String.class));
426
427 response = base.request()
428 .header("ResponseFilter1", "async-fail-instant")
429 .header("ResponseFilter2", "sync-pass")
430 .header("ResponseFilter3", "sync-pass")
431 .get();
432 assertEquals(200, response.getStatus());
433 assertEquals("ResponseFilter1", response.readEntity(String.class));
434
435 client.close();
436 }
437 /**
438 * @tpTestDetails Interceptors work
439 * @tpSince RESTEasy 3.5
440 */
441 @Test
442 public void testResponseFilters2() throws Exception {
443 Client client = ClientBuilder.newClient();
444
445 // Create book.
446 WebTarget base = client.target(generateURL("/async"));
447
448 // async way later
449 Response response = base.request()
450 .header("ResponseFilter1", "sync-pass")
451 .header("ResponseFilter2", "sync-pass")
452 .header("ResponseFilter3", "async-fail-late")
453 .get();
454 assertEquals(200, response.getStatus());
455 assertEquals("ResponseFilter3", response.readEntity(String.class));
456
457 client.close();
458 }
459 }
1919 import javax.ws.rs.core.HttpHeaders;
2020 import javax.ws.rs.core.Response;
2121 import java.lang.reflect.ReflectPermission;
22 import java.net.SocketPermission;
2223 import java.util.ArrayList;
2324 import java.util.HashMap;
2425 import java.util.Map;
2526 import java.util.PropertyPermission;
2627 import java.util.concurrent.CountDownLatch;
2728 import java.util.concurrent.TimeUnit;
29 import java.util.logging.LoggingPermission;
2830
2931 import static org.jboss.resteasy.utils.PortProviderUtil.generateURL;
3032
5658 }
5759 // Arquillian in the deployment
5860 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
61 new LoggingPermission("control", ""),
62 new PropertyPermission("arquillian.*", "read"),
63 new PropertyPermission("ipv6", "read"),
64 new PropertyPermission("node", "read"),
65 new PropertyPermission("org.jboss.resteasy.port", "read"),
5966 new RuntimePermission("accessDeclaredMembers"),
60 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
67 new RuntimePermission("getenv.RESTEASY_PORT"),
68 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
69 ), "permissions.xml");
6170 return TestUtil.finishContainerPrepare(war, contextParam, AsynchBasicResource.class);
6271 }
6372
2222 import org.junit.BeforeClass;
2323 import org.junit.Test;
2424 import org.junit.runner.RunWith;
25 import org.junit.experimental.categories.Category;
26 import org.jboss.resteasy.category.NotForForwardCompatibility;
2527
2628 /**
2729 * @tpSubChapter Asynchronous RESTEasy: RESTEASY-1225
6365 * @tpSince RESTEasy 3.1.1.Final
6466 */
6567 @Test
68 @Category(NotForForwardCompatibility.class)
6669 public void testContextualData() throws Exception {
6770 String id = "334";
6871
2828 * @tpSubChapter Asynchronous RESTEasy
2929 * @tpChapter Integration tests
3030 * @tpTestCaseDetails Tests use of SecureRandom to generate location job ids, RESTEASY-1483
31 * @tpSince RESTEasy 3.1.0.Final
31 * @tpSince RESTEasy 3.0.20.Final
3232 */
3333 @RunWith(Arquillian.class)
3434 @RunAsClient
6363 /**
6464 * @tpTestDetails Test that job ids are no longer consecutive
6565 * @tpInfo RESTEASY-1483
66 * @tpSince RESTEasy 3.1.0.Final
66 * @tpSince RESTEasy 3.0.20.Final
6767 */
6868 @Test
6969 public void testAsynchCounter() throws Exception {
00 package org.jboss.resteasy.test.asynch.resource;
11
2 import java.io.IOException;
3
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerResponseContext;
6 import javax.ws.rs.container.ContainerResponseFilter;
72 import javax.ws.rs.ext.Provider;
83
4 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
5 import org.jboss.resteasy.core.ServerResponse;
6 import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
7
98 @Provider
10 public class AsyncPostProcessingInterceptor implements ContainerResponseFilter {
9 @ServerInterceptor
10 public class AsyncPostProcessingInterceptor implements PostProcessInterceptor {
1111 public static boolean called;
1212
13 @Override
14 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
15 throws IOException
16 {
17 called = true;
18 }
13 @Override
14 public void postProcess(ServerResponse response) {
15 called = true;
16 }
1917 }
33
44 import javax.ws.rs.WebApplicationException;
55 import javax.ws.rs.ext.Provider;
6 import javax.ws.rs.ext.WriterInterceptor;
7 import javax.ws.rs.ext.WriterInterceptorContext;
6
7 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
8 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
9 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
810
911 @Provider
10 public class AsyncPostProcessingMsgBodyWriterInterceptor implements WriterInterceptor {
12 @ServerInterceptor
13 public class AsyncPostProcessingMsgBodyWriterInterceptor implements MessageBodyWriterInterceptor {
1114 public static boolean called;
1215
13 @Override
14 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
15 {
16 called = true;
17 context.proceed();
18 }
16 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
17 called = true;
18 context.proceed();
19 }
1920 }
00 package org.jboss.resteasy.test.asynch.resource;
1
2 import java.util.concurrent.TimeUnit;
31
42 import javax.ws.rs.GET;
53 import javax.ws.rs.Path;
6 import javax.ws.rs.container.AsyncResponse;
7 import javax.ws.rs.container.Suspended;
84 import javax.ws.rs.core.Response;
95
106 import org.jboss.logging.Logger;
7 import org.jboss.resteasy.annotations.Suspend;
8 import org.jboss.resteasy.spi.AsynchronousResponse;
119
1210 @Path("/")
1311 public class AsyncPostProcessingResource {
2220
2321 @GET
2422 @Path("async/delay")
25 public void asyncDelay(@Suspended final AsyncResponse response) throws Exception {
26 response.setTimeout(10000, TimeUnit.MILLISECONDS);
23 public void asyncDelay(@Suspend(10000) final AsynchronousResponse response) throws Exception {
2724 Thread t = new Thread() {
2825 @Override
2926 public void run() {
3027 try {
3128 Thread.sleep(5000);
3229 Response jaxrs = Response.ok("async/delay").build();
33 response.resume(jaxrs);
30 response.setResponse(jaxrs);
3431 } catch (Exception e) {
3532 logger.info("Error: " + e.getStackTrace());
3633 }
4138
4239 @GET
4340 @Path("async/nodelay")
44 public void asyncNoDelay(@Suspended final AsyncResponse response) throws Exception {
45 response.setTimeout(10000, TimeUnit.MILLISECONDS);
41 public void asyncNoDelay(@Suspend(10000) final AsynchronousResponse response) throws Exception {
4642 Response jaxrs = Response.ok("async/nodelay").build();
47 response.resume(jaxrs);
43 response.setResponse(jaxrs);
4844 }
4945
5046 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.container.PreMatching;
4 import javax.ws.rs.ext.Provider;
5
6 @PreMatching
7 @Priority(1)
8 @Provider
9 public class AsyncPreMatchRequestFilter1 extends AsyncRequestFilter {
10
11 public AsyncPreMatchRequestFilter1()
12 {
13 super("PreMatchFilter1");
14 }
15 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.container.PreMatching;
4 import javax.ws.rs.ext.Provider;
5
6 @PreMatching
7 @Priority(2)
8 @Provider
9 public class AsyncPreMatchRequestFilter2 extends AsyncRequestFilter {
10
11 public AsyncPreMatchRequestFilter2()
12 {
13 super("PreMatchFilter2");
14 }
15 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.container.PreMatching;
4 import javax.ws.rs.ext.Provider;
5
6 @PreMatching
7 @Priority(3)
8 @Provider
9 public class AsyncPreMatchRequestFilter3 extends AsyncRequestFilter {
10
11 public AsyncPreMatchRequestFilter3()
12 {
13 super("PreMatchFilter3");
14 }
15 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import java.io.IOException;
3 import java.util.concurrent.ExecutorService;
4 import java.util.concurrent.Executors;
5
6 import javax.ws.rs.container.ContainerRequestContext;
7 import javax.ws.rs.container.ContainerRequestFilter;
8 import javax.ws.rs.core.Response;
9
10 import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerRequestContext;
11
12 public abstract class AsyncRequestFilter implements ContainerRequestFilter {
13
14 private String name;
15
16 public AsyncRequestFilter(String name)
17 {
18 this.name = name;
19 }
20
21 @Override
22 public void filter(ContainerRequestContext requestContext) throws IOException
23 {
24 SuspendableContainerRequestContext ctx = (SuspendableContainerRequestContext) requestContext;
25 String action = ctx.getHeaderString(name);
26 System.err.println("Filter request for "+name+" with action: "+action);
27 if("sync-pass".equals(action)) {
28 // do nothing
29 }else if("sync-fail".equals(action)) {
30 ctx.abortWith(Response.ok(name).build());
31 }else if("async-pass".equals(action)) {
32 ctx.suspend();
33 ExecutorService executor = Executors.newSingleThreadExecutor();
34 executor.submit(() -> ctx.resume());
35 }else if("async-pass-instant".equals(action)) {
36 ctx.suspend();
37 ctx.resume();
38 }else if("async-fail".equals(action)) {
39 ctx.suspend();
40 ExecutorService executor = Executors.newSingleThreadExecutor();
41 executor.submit(() -> ctx.abortWith(Response.ok(name).build()));
42 }else if("async-fail-instant".equals(action)) {
43 ctx.suspend();
44 ctx.abortWith(Response.ok(name).build());
45 }
46 System.err.println("Filter request for "+name+" with action: "+action+" done");
47 }
48
49 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.ext.Provider;
4
5 @Priority(1)
6 @Provider
7 public class AsyncRequestFilter1 extends AsyncRequestFilter {
8
9 public AsyncRequestFilter1()
10 {
11 super("Filter1");
12 }
13 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.ext.Provider;
4
5 @Priority(2)
6 @Provider
7 public class AsyncRequestFilter2 extends AsyncRequestFilter {
8
9 public AsyncRequestFilter2()
10 {
11 super("Filter2");
12 }
13 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.ext.Provider;
4
5 @Priority(3)
6 @Provider
7 public class AsyncRequestFilter3 extends AsyncRequestFilter {
8
9 public AsyncRequestFilter3()
10 {
11 super("Filter3");
12 }
13 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import java.util.concurrent.CompletableFuture;
3 import java.util.concurrent.CompletionStage;
4 import java.util.concurrent.ExecutorService;
5 import java.util.concurrent.Executors;
6
7 import javax.ws.rs.DefaultValue;
8 import javax.ws.rs.GET;
9 import javax.ws.rs.HeaderParam;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.core.Context;
12 import javax.ws.rs.core.Response;
13
14 import org.jboss.resteasy.spi.HttpRequest;
15
16 @Path("/")
17 public class AsyncRequestFilterResource {
18
19 @GET
20 public Response threeSyncRequestFilters(@Context HttpRequest request,
21 @HeaderParam("Filter1") @DefaultValue("") String filter1,
22 @HeaderParam("Filter2") @DefaultValue("") String filter2,
23 @HeaderParam("Filter3") @DefaultValue("") String filter3,
24 @HeaderParam("PreMatchFilter1") @DefaultValue("") String preMatchFilter1,
25 @HeaderParam("PreMatchFilter2") @DefaultValue("") String preMatchFilter2,
26 @HeaderParam("PreMatchFilter3") @DefaultValue("") String preMatchFilter3) {
27 boolean async = isAsync(filter1)
28 || isAsync(filter2)
29 || isAsync(filter3)
30 || isAsync(preMatchFilter1)
31 || isAsync(preMatchFilter2)
32 || isAsync(preMatchFilter3);
33 if(async != request.getAsyncContext().isSuspended())
34 return Response.serverError().entity("Request suspention is wrong").build();
35 return Response.ok("resource").build();
36 }
37
38 @Path("async")
39 @GET
40 public CompletionStage<Response> async() {
41 ExecutorService executor = Executors.newSingleThreadExecutor();
42 CompletableFuture<Response> resp = new CompletableFuture<>();
43 executor.submit(() -> {
44 try
45 {
46 Thread.sleep(2000);
47 } catch (InterruptedException e)
48 {
49 // TODO Auto-generated catch block
50 e.printStackTrace();
51 }
52 resp.complete(Response.ok("resource").build());
53 });
54 return resp;
55 }
56
57 private boolean isAsync(String filter)
58 {
59 return filter.equals("async-pass")
60 || filter.equals("async-fail");
61 }
62 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import java.io.IOException;
3 import java.util.concurrent.ExecutorService;
4 import java.util.concurrent.Executors;
5
6 import javax.ws.rs.container.ContainerRequestContext;
7 import javax.ws.rs.container.ContainerResponseContext;
8 import javax.ws.rs.container.ContainerResponseFilter;
9 import javax.ws.rs.core.Response;
10
11 import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerResponseContext;
12
13 public abstract class AsyncResponseFilter implements ContainerResponseFilter {
14
15 private String name;
16
17 public AsyncResponseFilter(String name)
18 {
19 this.name = name;
20 }
21
22 @Override
23 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
24 throws IOException
25 {
26 SuspendableContainerResponseContext ctx = (SuspendableContainerResponseContext) responseContext;
27 String action = requestContext.getHeaderString(name);
28 System.err.println("Filter response for "+name+" with action: "+action);
29 if("sync-pass".equals(action)) {
30 // do nothing
31 }else if("sync-fail".equals(action)) {
32 ctx.setEntity(name);
33 }else if("async-pass".equals(action)) {
34 ctx.suspend();
35 ExecutorService executor = Executors.newSingleThreadExecutor();
36 executor.submit(() -> ctx.resume());
37 }else if("async-pass-instant".equals(action)) {
38 ctx.suspend();
39 ctx.resume();
40 }else if("async-fail".equals(action)) {
41 ctx.suspend();
42 ExecutorService executor = Executors.newSingleThreadExecutor();
43 executor.submit(() -> {
44 ctx.setEntity(name);
45 ctx.resume();
46 });
47 }else if("async-fail-late".equals(action)) {
48 ctx.suspend();
49 ExecutorService executor = Executors.newSingleThreadExecutor();
50 executor.submit(() -> {
51 try
52 {
53 Thread.sleep(2000);
54 } catch (InterruptedException e)
55 {
56 // TODO Auto-generated catch block
57 e.printStackTrace();
58 }
59 ctx.setEntity(name);
60 ctx.resume();
61 });
62 }else if("async-fail-instant".equals(action)) {
63 ctx.suspend();
64 ctx.setEntity(name);
65 ctx.resume();
66 }
67 System.err.println("Filter response for "+name+" with action: "+action+" done");
68 }
69 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.container.PreMatching;
4 import javax.ws.rs.ext.Provider;
5
6 @Priority(1)
7 @Provider
8 public class AsyncResponseFilter1 extends AsyncResponseFilter {
9
10 public AsyncResponseFilter1()
11 {
12 super("ResponseFilter1");
13 }
14 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.container.PreMatching;
4 import javax.ws.rs.ext.Provider;
5
6 @Priority(2)
7 @Provider
8 public class AsyncResponseFilter2 extends AsyncResponseFilter {
9
10 public AsyncResponseFilter2()
11 {
12 super("ResponseFilter2");
13 }
14 }
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.container.PreMatching;
4 import javax.ws.rs.ext.Provider;
5
6 @Priority(3)
7 @Provider
8 public class AsyncResponseFilter3 extends AsyncResponseFilter {
9
10 public AsyncResponseFilter3()
11 {
12 super("ResponseFilter3");
13 }
14 }
00 package org.jboss.resteasy.test.asynch.resource;
11
22 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.annotations.Suspend;
4 import org.jboss.resteasy.spi.AsynchronousResponse;
35
46 import javax.ws.rs.GET;
57 import javax.ws.rs.Path;
68 import javax.ws.rs.Produces;
7 import javax.ws.rs.container.AsyncResponse;
8 import javax.ws.rs.container.Suspended;
99 import javax.ws.rs.core.MediaType;
1010 import javax.ws.rs.core.Response;
1111 import java.io.PrintWriter;
1212 import java.io.StringWriter;
13 import java.util.concurrent.TimeUnit;
1413
1514 /**
1615 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
2019 public class AsyncServletResource {
2120 @GET
2221 @Produces("text/plain")
23 public void get(@Suspended final AsyncResponse response) {
24 response.setTimeout(2000, TimeUnit.MILLISECONDS);
22 public void get(@Suspend(2000) final AsynchronousResponse response) {
2523 Thread t = new Thread() {
2624 private Logger log = Logger.getLogger(AsyncServletResource.class);
2725 @Override
2927 try {
3028 Thread.sleep(100);
3129 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
32 response.resume(jaxrs);
30 response.setResponse(jaxrs);
3331 } catch (Exception e) {
3432 StringWriter errors = new StringWriter();
3533 e.printStackTrace(new PrintWriter(errors));
4341 @GET
4442 @Path("timeout")
4543 @Produces("text/plain")
46 public void timeout(@Suspended final AsyncResponse response) {
47 response.setTimeout(10, TimeUnit.MILLISECONDS);
44 public void timeout(@Suspend(10) final AsynchronousResponse response) {
4845 Thread t = new Thread() {
4946 private Logger log = Logger.getLogger(AsyncServletResource.class);
5047 @Override
5249 try {
5350 Thread.sleep(100000);
5451 Response jaxrs = Response.ok("goodbye").type(MediaType.TEXT_PLAIN).build();
55 response.resume(jaxrs);
52 response.setResponse(jaxrs);
5653 } catch (Exception e) {
5754 StringWriter errors = new StringWriter();
5855 e.printStackTrace(new PrintWriter(errors));
1313 @Path("/")
1414 public class AsynchBasicResource {
1515
16 protected final Logger logger = Logger.getLogger(AsynchBasicResource.class.getName());
16 private static Logger logger = Logger.getLogger(AsynchBasicResource.class);
1717
1818 @Context
1919 private ServletConfig config;
00 package org.jboss.resteasy.test.asynch.resource;
11
22 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.annotations.Suspend;
4 import org.jboss.resteasy.spi.AsynchronousResponse;
5
36 import javax.ws.rs.GET;
47 import javax.ws.rs.Path;
58 import javax.ws.rs.Produces;
6 import javax.ws.rs.container.AsyncResponse;
7 import javax.ws.rs.container.Suspended;
89 import javax.ws.rs.core.MediaType;
910 import javax.ws.rs.core.Response;
10
1111 import java.io.PrintWriter;
1212 import java.io.StringWriter;
13 import java.util.concurrent.TimeUnit;
1413
1514 @Path("/")
1615 public class LegacySuspendResource {
1817
1918 @GET
2019 @Produces("text/plain")
21 public void get(@Suspended final AsyncResponse response) {
22 response.setTimeout(8000, TimeUnit.MILLISECONDS);
20 public void get(@Suspend(8000) final AsynchronousResponse response) {
2321 Thread t = new Thread() {
2422 @Override
2523 public void run() {
2624 try {
2725 Thread.sleep(100);
2826 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
29 response.resume(jaxrs);
27 response.setResponse(jaxrs);
3028 } catch (Exception e) {
3129 StringWriter errors = new StringWriter();
3230 e.printStackTrace(new PrintWriter(errors));
4038 @GET
4139 @Path("timeout")
4240 @Produces("text/plain")
43 public void timeout(@Suspended final AsyncResponse response) {
44 response.setTimeout(100, TimeUnit.MILLISECONDS);
41 public void timeout(@Suspend(100) final AsynchronousResponse response) {
4542 Thread t = new Thread() {
4643 @Override
4744 public void run() {
4845 try {
4946 Thread.sleep(1000);
5047 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
51 response.resume(jaxrs);
48 response.setResponse(jaxrs);
5249 } catch (Exception e) {
5350 StringWriter errors = new StringWriter();
5451 e.printStackTrace(new PrintWriter(errors));
6767 .addClasses(DecoratorsFilterBinding.class, DecoratorsTestRequestFilter.class, DecoratorsRequestFilterDecorator.class)
6868 .addClasses(DecoratorsResponseFilter.class, DecoratorsResponseFilterDecorator.class)
6969 .addAsWebInfResource(DecoratorsTest.class.getPackage(), "decoratorBeans.xml", "beans.xml");
70
7170 return war;
7271 }
7372
3636 import javax.ws.rs.client.WebTarget;
3737 import javax.ws.rs.core.Response;
3838 import java.lang.reflect.ReflectPermission;
39 import java.net.SocketPermission;
40 import java.security.SecurityPermission;
3941 import java.util.Hashtable;
4042 import java.util.PropertyPermission;
43 import java.util.logging.LoggingPermission;
4144
4245 import static org.junit.Assert.assertEquals;
4346
7679 .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
7780 // Arquillian in the deployment
7881 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
82 new LoggingPermission("control", ""),
83 new PropertyPermission("arquillian.*", "read"),
84 new PropertyPermission("ipv6", "read"),
85 new PropertyPermission("node", "read"),
86 new PropertyPermission("org.jboss.resteasy.port", "read"),
7987 new RuntimePermission("accessDeclaredMembers"),
80 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
88 new SecurityPermission("insertProvider"),
89 new RuntimePermission("getenv.RESTEASY_PORT"),
90 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
91 ), "permissions.xml");
8192 return war;
8293 }
8394
00 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
13
24 import javax.enterprise.event.Event;
35 import javax.inject.Inject;
911 import java.util.logging.Logger;
1012
1113 @Provider
14 @ServerInterceptor
1215 public class EventsBookReaderInterceptor implements ReaderInterceptor {
1316 @Inject
1417 @EventsReadIntercept
00 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
13
24 import javax.enterprise.event.Event;
35 import javax.inject.Inject;
911 import java.util.logging.Logger;
1012
1113 @Provider
14 @ServerInterceptor
1215 public class EventsBookWriterInterceptor implements WriterInterceptor {
1316 @Inject
1417 @EventsWriteIntercept
2727 import javax.ws.rs.client.Entity;
2828 import javax.ws.rs.client.WebTarget;
2929 import javax.ws.rs.core.Response;
30 import java.io.FilePermission;
3130 import java.lang.reflect.ReflectPermission;
31 import java.net.SocketPermission;
3232 import java.util.PropertyPermission;
3333 import java.util.logging.Logger;
3434 import java.util.logging.LoggingPermission;
5959 .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
6060 .addAsServiceProvider(Extension.class, ScopeExtensionPlannedObsolescenceExtension.class);
6161 // Arquillian in the deployment
62 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
62 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
63 new LoggingPermission("control", ""),
64 new PropertyPermission("arquillian.*", "read"),
65 new PropertyPermission("ipv6", "read"),
66 new PropertyPermission("node", "read"),
67 new PropertyPermission("org.jboss.resteasy.port", "read"),
68 new ReflectPermission("suppressAccessChecks"),
6369 new RuntimePermission("accessDeclaredMembers"),
64 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
70 new RuntimePermission("getenv.RESTEASY_PORT"),
71 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
72 ), "permissions.xml");
6573 return war;
6674 }
6775
44
55 import java.lang.reflect.ParameterizedType;
66 import java.lang.reflect.Type;
7 import java.net.SocketPermission;
78 import java.util.Collection;
89 import java.util.Iterator;
910
4243 import org.jboss.resteasy.test.cdi.util.PersistenceUnitProducer;
4344 import org.jboss.resteasy.test.cdi.util.UtilityProducer;
4445 import org.jboss.resteasy.util.HttpResponseCodes;
46 import org.jboss.resteasy.utils.PermissionUtil;
4547 import org.jboss.resteasy.utils.PortProviderUtil;
4648 import org.jboss.resteasy.utils.TestUtil;
4749 import org.jboss.shrinkwrap.api.Archive;
5254 import org.junit.BeforeClass;
5355 import org.junit.AfterClass;
5456 import org.junit.Before;
55 import org.junit.experimental.categories.Category;
5657 import org.junit.runner.RunWith;
5758
5859 /**
120121 .addClasses(Resource.class, CDIInjectionResourceProducer.class, PersistenceUnitProducer.class)
121122 .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
122123 .addAsResource(InjectionTest.class.getPackage(), "persistence.xml", "META-INF/persistence.xml");
124
125 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
126 new SocketPermission(PortProviderUtil.getHost(), "resolve")),
127 "permissions.xml");
128
123129 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
124130 }
125131
236242 invocationCounter++;
237243 log.info("Status: " + response.getStatus());
238244 @SuppressWarnings("unchecked")
239 Collection<CDIInjectionBook> books = response.readEntity(new GenericType<>(BookCollectionType));
245 Collection<CDIInjectionBook> books = (Collection<CDIInjectionBook>)response.readEntity(new GenericType<>(BookCollectionType));
240246 log.info("Collection from response: " + books);
241247 Assert.assertEquals(2, books.size());
242248 Iterator<CDIInjectionBook> it = books.iterator();
298304 log.info("status: " + response.getStatus());
299305 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
300306 @SuppressWarnings("unchecked")
301 Collection<CDIInjectionBook> books = response.readEntity(new GenericType<>(BookCollectionType));
307 Collection<CDIInjectionBook> books = (Collection<CDIInjectionBook>)response.readEntity(new GenericType<>(BookCollectionType));
302308 log.info("Collection from response: " + books);
303309 Assert.assertEquals(2, books.size());
304310 Iterator<CDIInjectionBook> it = books.iterator();
7070 import java.lang.reflect.ParameterizedType;
7171 import java.lang.reflect.ReflectPermission;
7272 import java.lang.reflect.Type;
73 import java.net.SocketPermission;
7374 import java.util.Collection;
7475 import java.util.Hashtable;
7576 import java.util.Iterator;
7677 import java.util.PropertyPermission;
78 import java.util.logging.LoggingPermission;
7779
7880 import static junit.framework.TestCase.assertEquals;
7981 import static org.junit.Assert.assertNotNull;
150152 .addAsResource(ReverseInjectionTest.class.getPackage(), "persistence.xml", "META-INF/persistence.xml");
151153 // Arquillian in the deployment
152154 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
155 new LoggingPermission("control", ""),
156 new PropertyPermission("arquillian.*", "read"),
157 new PropertyPermission("ipv6", "read"),
158 new PropertyPermission("node", "read"),
159 new PropertyPermission("org.jboss.resteasy.port", "read"),
153160 new RuntimePermission("accessDeclaredMembers"),
154 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
161 new RuntimePermission("getenv.RESTEASY_PORT"),
162 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
163 ), "permissions.xml");
155164 return war;
156165 }
157166
300309 log.info("status: " + response.getStatus());
301310 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
302311 @SuppressWarnings("unchecked")
303 Collection<CDIInjectionBook> books = response.readEntity(new GenericType<>(BookCollectionType));
312 Collection<CDIInjectionBook> books = (Collection<CDIInjectionBook>)response.readEntity(new GenericType<>(BookCollectionType));
304313 log.info("Collection: " + books);
305314 assertEquals("Wrong count of received items", 2, books.size());
306315 Iterator<CDIInjectionBook> it = books.iterator();
4141 * @tpChapter Integration tests
4242 * @tpTestCaseDetails Tests RESTEASY-1186, which reports issues with validation in
4343 * the presence of CDI.
44 * @tpSince RESTEasy 3.1.0
44 * @tpSince RESTEasy 3.0.20.Final
4545 */
4646 @RunWith(Arquillian.class)
4747 @RunAsClient
7171
7272 /**
7373 * @tpTestDetails Tests Bean Validation constraints on method parameters
74 * @tpSince RESTEasy 3.1.0
74 * @tpSince RESTEasy 3.0.20.Final
7575 */
7676 @Test
7777 public void testRoot() throws Exception
9191
9292 /**
9393 * @tpTestDetails Tests Bean Validation constraints on method parameters
94 * @tpSince RESTEasy 3.1.0
94 * @tpSince RESTEasy 3.0.20.Final
9595 */
9696 @Test
9797 @Category({NotForForwardCompatibility.class})
11
22
33 import java.io.UnsupportedEncodingException;
4 import java.util.logging.LoggingPermission;
45
56 import javax.ws.rs.client.Client;
67 import javax.ws.rs.client.ClientBuilder;
1213 import org.jboss.arquillian.junit.Arquillian;
1314 import org.jboss.resteasy.category.NotForForwardCompatibility;
1415 import org.jboss.resteasy.test.client.resource.AbortMessageResourceFilter;
16 import org.jboss.resteasy.utils.PermissionUtil;
1517 import org.jboss.resteasy.utils.PortProviderUtil;
1618 import org.jboss.resteasy.utils.TestUtil;
1719 import org.jboss.shrinkwrap.api.Archive;
2729 * @tpSubChapter Resteasy-client
2830 * @tpChapter Client tests
2931 * @tpTestCaseDetails RESTEASY-1540
30 * @tpSince RESTEasy 3.1.0.Final
32 * @tpSince RESTEasy 3.0.20.Final
3133 */
3234 @RunWith(Arquillian.class)
3335 @RunAsClient
4850 @Deployment
4951 public static Archive<?> deploy() {
5052 WebArchive war = TestUtil.prepareArchive(AbortMessageTest.class.getSimpleName());
53 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
54 new LoggingPermission("control", ""),
55 new RuntimePermission("accessDeclaredMembers")
56 ), "permissions.xml");
5157 return TestUtil.finishContainerPrepare(war, null, AbortMessageResourceFilter.class);
5258 }
5359
5763
5864 /**
5965 * @tpTestDetails Send response with "Aborted"
60 * @tpSince RESTEasy 3.1.0.Final
66 * @tpSince RESTEasy 3.0.20.Final
6167 */
6268 @Test
6369 public void testAbort() throws UnsupportedEncodingException {
0 package org.jboss.resteasy.test.client;
1
2 import java.util.concurrent.CountDownLatch;
3
4 import javax.ws.rs.client.Client;
5 import javax.ws.rs.client.Entity;
6 import javax.ws.rs.client.InvocationCallback;
7 import javax.ws.rs.client.WebTarget;
8 import javax.ws.rs.core.Response;
9
10 import org.jboss.arquillian.container.test.api.Deployment;
11 import org.jboss.arquillian.container.test.api.RunAsClient;
12 import org.jboss.arquillian.junit.Arquillian;
13 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
14 import org.jboss.resteasy.test.client.resource.AsyncInvokeResource;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Ignore;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 @RunWith(Arquillian.class)
25 @RunAsClient
26 @Ignore
27 public class AsyncBenchTest extends ClientTestBase
28 {
29
30 static Client client;
31
32 static Client nioClient;
33
34 static final int ITERATIONS = 4000;
35 static final int MAX_CONNECTIONS = 200;
36
37 @Deployment
38 public static Archive<?> deploy()
39 {
40 WebArchive war = TestUtil.prepareArchive(AsyncBenchTest.class.getSimpleName());
41 war.addClass(AsyncBenchTest.class);
42 war.addClass(ClientTestBase.class);
43 return TestUtil.finishContainerPrepare(war, null, AsyncInvokeResource.class);
44 }
45
46 @After
47 public void after() throws Exception
48 {
49 if (client != null)
50 client.close();
51 if (nioClient != null)
52 nioClient.close();
53 }
54
55 @Test
56 public void testAsyncPost() throws Exception
57 {
58 long start = System.currentTimeMillis();
59 final String oldProp = System.getProperty("http.maxConnections");
60 System.setProperty("http.maxConnections", String.valueOf(MAX_CONNECTIONS));
61 nioClient = new ResteasyClientBuilder().useAsyncHttpEngine().build();
62 WebTarget wt = nioClient.target(generateURL("/test"));
63 runCallback(wt, "NIO");
64 long end = System.currentTimeMillis() - start;
65 System.out.println("TEST NON BLOCKING IO - " + ITERATIONS + " iterations took " + end + "ms");
66 if (oldProp != null)
67 {
68 System.setProperty("http.maxConnections", oldProp);
69 }
70 else
71 {
72 System.clearProperty("http.maxConnections");
73 }
74 }
75
76 @Test
77 public void testPost() throws Exception
78 {
79 long start = System.currentTimeMillis();
80 client = new ResteasyClientBuilder().connectionPoolSize(MAX_CONNECTIONS).maxPooledPerRoute(MAX_CONNECTIONS).build();
81 WebTarget wt2 = client.target(generateURL("/test"));
82 runCallback(wt2, "BIO");
83 long end = System.currentTimeMillis() - start;
84 System.out.println("TEST BLOCKING IO - " + ITERATIONS + " iterations took " + end + "ms");
85 }
86
87 private void runCallback(WebTarget wt, String msg) throws Exception
88 {
89 CountDownLatch latch = new CountDownLatch(ITERATIONS);
90 for (int i = 0; i < ITERATIONS; i++) {
91 final String m = msg + i;
92 wt.request().async().post(Entity.text(m), new InvocationCallback<Response>()
93 {
94 @Override
95 public void completed(Response response)
96 {
97 String entity = response.readEntity(String.class);
98 Assert.assertEquals("post " + m, entity);
99 latch.countDown();
100 }
101
102 @Override
103 public void failed(Throwable error)
104 {
105 throw new RuntimeException(error);
106 }
107 });
108 }
109 latch.await();
110 }
111 }
00 package org.jboss.resteasy.test.client;
11
2 import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
3 import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
24 import org.jboss.arquillian.container.test.api.Deployment;
35 import org.jboss.arquillian.container.test.api.RunAsClient;
46 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpAsyncClient4Engine;
59 import org.jboss.resteasy.test.client.resource.AsyncInvokeResource;
610 import org.jboss.resteasy.util.HttpResponseCodes;
711 import org.jboss.resteasy.utils.TestUtil;
2226 import java.lang.annotation.ElementType;
2327 import java.lang.annotation.Retention;
2428 import java.lang.annotation.RetentionPolicy;
29 import java.util.concurrent.CountDownLatch;
2530 import java.util.concurrent.Future;
31 import java.util.concurrent.TimeUnit;
2632
2733 /**
2834 * @tpSubChapter Resteasy-client
4046 }
4147
4248 static Client client;
49 static Client nioClient;
4350
4451 @Deployment
4552 public static Archive<?> deploy() {
5259 @Before
5360 public void init() {
5461 client = ClientBuilder.newClient();
62
63 nioClient = new ResteasyClientBuilder().useAsyncHttpEngine().build();
5564 }
5665
5766 @After
5867 public void after() throws Exception {
5968 client.close();
69 nioClient.close();
6070 }
6171
6272 /**
6878 @Test
6979 public void AsyncGetTest() throws Exception {
7080 {
71 Future<Response> future = client.target(generateURL("/test")).request().async().get();
81 Future<Response> future = nioClient.target(generateURL("/test")).request().async().get();
7282 Response res = future.get();
7383 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
7484 String entity = res.readEntity(String.class);
92102 public void AsyncDeleteTest() throws Exception {
93103
94104 {
95 Future<Response> future = client.target(generateURL("/test")).request().async().delete();
105 Future<Response> future = nioClient.target(generateURL("/test")).request().async().delete();
96106 Response res = future.get();
97107 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
98108 String entity = res.readEntity(String.class);
115125 @Test
116126 public void AsyncPutTest() throws Exception {
117127 {
118 Future<Response> future = client.target(generateURL("/test")).request().async().put(Entity.text("hello"));
128 Future<Response> future = nioClient.target(generateURL("/test")).request().async().put(Entity.text("hello"));
119129 Response res = future.get();
120130 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
121131 String entity = res.readEntity(String.class);
138148 @Test
139149 public void AsyncPostTest() throws Exception {
140150 {
141 Future<Response> future = client.target(generateURL("/test")).request().async().post(Entity.text("hello"));
151 Future<Response> future = nioClient.target(generateURL("/test")).request().async().post(Entity.text("hello"));
142152 Response res = future.get();
143153 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
144154 String entity = res.readEntity(String.class);
163173 @Test
164174 public void AsyncCustomMethodTest() throws Exception {
165175 {
166 Future<Response> future = client.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"));
176 Future<Response> future = nioClient.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"));
167177 Response res = future.get();
168178 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
169179 String entity = res.readEntity(String.class);
177187 }
178188 }
179189
180 static boolean ok;
181
182190 /**
183191 * @tpTestDetails Client sends async GET requests using Asynchronous InvocationCallback. First request expects Response object in return,
184192 * the second expects String object in return
188196 @Test
189197 public void AsyncCallbackGetTest() throws Exception {
190198 {
191 ok = false;
192 Future<Response> future = client.target(generateURL("/test")).request().async().get(new InvocationCallback<Response>() {
199 final CountDownLatch latch = new CountDownLatch(1);
200 Future<Response> future = nioClient.target(generateURL("/test")).request().async().get(new InvocationCallback<Response>() {
193201 @Override
194202 public void completed(Response response) {
195203 String entity = response.readEntity(String.class);
196204 Assert.assertEquals("get", entity);
197 ok = true;
198 }
199
200 @Override
201 public void failed(Throwable error) {
202 }
203 });
204 Response res = future.get();
205 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
206 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
207
208 }
209
210 {
211 ok = false;
212 Future<String> future = client.target(generateURL("/test")).request().async().get(new InvocationCallback<String>() {
205 latch.countDown();
206 }
207
208 @Override
209 public void failed(Throwable error) {
210 }
211 });
212 Response res = future.get();
213 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
214 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
215
216 }
217
218 {
219 final CountDownLatch latch = new CountDownLatch(1);
220 Future<String> future = nioClient.target(generateURL("/test")).request().async().get(new InvocationCallback<String>() {
213221 @Override
214222 public void completed(String entity) {
215223 Assert.assertEquals("get", entity);
216 ok = true;
224 latch.countDown();
217225 }
218226
219227 @Override
222230 });
223231 String entity = future.get();
224232 Assert.assertEquals("get", entity);
225 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
233 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
226234 }
227235 }
228236
236244 public void AsyncCallbackDeleteTest() throws Exception {
237245
238246 {
239 ok = false;
240 Future<Response> future = client.target(generateURL("/test")).request().async().delete(new InvocationCallback<Response>() {
247 final CountDownLatch latch = new CountDownLatch(1);
248 Future<Response> future = nioClient.target(generateURL("/test")).request().async().delete(new InvocationCallback<Response>() {
241249 @Override
242250 public void completed(Response response) {
243251 String entity = response.readEntity(String.class);
244252 Assert.assertEquals("delete", entity);
245 ok = true;
246 }
247
248 @Override
249 public void failed(Throwable error) {
250 }
251 });
252 Response res = future.get();
253 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
254 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
255 }
256
257 {
258 ok = false;
259 Future<String> future = client.target(generateURL("/test")).request().async().delete(new InvocationCallback<String>() {
253 latch.countDown();
254 }
255
256 @Override
257 public void failed(Throwable error) {
258 }
259 });
260 Response res = future.get();
261 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
262 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
263 }
264
265 {
266 final CountDownLatch latch = new CountDownLatch(1);
267 Future<String> future = nioClient.target(generateURL("/test")).request().async().delete(new InvocationCallback<String>() {
260268 @Override
261269 public void completed(String s) {
262270 Assert.assertEquals("delete", s);
263 ok = true;
271 latch.countDown();
264272 }
265273
266274 @Override
269277 });
270278 String entity = future.get();
271279 Assert.assertEquals("delete", entity);
272 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
280 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
273281 }
274282 }
275283
283291 @Test
284292 public void AsyncCallbackPutTest() throws Exception {
285293 {
286 ok = false;
287 Future<Response> future = client.target(generateURL("/test")).request().async().put(Entity.text("hello"), new InvocationCallback<Response>() {
294 final CountDownLatch latch = new CountDownLatch(1);
295 Future<Response> future = nioClient.target(generateURL("/test")).request().async().put(Entity.text("hello"), new InvocationCallback<Response>() {
288296 @Override
289297 public void completed(Response response) {
290298 String entity = response.readEntity(String.class);
291299 Assert.assertEquals("put hello", entity);
292 ok = true;
293 }
294
295 @Override
296 public void failed(Throwable error) {
297 }
298 });
299 Response res = future.get();
300 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
301 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
302
303 }
304 {
305 ok = false;
306 Future<String> future = client.target(generateURL("/test")).request().async().put(Entity.text("hello"), new InvocationCallback<String>() {
300 latch.countDown();
301 }
302
303 @Override
304 public void failed(Throwable error) {
305 }
306 });
307 Response res = future.get();
308 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
309 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
310
311 }
312 {
313 final CountDownLatch latch = new CountDownLatch(1);
314 Future<String> future = nioClient.target(generateURL("/test")).request().async().put(Entity.text("hello"), new InvocationCallback<String>() {
307315 @Override
308316 public void completed(String s) {
309317 Assert.assertEquals("put hello", s);
310 ok = true;
318 latch.countDown();
311319 }
312320
313321 @Override
316324 });
317325 String entity = future.get();
318326 Assert.assertEquals("put hello", entity);
319 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
327 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
320328
321329 }
322330 }
330338 @Test
331339 public void AsyncCallbackPostTest() throws Exception {
332340 {
333 ok = false;
334 Future<Response> future = client.target(generateURL("/test")).request().async().post(Entity.text("hello"), new InvocationCallback<Response>() {
341 final CountDownLatch latch = new CountDownLatch(1);
342 Future<Response> future = nioClient.target(generateURL("/test")).request().async().post(Entity.text("hello"), new InvocationCallback<Response>() {
335343 @Override
336344 public void completed(Response response) {
337345 String entity = response.readEntity(String.class);
338346 Assert.assertEquals("post hello", entity);
339 ok = true;
340 }
341
342 @Override
343 public void failed(Throwable error) {
344 }
345 });
346 Response res = future.get();
347 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
348 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
349
350 }
351 {
352 ok = false;
353 Future<String> future = client.target(generateURL("/test")).request().async().post(Entity.text("hello"), new InvocationCallback<String>() {
347 latch.countDown();
348 }
349
350 @Override
351 public void failed(Throwable error) {
352 }
353 });
354 Response res = future.get();
355 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
356 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
357
358 }
359 {
360 final CountDownLatch latch = new CountDownLatch(1);
361 Future<String> future = nioClient.target(generateURL("/test")).request().async().post(Entity.text("hello"), new InvocationCallback<String>() {
354362 @Override
355363 public void completed(String s) {
356364 Assert.assertEquals("post hello", s);
357 ok = true;
365 latch.countDown();
358366 }
359367
360368 @Override
363371 });
364372 String entity = future.get();
365373 Assert.assertEquals("post hello", entity);
366 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
374 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
367375
368376 }
369377 }
377385 @Test
378386 public void AsyncCallbackCustomMethodTest() throws Exception {
379387 {
380 ok = false;
381 Future<Response> future = client.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"), new InvocationCallback<Response>() {
388 final CountDownLatch latch = new CountDownLatch(1);
389 Future<Response> future = nioClient.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"), new InvocationCallback<Response>() {
382390 @Override
383391 public void completed(Response response) {
384392 String entity = response.readEntity(String.class);
385393 Assert.assertEquals("patch hello", entity);
386 ok = true;
387 }
388
389 @Override
390 public void failed(Throwable error) {
391 }
392 });
393 Response res = future.get();
394 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
395 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
396
397 }
398 {
399 ok = false;
400 Future<String> future = client.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"), new InvocationCallback<String>() {
394 latch.countDown();
395 }
396
397 @Override
398 public void failed(Throwable error) {
399 }
400 });
401 Response res = future.get();
402 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
403 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
404
405 }
406 {
407 final CountDownLatch latch = new CountDownLatch(1);
408 Future<String> future = nioClient.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"), new InvocationCallback<String>() {
401409 @Override
402410 public void completed(String s) {
403411 Assert.assertEquals("patch hello", s);
404 ok = true;
412 latch.countDown();
405413 }
406414
407415 @Override
410418 });
411419 String entity = future.get();
412420 Assert.assertEquals("patch hello", entity);
413 Assert.assertTrue( "Asynchronous invocation didn't use custom implemented Invocation callback", ok);
414
415 }
421 Assert.assertTrue( "Asynchronous invocation didn't use custom implemented Invocation callback", latch.await(5, TimeUnit.SECONDS));
422
423 }
424 }
425
426 @Test
427 public void AsyncCallbackExceptionHandlingTest() throws Exception {
428 {
429 final CountDownLatch latch = new CountDownLatch(1);
430 Future<Response> future = nioClient.target(generateURL("/test")).request().async().get(new InvocationCallback<Response>()
431 {
432 @Override
433 public void completed(Response response)
434 {
435 String entity = response.readEntity(String.class);
436 Assert.assertEquals("get", entity);
437 latch.countDown();
438 throw new RuntimeException("for the test of it");
439 }
440
441 @Override
442 public void failed(Throwable error)
443 {
444 }
445 });
446 Assert.assertTrue(latch.await(15, TimeUnit.SECONDS));
447 Response res = future.get();
448 Assert.assertEquals(200, res.getStatus()); // must not see the runtimeexception of the callback
449 }
450
451 {
452 final CountDownLatch latch = new CountDownLatch(1);
453 Future<String> future = nioClient.target(generateURL("/test")).request().async().get(new InvocationCallback<String>()
454 {
455 @Override
456 public void completed(String s)
457 {
458 Assert.assertEquals("get", s);
459 latch.countDown();
460 throw new RuntimeException("for the test of it");
461 }
462
463 @Override
464 public void failed(Throwable error)
465 {
466 }
467 });
468 Assert.assertTrue(latch.await(15, TimeUnit.SECONDS));
469 String entity = future.get();
470 Assert.assertEquals("get", entity); // must not see the runtimeexception of the callback
471 }
416472 }
417473
418474
427483 public void SubmitGetTest() throws Exception {
428484
429485 {
430 Future<Response> future = client.target(generateURL("/test")).request().buildGet().submit();
486 Future<Response> future = nioClient.target(generateURL("/test")).request().buildGet().submit();
431487 Response res = future.get();
432488 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
433489 String entity = res.readEntity(String.class);
451507 @Test
452508 public void SubmitDeleteTest() throws Exception {
453509 {
454 Future<Response> future = client.target(generateURL("/test")).request().buildDelete().submit();
510 Future<Response> future = nioClient.target(generateURL("/test")).request().buildDelete().submit();
455511 Response res = future.get();
456512 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
457513 String entity = res.readEntity(String.class);
475531 @Test
476532 public void SubmitPutTest() throws Exception {
477533 {
478 Future<Response> future = client.target(generateURL("/test")).request().buildPut(Entity.text("hello")).submit();
534 Future<Response> future = nioClient.target(generateURL("/test")).request().buildPut(Entity.text("hello")).submit();
479535 Response res = future.get();
480536 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
481537 String entity = res.readEntity(String.class);
500556 @Test
501557 public void SubmitPostTest() throws Exception {
502558 {
503 Future<Response> future = client.target(generateURL("/test")).request().buildPost(Entity.text("hello")).submit();
559 Future<Response> future = nioClient.target(generateURL("/test")).request().buildPost(Entity.text("hello")).submit();
504560 Response res = future.get();
505561 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
506562 String entity = res.readEntity(String.class);
525581 @Test
526582 public void SubmitCustomMethodTest() throws Exception {
527583 {
528 Future<Response> future = client.target(generateURL("/test")).request().build("PATCH", Entity.text("hello")).submit();
584 Future<Response> future = nioClient.target(generateURL("/test")).request().build("PATCH", Entity.text("hello")).submit();
529585 Response res = future.get();
530586 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
531587 String entity = res.readEntity(String.class);
104104
105105 RequestConfig reqConfig = RequestConfig.custom() // apache HttpClient specific
106106 .setConnectTimeout(2000)
107 .setSocketTimeout(2000)
107 .setSocketTimeout(-1)
108108 .setConnectionRequestTimeout(200)
109109 .build();
110110 CloseableHttpClient httpClient = HttpClientBuilder.create()
1919 import java.io.FilePermission;
2020 import java.lang.reflect.ReflectPermission;
2121 import java.util.PropertyPermission;
22 import java.util.logging.LoggingPermission;
2223
2324 /**
2425 * @tpSubChapter Resteasy-client
3637 war.addClass(NotForForwardCompatibility.class);
3738 // Arquillian in the deployment and use of TestUtil
3839 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
39 new RuntimePermission("accessDeclaredMembers"),
40 new FilePermission(TestUtil.getJbossHome() + File.separator + "standalone" + File.separator + "log" +
41 File.separator + "server.log", "read"),
42 new LoggingPermission("control", ""),
4043 new PropertyPermission("arquillian.*", "read"),
4144 new PropertyPermission("jboss.home.dir", "read"),
42 new FilePermission(TestUtil.getJbossHome() + File.separator + "standalone" + File.separator + "log" +
43 File.separator + "server.log", "read")), "permissions.xml");
45 new RuntimePermission("accessDeclaredMembers")
46 ), "permissions.xml");
4447 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
4548 }
4649
2222 import org.junit.runner.RunWith;
2323
2424 import java.lang.reflect.ReflectPermission;
25 import java.net.SocketPermission;
2526 import java.util.PropertyPermission;
27 import java.util.logging.LoggingPermission;
2628
2729
2830 /**
4749 war.addClasses(ClientCacheProxy.class, ClientCacheTest.class, TestUtil.class, PortProviderUtil.class);
4850 // Arquillian in the deployment and use of PortProviderUtil and Test util in the deployment
4951 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
52 new LoggingPermission("control", ""),
53 new PropertyPermission("arquillian.*", "read"),
54 new PropertyPermission("ipv6", "read"),
55 new PropertyPermission("node", "read"),
56 new PropertyPermission("org.jboss.resteasy.port", "read"),
5057 new RuntimePermission("accessDeclaredMembers"),
51 new PropertyPermission("arquillian.*", "read"),
52 new PropertyPermission("node", "read"),
53 new PropertyPermission("ipv6", "read"),
5458 new RuntimePermission("getenv.RESTEASY_PORT"),
55 new PropertyPermission("org.jboss.resteasy.port", "read")), "permissions.xml");
59 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
60 ), "permissions.xml");
61 war.addClasses(ClientCacheProxy.class, ClientCacheTest.class, TestUtil.class, PortProviderUtil.class);
5662 return TestUtil.finishContainerPrepare(war, null, ClientCacheService.class);
5763 }
5864
66 import org.jboss.arquillian.container.test.api.Deployment;
77 import org.jboss.arquillian.container.test.api.RunAsClient;
88 import org.jboss.arquillian.junit.Arquillian;
9 import org.jboss.logging.Logger;
109 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
1110 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
1211 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
12 import org.jboss.resteasy.logging.Logger;
1313 import org.jboss.resteasy.test.client.resource.ClientExecutorShutdownTestResource;
1414 import org.jboss.resteasy.util.HttpResponseCodes;
1515 import org.jboss.resteasy.utils.TestUtil;
+0
-130
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientInvocationBuilderTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import java.util.concurrent.ExecutionException;
3 import java.util.concurrent.Future;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.client.AsyncInvoker;
9 import javax.ws.rs.client.Entity;
10 import javax.ws.rs.client.Invocation.Builder;
11 import javax.ws.rs.core.MediaType;
12
13 import org.jboss.arquillian.container.test.api.Deployment;
14 import org.jboss.arquillian.container.test.api.RunAsClient;
15 import org.jboss.arquillian.junit.Arquillian;
16 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
17 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
18 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
19 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
20 import org.jboss.resteasy.utils.TestUtil;
21 import org.jboss.shrinkwrap.api.Archive;
22 import org.jboss.shrinkwrap.api.spec.WebArchive;
23 import org.junit.Assert;
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class ClientInvocationBuilderTest extends ClientTestBase{
30
31 @Path("/")
32 public static class ClientInvocationBuilderResource {
33 @POST
34 @Produces("text/plain")
35 public String post(String s) {
36 return s;
37 }
38
39 @GET
40 @Produces("text/plain")
41 public String get() {
42 String s = "default";
43 return s;
44 }
45 }
46
47 @Deployment
48 public static Archive<?> deploy() {
49 WebArchive war = TestUtil.prepareArchive(ClientInvocationBuilderTest.class.getSimpleName());
50 war.addClass(ClientInvocationBuilderTest.class);
51 war.addClass(ClientTestBase.class);
52 return TestUtil.finishContainerPrepare(war, null, ClientInvocationBuilderResource.class);
53 }
54
55 @Test
56 public void testBuildMethodReturnNewInstance() {
57 ResteasyClient client = new ResteasyClientBuilder().build();
58 try {
59 ResteasyWebTarget webTarget = client.target(generateURL(""));
60 Builder invocationBuilder = webTarget.request();
61
62 // GET invocation
63 ClientInvocation getInvocation = (ClientInvocation) invocationBuilder.accept(MediaType.TEXT_PLAIN_TYPE)
64 .build("GET");
65 Assert.assertEquals("default", getInvocation.invoke(String.class));
66
67 // Alter invocationBuilder
68 invocationBuilder.accept(MediaType.APPLICATION_XML_TYPE);
69 invocationBuilder.property("property1", "property1Value");
70 // Previously built getInvocation must not have been altered.(Those
71 // tests are not about immutability of
72 // getInvocation instance but about Builder pattern behavior).
73 Assert.assertFalse(getInvocation.getHeaders().getAcceptableMediaTypes()
74 .contains(MediaType.APPLICATION_XML_TYPE));
75 Assert.assertFalse(getInvocation.getConfiguration().getProperties().containsKey("property1"));
76
77 // POST invocation
78 ClientInvocation postInvocation = (ClientInvocation) invocationBuilder.accept(MediaType.TEXT_PLAIN_TYPE)
79 .build("POST", Entity.text("test"));
80 // Previous lines must build a new postInvocation instance and not
81 // modify previously built getInvocation instance.
82 // (It's all about Builder pattern behavior not immutability since
83 // Invocation is a mutable object.)
84 Assert.assertNotSame(getInvocation, postInvocation);
85 Assert.assertEquals("default", getInvocation.invoke(String.class));
86 Assert.assertTrue(postInvocation.getConfiguration().getProperties().containsKey("property1"));
87 Assert.assertEquals("test", postInvocation.invoke(String.class));
88 } finally {
89 client.close();
90 }
91 }
92
93 @Test
94 public void testBuildMethodResetEntity() throws InterruptedException, ExecutionException {
95 ResteasyClient client = new ResteasyClientBuilder().build();
96 try {
97 ResteasyWebTarget webTarget = client.target(generateURL(""));
98 Builder invocationBuilder = webTarget.request().accept(MediaType.TEXT_PLAIN_TYPE);
99
100 // POST invocation
101 ClientInvocation postInvocation = (ClientInvocation) invocationBuilder.build("POST", Entity.text("test"));
102 Assert.assertEquals("test", postInvocation.invoke(String.class));
103
104 // GET invocation
105 ClientInvocation getInvocation = (ClientInvocation) invocationBuilder.build("GET");
106 // In order the request to be OK, invocation instance built from
107 // invocationBuilder must not contain the previous entity used for
108 // post request.
109 Assert.assertNull(getInvocation.getEntity());
110 Assert.assertEquals("default", getInvocation.invoke(String.class));
111
112 // Same test for async request
113 AsyncInvoker async = invocationBuilder.async();
114
115 // POST invocation
116 Future<String> postFuture = async.post(Entity.text("test"), String.class);
117 Assert.assertEquals("test", postFuture.get());
118
119 // GET invocation
120 Future<String> getFuture = async.get(String.class);
121 Assert.assertEquals("default", getFuture.get());
122 } finally {
123 client.close();
124 }
125 }
126
127
128
129 }
44 import org.jboss.arquillian.container.test.api.Deployment;
55 import org.jboss.arquillian.container.test.api.RunAsClient;
66 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
8 import org.jboss.resteasy.client.ProxyFactory;
79 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
810 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
911 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
12 import org.jboss.resteasy.test.client.resource.ClientResponseRedirectClientResponseOld;
1013 import org.jboss.resteasy.test.client.resource.ClientResponseRedirectIntf;
1114 import org.jboss.resteasy.test.client.resource.ClientResponseRedirectResource;
1215 import org.jboss.resteasy.util.HttpResponseCodes;
6366 }
6467
6568 /**
69 * @tpTestDetails Tests redirection of the request using deprecated ProxyFactory client
70 * @tpPassCrit The header 'location' contains the redirected target
71 * @tpSince RESTEasy 3.0.16
72 */
73 @Test
74 public void testRedirectProxyFactory() throws Exception {
75 testRedirect(ProxyFactory.create(ClientResponseRedirectClientResponseOld.class, PortProviderUtil.generateBaseUrl(ClientResponseRedirectTest.class.getSimpleName())).get());
76 }
77
78 /**
6679 * @tpTestDetails Tests redirection of the request using ProxyBuilder client
6780 * @tpPassCrit The header 'location' contains the redirected target
6881 * @tpSince RESTEasy 3.0.16
7083 @Test
7184 public void testRedirectProxyBuilder() throws Exception {
7285 testRedirect(ProxyBuilder.builder(ClientResponseRedirectIntf.class, client.target(generateURL(""))).build().get());
86 }
87
88 /**
89 * @tpTestDetails Tests redirection of the request using deprecated ClientRequest
90 * @tpPassCrit The header 'location' contains the redirected target
91 * @tpSince RESTEasy 3.0.16
92 */
93 @Test
94 public void testRedirectClientRequest() throws Exception {
95 testRedirect(PortProviderUtil.createClientRequest("/redirect", ClientResponseRedirectTest.class.getSimpleName()).get());
7396 }
7497
7598 /**
100123 Assert.assertEquals(HttpResponseCodes.SC_SEE_OTHER, conn.getResponseCode());
101124 }
102125
126 private void testRedirect(ClientResponse response) {
127 MultivaluedMap headers = response.getResponseHeaders();
128 logger.info("size: " + headers.size());
129 for (Object name : headers.keySet()) {
130 logger.info(name + ":" + headers.getFirst(name.toString()));
131 }
132 Assert.assertTrue(headers.getFirst("location").toString().equalsIgnoreCase(PortProviderUtil.generateURL("/redirect/data", ClientResponseRedirectTest.class.getSimpleName())));
133 }
134
103135 @SuppressWarnings(value = "unchecked")
104136 private void testRedirect(Response response) {
105137 MultivaluedMap headers = response.getHeaders();
0 package org.jboss.resteasy.test.client;
1
2 import java.io.ByteArrayOutputStream;
3 import java.io.InputStream;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9 import javax.ws.rs.client.Client;
10 import javax.ws.rs.client.ClientBuilder;
11 import javax.ws.rs.client.Invocation;
12 import javax.ws.rs.core.MediaType;
13 import javax.ws.rs.core.Response;
14 import javax.ws.rs.core.Response.Status;
15 import javax.xml.bind.annotation.XmlRootElement;
16
17 import org.jboss.arquillian.container.test.api.Deployment;
18 import org.jboss.arquillian.container.test.api.RunAsClient;
19 import org.jboss.arquillian.junit.Arquillian;
20 import org.jboss.resteasy.client.jaxrs.internal.ClientResponse;
21 import org.jboss.resteasy.utils.PortProviderUtil;
22 import org.jboss.resteasy.utils.TestUtil;
23 import org.jboss.shrinkwrap.api.Archive;
24 import org.jboss.shrinkwrap.api.spec.WebArchive;
25 import org.junit.AfterClass;
26 import org.junit.Assert;
27 import org.junit.BeforeClass;
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class ClientResponseWithEntityTest {
34
35 @XmlRootElement
36 public static class Message {
37 private String message;
38
39 public Message() {
40 }
41
42 public String getMessage() {
43 return this.message;
44 }
45
46 public void setMessage(String message) {
47 this.message = message;
48 }
49 }
50
51 @Path("echo")
52 @Produces(MediaType.APPLICATION_XML)
53 public static class EchoResource {
54
55 @GET
56 public Response echo(@QueryParam("msg") String msg) {
57 Message message = new Message();
58 message.setMessage(String.valueOf(msg));
59 return Response.ok(message).build();
60 }
61
62 }
63
64 private static Client client;
65 private static final String DEP = "ClientResponseWithEntityTest";
66
67 @Deployment
68 public static Archive<?> deploy() {
69 WebArchive war = TestUtil.prepareArchive(DEP);
70 war.addClass(Message.class);
71 war.addClass(EchoResource.class);
72 return TestUtil.finishContainerPrepare(war, null, EchoResource.class);
73 }
74
75 @BeforeClass
76 public static void setup() {
77 client = ClientBuilder.newClient();
78 }
79
80 @AfterClass
81 public static void cleanup() {
82 client.close();
83 }
84
85 private static String generateURL() {
86 return PortProviderUtil.generateBaseUrl(DEP);
87 }
88
89 @Test
90 public void Should_ReturnEntity_When_NoNull() throws Exception {
91 Invocation.Builder request = client.target(generateURL()).path("echo").queryParam("msg", "Hello world")
92 .request(MediaType.APPLICATION_XML_TYPE);
93 try (ClientResponse response = (ClientResponse) request.get()) {
94 Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());
95 Assert.assertTrue(response.hasEntity());
96 Assert.assertNotNull(response.getEntity());
97 Assert.assertNotNull(response.getEntityClass());
98 }
99 }
100
101 @Test(expected = IllegalStateException.class)
102 public void Should_ThrowIllegalStateException_When_EntityIsConsumed() throws Exception {
103 Invocation.Builder request = client.target(generateURL()).path("echo").queryParam("msg", "Hello world")
104 .request(MediaType.APPLICATION_XML_TYPE);
105 try (ClientResponse response = (ClientResponse) request.get()) {
106 Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());
107 Assert.assertTrue(response.hasEntity());
108 InputStream entityStream = (InputStream) response.getEntity();
109 ByteArrayOutputStream baos = new ByteArrayOutputStream();
110 byte[] buffer = new byte[1024];
111 int wasRead = 0;
112 do {
113 wasRead = entityStream.read(buffer);
114 if (wasRead > 0) {
115 baos.write(buffer, 0, wasRead);
116 }
117 } while (wasRead > -1);
118 response.getEntity();
119 }
120 }
121
122 }
00 package org.jboss.resteasy.test.client;
11
2 import org.apache.commons.io.IOUtils;
23 import org.apache.logging.log4j.LogManager;
34 import org.apache.logging.log4j.Logger;
45 import org.jboss.arquillian.container.test.api.Deployment;
3637 @Path("test")
3738 @Produces("text/plain")
3839 @GET
39 default InputStream get() {
40 return null;
41 }
40 InputStream get();
4241
4342 }
4443
7271 @Test
7372 public void testInputStream() throws Exception {
7473 InputStream is = client.target(generateURL("/test")).request().get(InputStream.class);
75 byte[] buf = new byte[1024];
76 int read = is.read(buf);
77 String str = new String(buf, 0, read);
74 byte[] buf = IOUtils.toByteArray(is);
75 String str = new String(buf);
7876 Assert.assertEquals("The returned inputStream doesn't contain expexted text", "hello world", str);
7977 logger.info("Text from inputstream: " + str);
8078 is.close();
8987 @Test
9088 public void testInputStreamProxy() throws Exception {
9189 InputStreamInterface proxy = client.target(generateURL("/")).proxy(InputStreamInterface.class);
92 byte[] buf = new byte[1024];
9390 InputStream is = proxy.get();
94 int read = is.read(buf);
95 String str = new String(buf, 0, read);
91 byte[] buf = IOUtils.toByteArray(is);
92 String str = new String(buf);
9693 Assert.assertEquals("The returned inputStream doesn't contain expexted text", "hello world", str);
9794 is.close();
9895 }
0 package org.jboss.resteasy.test.client;
1
2 import javax.ws.rs.HttpMethod;
3 import javax.ws.rs.client.Client;
4 import javax.ws.rs.client.ClientBuilder;
5 import javax.ws.rs.client.Entity;
6 import javax.ws.rs.core.Response;
7
8 import org.jboss.arquillian.container.test.api.Deployment;
9 import org.jboss.arquillian.container.test.api.RunAsClient;
10 import org.jboss.arquillian.junit.Arquillian;
11 import org.jboss.resteasy.category.Jaxrs21;
12 import org.jboss.resteasy.test.client.resource.JAXRS21SyncInvokeResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.After;
18 import org.junit.Assert;
19 import org.junit.Before;
20 import org.junit.Test;
21 import org.junit.experimental.categories.Category;
22 import org.junit.runner.RunWith;
23
24 @RunWith(Arquillian.class)
25 @RunAsClient
26 @Category(Jaxrs21.class)
27 public class JAXRS21PatchTest extends ClientTestBase {
28
29 static Client client;
30
31 @Deployment
32 public static Archive<?> deploy() {
33 WebArchive war = TestUtil.prepareArchive(JAXRS21PatchTest.class.getSimpleName());
34 war.addClass(JAXRS21PatchTest.class);
35 return TestUtil.finishContainerPrepare(war, null, JAXRS21SyncInvokeResource.class);
36 }
37
38 @Before
39 public void init() {
40 client = ClientBuilder.newClient();
41 }
42
43 @After
44 public void after() throws Exception {
45 client.close();
46 }
47
48 @Test
49 public void testMethods() throws Exception {
50 {
51 Response res = client.target(generateURL("/test")).request().method(HttpMethod.PATCH, Entity.text("hello"));
52 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
53 String entity = res.readEntity(String.class);
54 Assert.assertEquals("patch hello", entity);
55 }
56 {
57 String entity = client.target(generateURL("/test")).request().method(HttpMethod.PATCH, Entity.text("hello"), String.class);
58 Assert.assertEquals("patch hello", entity);
59 }
60 }
61
62 @Test
63 public void testInvoke() throws Exception {
64 {
65 Response res = client.target(generateURL("/test")).request().build(HttpMethod.PATCH, Entity.text("hello")).invoke();
66 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
67 String entity = res.readEntity(String.class);
68 Assert.assertEquals("patch hello", entity);
69 }
70 {
71 String entity = client.target(generateURL("/test")).request().build(HttpMethod.PATCH, Entity.text("hello")).invoke(String.class);
72 Assert.assertEquals("patch hello", entity);
73 }
74 }
75 }
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
57 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
68 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.plugins.delegates.LinkHeaderDelegate;
10 import org.jboss.resteasy.spi.LinkHeader;
711 import org.jboss.resteasy.test.client.resource.LinkHeaderService;
812 import org.jboss.resteasy.utils.TestUtil;
913 import org.jboss.shrinkwrap.api.Archive;
2024 /**
2125 * @tpSubChapter Resteasy-client
2226 * @tpChapter Integration tests
23 * @tpTestCaseDetails Test for new Link provided by jax-rs 2.0 spec
27 * @tpTestCaseDetails Test for LinkHeader (it use deprecated Link). Test also new Link provided by jax-rs 2.0 spec
2428 * @tpSince RESTEasy 3.0.16
2529 */
2630 @RunWith(Arquillian.class)
4650 }
4751
4852 /**
49 * @tpTestDetails Test new client without API
53 * @tpTestDetails Test new client without API and old client with API
5054 * @tpSince RESTEasy 3.0.16
5155 */
5256 @Test
5357 public void testLinkheader() throws Exception {
58 // old client testing
59 {
60 ClientRequest request = new ClientRequest(generateURL("/linkheader/str"));
61 request.addLink("previous chapter", "previous", "http://example.com/TheBook/chapter2", null);
62 ClientResponse response = request.post();
63 LinkHeader header = response.getLinkHeader();
64 Assert.assertNotNull(header);
65 Assert.assertTrue("Wrong link", header.getLinksByTitle().containsKey("previous chapter"));
66 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("previous"));
67 Assert.assertEquals("Wrong link", header.getLinksByTitle().get("previous chapter").getHref(), "http://example.com/TheBook/chapter2");
68 }
5469
5570 // new client testing
5671 {
6277 Assert.assertEquals("Wrong link", "http://example.com/TheBook/chapter2", link.getUri().toString());
6378 }
6479 }
80
81 /**
82 * @tpTestDetails Test old client without API
83 * @tpSince RESTEasy 3.0.16
84 */
85 @Test
86 public void testLinkheaderOldClientWithoutApi() throws Exception {
87 LinkHeaderDelegate delegate = new LinkHeaderDelegate();
88 LinkHeader header = delegate.fromString("<http://example.org/>; rel=index;\n" +
89 " rel=\"start http://example.net/relation/other\"");
90 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("index"));
91 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("start"));
92 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("http://example.net/relation/other"));
93 String str = delegate.toString(header);
94 header = delegate.fromString(str);
95 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("index"));
96 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("start"));
97 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("http://example.net/relation/other"));
98 ClientRequest request = new ClientRequest(generateURL("/linkheader"));
99 request.header("link", "<http://example.org/>; rel=index;" +
100 " rel=\"start http://example.net/relation/other\"");
101 ClientResponse response = request.post();
102 header = response.getLinkHeader();
103 Assert.assertNotNull("Wrong link", header);
104 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("index"));
105 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("start"));
106 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("http://example.net/relation/other"));
107 }
65108 }
44 import org.jboss.arquillian.container.test.api.Deployment;
55 import org.jboss.arquillian.container.test.api.RunAsClient;
66 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
8 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
9 import org.jboss.resteasy.client.ProxyFactory;
710 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
811 import org.jboss.resteasy.test.client.resource.ParameterListInterface;
912 import org.jboss.resteasy.test.client.resource.ParameterListResource;
6265 }
6366
6467 /**
68 * @tpTestDetails Old client: set matrix param by URL and by matrixParameter function
69 * @tpSince RESTEasy 3.0.16
70 */
71 @Test
72 public void testMatrixOldClient() throws Exception {
73 ClientRequest request = new ClientRequest(generateURL("/matrix;m1=a/list;m1=b;p2=c"));
74 request.matrixParameter("m1", "d");
75 ClientResponse<String> response = request.get(String.class);
76 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
77 Assert.assertEquals(ERROR_MESSAGE, "a:b:d:", response.getEntity());
78 }
79
80 /**
81 * @tpTestDetails Old client: set query param by URL and by queryParameter function
82 * @tpSince RESTEasy 3.0.16
83 */
84 @Test
85 public void testQueryOldClient() throws Exception {
86 ClientRequest request = new ClientRequest(generateURL("/query/list?q1=a&q2=b&q1=c"));
87 request.queryParameter("q1", "d");
88 ClientResponse<String> response = request.get(String.class);
89 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
90 Assert.assertEquals(ERROR_MESSAGE, "a:c:d:", response.getEntity());
91 }
92
93 /**
6594 * @tpTestDetails New client: set matrix param by URL and by matrixParam function
6695 * @tpSince RESTEasy 3.0.16
6796 */
82111 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
83112 Assert.assertEquals(ERROR_MESSAGE, "a:c:d:", response.readEntity(String.class));
84113 }
114
115
116 /**
117 * @tpTestDetails Old client: check settings of matrix list by proxy
118 * @tpSince RESTEasy 3.0.16
119 */
120 @SuppressWarnings("unchecked")
121 @Test
122 public void testMatrixProxyListOldClient() throws Exception {
123 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
124 ArrayList<String> list = new ArrayList<>();
125 list.add("a");
126 list.add("b");
127 list.add("c");
128 ClientResponse<String> response = ClientResponse.class.cast(client.matrixList(list));
129 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
130 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
131 }
132
133 /**
134 * @tpTestDetails Old client: check settings of matrix set by proxy
135 * @tpSince RESTEasy 3.0.16
136 */
137 @SuppressWarnings("unchecked")
138 @Test
139 public void testMatrixProxySetOldClient() throws Exception {
140 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
141 HashSet<String> set = new HashSet<>();
142 set.add("a");
143 set.add("b");
144 set.add("c");
145 ClientResponse<String> response = ClientResponse.class.cast(client.matrixSet(set));
146 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
147 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
148 }
149
150 /**
151 * @tpTestDetails Old client: check settings of matrix sorted set by proxy
152 * @tpSince RESTEasy 3.0.16
153 */
154 @SuppressWarnings("unchecked")
155 @Test
156 public void testMatrixProxySortedSetOldClient() throws Exception {
157 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
158 TreeSet<String> set = new TreeSet<String>();
159 set.add("a");
160 set.add("b");
161 set.add("c");
162 ClientResponse<String> response = ClientResponse.class.cast(client.matrixSortedSet(set));
163 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
164 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
165 }
166
167 /**
168 * @tpTestDetails Old client: check settings of matrix list and other parameter by proxy
169 * @tpSince RESTEasy 3.0.16
170 */
171 @SuppressWarnings("unchecked")
172 @Test
173 public void testMatrixWithEntityProxyOldClient() throws Exception {
174 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
175 ArrayList<String> list = new ArrayList<>();
176 list.add("a");
177 list.add("b");
178 list.add("c");
179 ClientResponse<String> response = ClientResponse.class.cast(client.matrixWithEntity(list, "entity"));
180 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
181 Assert.assertEquals(ERROR_MESSAGE, "entity:a:b:c:", response.getEntity(String.class));
182 }
183
184 /**
185 * @tpTestDetails Old client: check settings of query list by proxy
186 * @tpSince RESTEasy 3.0.16
187 */
188 @SuppressWarnings("unchecked")
189 @Test
190 public void testQueryProxyListOldClient() throws Exception {
191 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
192 ArrayList<String> list = new ArrayList<>();
193 list.add("a");
194 list.add("b");
195 list.add("c");
196 ClientResponse<String> response = ClientResponse.class.cast(client.queryList(list));
197 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
198 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
199 }
200
201 /**
202 * @tpTestDetails Old client: check settings of query set by proxy
203 * @tpSince RESTEasy 3.0.16
204 */
205 @SuppressWarnings("unchecked")
206 @Test
207 public void testQueryProxySetOldClient() throws Exception {
208 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
209 HashSet<String> set = new HashSet<>();
210 set.add("a");
211 set.add("b");
212 set.add("c");
213 ClientResponse<String> response = ClientResponse.class.cast(client.querySet(set));
214 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
215 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
216 }
217
218 /**
219 * @tpTestDetails Old client: check settings of query sorted set by proxy
220 * @tpSince RESTEasy 3.0.16
221 */
222 @SuppressWarnings("unchecked")
223 @Test
224 public void testQueryProxySortedSetOldClient() throws Exception {
225 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
226 TreeSet<String> set = new TreeSet<String>();
227 set.add("a");
228 set.add("b");
229 set.add("c");
230 ClientResponse<String> response = ClientResponse.class.cast(client.querySortedSet(set));
231 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
232 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
233 }
234
235 /**
236 * @tpTestDetails Old client: check settings of query list with other parameter by proxy
237 * @tpSince RESTEasy 3.0.16
238 */
239 @SuppressWarnings("unchecked")
240 @Test
241 public void testQueryWithEntityProxyOldClient() throws Exception {
242 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
243 ArrayList<String> list = new ArrayList<>();
244 list.add("a");
245 list.add("b");
246 list.add("c");
247 ClientResponse<String> response = ClientResponse.class.cast(client.queryWithEntity(list, "entity"));
248 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
249 Assert.assertEquals(ERROR_MESSAGE, "entity:a:b:c:", response.getEntity(String.class));
250 }
251
252 /**
253 * @tpTestDetails Old client: check settings of query list, matrix list and other parameter by proxy
254 * @tpSince RESTEasy 3.0.16
255 */
256 @SuppressWarnings("unchecked")
257 @Test
258 public void testMatrixQueryWithEntityProxyOldClient() throws Exception {
259 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
260 ArrayList<String> matrixParams = new ArrayList<>();
261 matrixParams.add("a");
262 matrixParams.add("b");
263 matrixParams.add("c");
264 ArrayList<String> queryParams = new ArrayList<>();
265 queryParams.add("x");
266 queryParams.add("y");
267 queryParams.add("z");
268 ClientResponse<String> response = ClientResponse.class.cast(client.matrixQueryWithEntity(matrixParams, queryParams, "entity"));
269 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
270 Assert.assertEquals(ERROR_MESSAGE, "entity:a:b:c:x:y:z:", response.getEntity(String.class));
271 }
272
85273
86274 /**
87275 * @tpTestDetails New client: check settings of matrix list by proxy
0 package org.jboss.resteasy.test.client;
1
2 import javax.ws.rs.client.Client;
3 import javax.ws.rs.client.ClientBuilder;
4 import javax.ws.rs.client.Entity;
5 import javax.ws.rs.core.Response;
6
7 import org.jboss.arquillian.container.test.api.Deployment;
8 import org.jboss.arquillian.container.test.api.RunAsClient;
9 import org.jboss.arquillian.junit.Arquillian;
10 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
11 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
12 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine;
13 import org.jboss.resteasy.test.client.resource.RedirectProxyResource;
14 import org.jboss.resteasy.test.client.resource.RedirectResource;
15 import org.jboss.resteasy.utils.PortProviderUtil;
16 import org.jboss.resteasy.utils.TestUtil;
17 import org.jboss.shrinkwrap.api.Archive;
18 import org.jboss.shrinkwrap.api.spec.WebArchive;
19 import org.junit.Assert;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 /**
24 * @tpSubChapter Resteasy-client
25 * @tpChapter Integration tests
26 * @tpSince RESTEasy 3.5
27 * @tpTestCaseDetails https://issues.jboss.org/browse/RESTEASY-1075
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class RedirectTest extends ClientTestBase
32 {
33 @Deployment
34 public static Archive<?> deploy()
35 {
36 WebArchive war = TestUtil.prepareArchive(RedirectTest.class.getSimpleName());
37 war.addClasses(PortProviderUtil.class);
38 return TestUtil.finishContainerPrepare(war, null, RedirectResource.class);
39 }
40
41 /**
42 * @tpTestDetails Set client to following the redirect
43 * Do not use RESTEasy proxy
44 * Use GET HTTP request
45 * Send request to "end-point 1", that returns 307 HTTP code (Temporary Redirect) and redirect client to another URL (handled by "end-point 2")
46 * Client should follow redirect URL
47 * Client should return data from "end-point 2"
48 * Both end-points return Response data type
49 * @tpSince RESTEasy 3.5
50 */
51 @Test
52 public void testRedirect()
53 {
54 ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine();
55 engine.setFollowRedirects(true);
56 Client client = new ResteasyClientBuilder().httpEngine(engine).build();
57 try
58 {
59 Response response = client.target(generateURL("/redirect/" + RedirectTest.class.getSimpleName())).request()
60 .get();
61 Assert.assertEquals(200, response.getStatus());
62 Assert.assertEquals("OK", response.readEntity(String.class));
63 response.close();
64 }
65 finally
66 {
67 client.close();
68 }
69 }
70
71 /**
72 * @tpTestDetails Set client to following the redirect
73 * Do not use RESTEasy proxy
74 * Use POST HTTP request
75 * Send request to "end-point 1", that returns 307 HTTP code (Temporary Redirect) and redirect client to another URL (handled by "end-point 2")
76 * Client should follow redirect URL
77 * Client should return data from "end-point 2"
78 * Both end-points return Response data type
79 * @tpSince RESTEasy 3.5
80 */
81 @Test
82 public void testPostRedirect()
83 {
84 ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine();
85 engine.setFollowRedirects(true);
86 Client client = new ResteasyClientBuilder().httpEngine(engine).build();
87 try
88 {
89 Response response = client.target(generateURL("/post-redirect")).request()
90 .post(Entity.entity(RedirectTest.class.getSimpleName(), "text/plain"));
91 Assert.assertEquals(200, response.getStatus());
92 Assert.assertEquals("OK", response.readEntity(String.class));
93 response.close();
94 }
95 finally
96 {
97 client.close();
98 }
99 }
100
101 /**
102 * @tpTestDetails Set client to following the redirect
103 * Use RESTEasy proxy
104 * Use GET HTTP request
105 * Send request to "end-point 1", that returns 307 HTTP code (Temporary Redirect) and redirect client to another URL (handled by "end-point 2")
106 * Client should follow redirect URL
107 * Client should return data from "end-point 2"
108 * Both end-points return Response data type
109 * @tpSince RESTEasy 3.5
110 */
111 @Test
112 public void testRedirectProxy()
113 {
114 ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine();
115 engine.setFollowRedirects(true);
116 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
117 try
118 {
119 RedirectProxyResource proxy = client.target(generateURL("/"))
120 .proxy(RedirectProxyResource.class);
121 Response response = proxy.redirect(RedirectTest.class.getSimpleName());
122 Assert.assertEquals(200, response.getStatus());
123 Assert.assertEquals("OK", response.readEntity(String.class));
124 response.close();
125 }
126 finally
127 {
128 client.close();
129 }
130 }
131
132 /**
133 * @tpTestDetails Set client to following the redirect
134 * Use RESTEasy proxy
135 * Use GET HTTP request
136 * Send request to "end-point 1", that returns 307 HTTP code (Temporary Redirect) and redirect client to another URL (handled by "end-point 2")
137 * Client should follow redirect URL
138 * Client should return data from "end-point 2"
139 * "end-point 1" returns Response data type, "end-point 2" returns String data type
140 * @tpSince RESTEasy 3.5
141 */
142 @Test
143 public void testRedirectDirectResponseProxy()
144 {
145 ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine();
146 engine.setFollowRedirects(true);
147 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
148 try
149 {
150 RedirectProxyResource proxy = client.target(generateURL("/"))
151 .proxy(RedirectProxyResource.class);
152 Response response = proxy.redirectDirectResponse(RedirectTest.class.getSimpleName());
153 Assert.assertEquals(200, response.getStatus());
154 Assert.assertEquals("ok - direct response", response.readEntity(String.class));
155 response.close();
156 }
157 finally
158 {
159 client.close();
160 }
161 }
162
163 /**
164 * @tpTestDetails Set client to following the redirect
165 * Use RESTEasy proxy
166 * Use GET HTTP request
167 * Send request to "end-point 1", that returns 301 HTTP code (Moved Permanently) and redirect client to another URL (handled by "end-point 2")
168 * Client should follow redirect URL
169 * Client should return data from "end-point 2"
170 * "end-point 1" returns Response data type, "end-point 2" returns String data type
171 * @tpSince RESTEasy 3.5
172 */
173 @Test
174 public void testMovedPermanentlyDirectResponseProxy()
175 {
176 ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine();
177 engine.setFollowRedirects(true);
178 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
179 try
180 {
181 RedirectProxyResource proxy = client.target(generateURL("/"))
182 .proxy(RedirectProxyResource.class);
183 Response response = proxy.movedPermanently(RedirectTest.class.getSimpleName());
184 Assert.assertEquals(200, response.getStatus());
185 Assert.assertEquals("ok - direct response", response.readEntity(String.class));
186 response.close();
187 }
188 finally
189 {
190 client.close();
191 }
192 }
193
194 /**
195 * @tpTestDetails Set client to following the redirect
196 * Use RESTEasy proxy
197 * Use GET HTTP request
198 * Send request to "end-point 1", that returns 302 HTTP code (Found) and redirect client to another URL (handled by "end-point 2")
199 * Client should follow redirect URL
200 * Client should return data from "end-point 2"
201 * "end-point 1" returns Response data type, "end-point 2" returns String data type
202 * @tpSince RESTEasy 3.5
203 */
204 @Test
205 public void testFoundDirectResponseProxy()
206 {
207 ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine();
208 engine.setFollowRedirects(true);
209 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
210 try
211 {
212 RedirectProxyResource proxy = client.target(generateURL("/"))
213 .proxy(RedirectProxyResource.class);
214 Response response = proxy.found(RedirectTest.class.getSimpleName());
215 Assert.assertEquals(200, response.getStatus());
216 Assert.assertEquals("ok - direct response", response.readEntity(String.class));
217 response.close();
218 }
219 finally
220 {
221 client.close();
222 }
223 }
224
225 /**
226 * @tpTestDetails Do not use RESTEasy proxy
227 * Use GET HTTP request
228 * Do not set client to following the redirect
229 * Send request to "end-point 1", that returns 307 HTTP code (Temporary Redirect) and redirect client to another URL (handled by "end-point 2")
230 * Client should not follow redirect URL
231 * Client should return 307 HTTP code
232 * @tpSince RESTEasy 3.5
233 */
234 @Test
235 public void testNoRedirect()
236 {
237 Client client = ClientBuilder.newClient();
238 try
239 {
240 Response response = client.target(generateURL("/redirect/" + RedirectTest.class.getSimpleName())).request()
241 .get();
242 Assert.assertEquals(307, response.getStatus());
243 response.close();
244 }
245 finally
246 {
247 client.close();
248 }
249 }
250
251 /**
252 * @tpTestDetails Do not use RESTEasy proxy
253 * Use POST HTTP request
254 * Do not set client to following the redirect
255 * Send request to "end-point 1", that returns 307 HTTP code (Temporary Redirect) and redirect client to another URL (handled by "end-point 2")
256 * Client should not follow redirect URL
257 * Client should return 307 HTTP code
258 * @tpSince RESTEasy 3.5
259 */
260 @Test
261 public void testNoPostRedirect()
262 {
263 Client client = ClientBuilder.newClient();
264 try
265 {
266 Response response = client.target(generateURL("/post-redirect")).request()
267 .post(Entity.entity(RedirectTest.class.getSimpleName(), "text/plain"));
268 Assert.assertEquals(303, response.getStatus());
269 response.close();
270 }
271 finally
272 {
273 client.close();
274 }
275 }
276
277 /**
278 * @tpTestDetails Use RESTEasy proxy
279 * Do not set client to following the redirect
280 * Send request to "end-point 1", that returns 307 HTTP code (Temporary Redirect) and redirect client to another URL (handled by "end-point 2")
281 * Client should not follow redirect URL
282 * Client should return 307 HTTP code
283 * @tpSince RESTEasy 3.5
284 */
285 @Test
286 public void testNoRedirectProxy()
287 {
288 ResteasyClient client = new ResteasyClientBuilder().build();
289 try
290 {
291 RedirectProxyResource proxy = client.target(generateURL("/"))
292 .proxy(RedirectProxyResource.class);
293 Response response = proxy.redirect(RedirectTest.class.getSimpleName());
294 Assert.assertEquals(307, response.getStatus());
295 response.close();
296 }
297 finally
298 {
299 client.close();
300 }
301 }
302 }
0 package org.jboss.resteasy.test.client;
1
2 import java.util.concurrent.CompletableFuture;
3 import java.util.concurrent.ExecutorService;
4 import java.util.concurrent.Future;
5
6 import javax.ws.rs.client.Client;
7 import javax.ws.rs.client.ClientBuilder;
8 import javax.ws.rs.client.Entity;
9 import javax.ws.rs.client.Invocation.Builder;
10 import javax.ws.rs.client.RxInvoker;
11 import javax.ws.rs.client.RxInvokerProvider;
12 import javax.ws.rs.client.SyncInvoker;
13 import javax.ws.rs.core.GenericType;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.core.Response;
16
17 import org.jboss.arquillian.container.test.api.Deployment;
18 import org.jboss.arquillian.container.test.api.RunAsClient;
19 import org.jboss.arquillian.junit.Arquillian;
20 import org.jboss.dmr.ModelNode;
21 import org.jboss.resteasy.client.jaxrs.internal.CompletionStageRxInvokerImpl;
22 import org.jboss.resteasy.test.client.resource.TestResource;
23 import org.jboss.resteasy.utils.TestUtil;
24 import org.jboss.shrinkwrap.api.Archive;
25 import org.jboss.shrinkwrap.api.spec.WebArchive;
26 import org.junit.AfterClass;
27 import org.junit.Assert;
28 import org.junit.BeforeClass;
29 import org.junit.Test;
30 import org.junit.runner.RunWith;
31 import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
32 import org.wildfly.extras.creaper.core.online.operations.Address;
33 import org.wildfly.extras.creaper.core.online.operations.Operations;
34 import org.wildfly.extras.creaper.core.online.operations.admin.Administration;
35
36 /**
37 *
38 * @author <a href="mailto:ron.sigal@jboss.com">Ron Sigal</a>
39 * @author <a href="mailto:alessio.soldano@jboss.com">Alessio Soldano</a>
40 * @date March 9, 2016
41 */
42 @RunWith(Arquillian.class)
43 @RunAsClient
44 public class RxInvokerTest extends ClientTestBase
45 {
46 private static final GenericType<String> STRING_TYPE = new GenericType<String>() {};
47 private static final Address ADDRESS = Address.subsystem("undertow").and("server", "default-server").and("http-listener", "default");
48
49 private static ModelNode origDisallowedMethodsValue;
50
51 @Deployment
52 public static Archive<?> deploy() {
53 WebArchive war = TestUtil.prepareArchive(RxInvokerTest.class.getSimpleName());
54 return TestUtil.finishContainerPrepare(war, null, TestResource.class);
55 }
56
57 @BeforeClass
58 public static void setup() throws Exception {
59 OnlineManagementClient mgmtClient = TestUtil.clientInit();
60 Administration admin = new Administration(mgmtClient);
61 Operations ops = new Operations(mgmtClient);
62
63 // get original 'disallowed methods' value
64 origDisallowedMethodsValue = ops.readAttribute(ADDRESS, "disallowed-methods").value();
65 // set 'disallowed methods' to empty list to allow TRACE
66 ops.writeAttribute(ADDRESS, "disallowed-methods", new ModelNode().setEmptyList());
67
68 // reload server
69 admin.reload();
70 mgmtClient.close();
71 }
72
73 @AfterClass
74 public static void cleanup() throws Exception {
75 OnlineManagementClient mgmtClient = TestUtil.clientInit();
76 Administration admin = new Administration(mgmtClient);
77 Operations ops = new Operations(mgmtClient);
78
79 // write original 'disallowed methods' value
80 ops.writeAttribute(ADDRESS, "disallowed-methods", origDisallowedMethodsValue);
81
82 // reload server
83 admin.reload();
84 mgmtClient.close();
85 }
86
87 public static class TestRxInvokerProvider implements RxInvokerProvider<TestRxInvoker>
88 {
89
90 @Override
91 public boolean isProviderFor(Class<?> clazz)
92 {
93 return clazz.isAssignableFrom(TestRxInvoker.class);
94 }
95
96 @Override
97 public TestRxInvoker getRxInvoker(SyncInvoker syncInvoker, ExecutorService executorService)
98 {
99 return new TestRxInvoker(syncInvoker, executorService);
100 }
101
102 }
103
104 public static class TestRxInvoker extends CompletionStageRxInvokerImpl
105 {
106 public static volatile boolean used;
107
108 public TestRxInvoker(SyncInvoker builder)
109 {
110 super(builder);
111 used = true;
112 }
113
114 public TestRxInvoker(SyncInvoker builder, ExecutorService executor)
115 {
116 super(builder, executor);
117 used = true;
118 }
119 }
120
121 static Client newClient(boolean useCustomInvoker) {
122 TestRxInvoker.used = false;
123 final Client client;
124 if (useCustomInvoker) {
125 client = ClientBuilder.newClient().register(TestRxInvokerProvider.class, RxInvokerProvider.class);
126 } else {
127 client = ClientBuilder.newClient();
128 }
129 return client;
130 }
131
132 @Test
133 public void testRxClientGet() throws Exception
134 {
135 doTestRxClientGet(false);
136 doTestRxClientGet(true);
137 }
138
139 void doTestRxClientGet(boolean useCustomInvoker) throws Exception
140 {
141 final Client client = newClient(useCustomInvoker);
142 Builder builder = client.target(generateURL("/get")).request();
143 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
144 CompletableFuture<Response> cs = (CompletableFuture<Response>) invoker.get();
145 String response = cs.get().readEntity(String.class);
146 Assert.assertEquals("get", response);
147 Assert.assertEquals(useCustomInvoker, TestRxInvoker.used);
148 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
149 client.close();
150 }
151
152 @Test
153 public void testRxClientGetClass() throws Exception
154 {
155 doTestRxClientGetClass(false);
156 doTestRxClientGetClass(true);
157 }
158
159 void doTestRxClientGetClass(boolean useCustomInvoker) throws Exception
160 {
161 final Client client = newClient(useCustomInvoker);
162 Builder builder = client.target(generateURL("/get")).request();
163 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
164 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.get(String.class);
165 Assert.assertEquals("get", cs.get());
166 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
167 client.close();
168 }
169
170 @Test
171 public void testRxClientGetGenericType() throws Exception
172 {
173 doTestRxClientGetGenericType(false);
174 doTestRxClientGetGenericType(true);
175 }
176
177 void doTestRxClientGetGenericType(boolean useCustomInvoker) throws Exception
178 {
179 final Client client = newClient(useCustomInvoker);
180 Builder builder = client.target(generateURL("/get")).request();
181 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
182 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.get(STRING_TYPE);
183 Assert.assertEquals("get", cs.get());
184 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
185 client.close();
186 }
187
188 @Test
189 public void testRxClientPut() throws Exception
190 {
191 doTestRxClientPut(false);
192 doTestRxClientPut(true);
193 }
194
195 void doTestRxClientPut(boolean useCustomInvoker) throws Exception
196 {
197 final Client client = newClient(useCustomInvoker);
198 Builder builder = client.target(generateURL("/put")).request();
199 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
200 CompletableFuture<Response> cs = (CompletableFuture<Response>) invoker.put(Entity.entity("put", MediaType.TEXT_PLAIN_TYPE));
201 String response = cs.get().readEntity(String.class);
202 Assert.assertEquals("put", response);
203 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
204 client.close();
205 }
206
207 @Test
208 public void testRxClientPutClass() throws Exception
209 {
210 doTestRxClientPutClass(false);
211 doTestRxClientPutClass(true);
212 }
213
214 void doTestRxClientPutClass(boolean useCustomInvoker) throws Exception
215 {
216 final Client client = newClient(useCustomInvoker);
217 Builder builder = client.target(generateURL("/put")).request();
218 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
219 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.put(Entity.entity("put", MediaType.TEXT_PLAIN_TYPE), String.class);
220 String response = cs.get();
221 Assert.assertEquals("put", response);
222 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
223 client.close();
224 }
225
226 @Test
227 public void testRxClientPutGenericType() throws Exception
228 {
229 doTestRxClientPutGenericType(false);
230 doTestRxClientPutGenericType(true);
231 }
232
233 void doTestRxClientPutGenericType(boolean useCustomInvoker) throws Exception
234 {
235 final Client client = newClient(useCustomInvoker);
236 Builder builder = client.target(generateURL("/put")).request();
237 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
238 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.put(Entity.entity("put", MediaType.TEXT_PLAIN_TYPE), STRING_TYPE);
239 String response = cs.get();
240 Assert.assertEquals("put", response);
241 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
242 client.close();
243 }
244
245 @Test
246 public void testRxClientPost() throws Exception
247 {
248 doTestRxClientPost(false);
249 doTestRxClientPost(true);
250 }
251
252 void doTestRxClientPost(boolean useCustomInvoker) throws Exception
253 {
254 final Client client = newClient(useCustomInvoker);
255 Builder builder = client.target(generateURL("/post")).request();
256 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
257 CompletableFuture<Response> cs = (CompletableFuture<Response>) invoker.post(Entity.entity("post", MediaType.TEXT_PLAIN_TYPE));
258 String response = cs.get().readEntity(String.class);
259 Assert.assertEquals("post", response);
260 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
261 client.close();
262 }
263
264 @Test
265 public void testRxClientPostClass() throws Exception
266 {
267 doTestRxClientPostClass(false);
268 doTestRxClientPostClass(true);
269 }
270
271 void doTestRxClientPostClass(boolean useCustomInvoker) throws Exception
272 {
273 final Client client = newClient(useCustomInvoker);
274 Builder builder = client.target(generateURL("/post")).request();
275 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
276 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.post(Entity.entity("post", MediaType.TEXT_PLAIN_TYPE), String.class);
277 String response = cs.get();
278 Assert.assertEquals("post", response);
279 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
280 client.close();
281 }
282
283 @Test
284 public void testRxClientPostGenericType() throws Exception
285 {
286 dotestRxClientPostGenericType(false);
287 dotestRxClientPostGenericType(true);
288 }
289
290 void dotestRxClientPostGenericType(boolean useCustomInvoker) throws Exception
291 {
292 final Client client = newClient(useCustomInvoker);
293 Builder builder = client.target(generateURL("/post")).request();
294 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
295 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.post(Entity.entity("post", MediaType.TEXT_PLAIN_TYPE), STRING_TYPE);
296 String response = cs.get();
297 Assert.assertEquals("post", response);
298 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
299 client.close();
300 }
301
302 @Test
303 public void testRxClientDelete() throws Exception
304 {
305 doTestRxClientDelete(false);
306 doTestRxClientDelete(true);
307 }
308
309 void doTestRxClientDelete(boolean useCustomInvoker) throws Exception
310 {
311 final Client client = newClient(useCustomInvoker);
312 Builder builder = client.target(generateURL("/delete")).request();
313 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
314 CompletableFuture<Response> cs = (CompletableFuture<Response>) invoker.delete();
315 String response = cs.get().readEntity(String.class);
316 Assert.assertEquals("delete", response);
317 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
318 client.close();
319 }
320
321 @Test
322 public void testRxClientDeleteClass() throws Exception
323 {
324 doTestRxClientDeleteClass(false);
325 doTestRxClientDeleteClass(true);
326 }
327
328 void doTestRxClientDeleteClass(boolean useCustomInvoker) throws Exception
329 {
330 final Client client = newClient(useCustomInvoker);
331 Builder builder = client.target(generateURL("/delete")).request();
332 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
333 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.delete(String.class);
334 Assert.assertEquals("delete", cs.get());
335 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
336 client.close();
337 }
338
339 @Test
340 public void testRxClientDeleteGenericType() throws Exception
341 {
342 doTestRxClientDeleteGenericType(false);
343 doTestRxClientDeleteGenericType(true);
344 }
345
346 void doTestRxClientDeleteGenericType(boolean useCustomInvoker) throws Exception
347 {
348 final Client client = newClient(useCustomInvoker);
349 Builder builder = client.target(generateURL("/delete")).request();
350 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
351 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.delete(STRING_TYPE);
352 Assert.assertEquals("delete", cs.get());
353 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
354 client.close();
355 }
356
357 @Test
358 public void testRxClientHead() throws Exception
359 {
360 doTestRxClientHead(false);
361 doTestRxClientHead(true);
362 }
363
364 void doTestRxClientHead(boolean useCustomInvoker) throws Exception
365 {
366 final Client client = newClient(useCustomInvoker);
367 Builder builder = client.target(generateURL("/head")).request();
368 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
369 CompletableFuture<Response> cs = (CompletableFuture<Response>) invoker.head();
370 Response response = cs.get();
371 Assert.assertEquals(204, response.getStatus());
372 Assert.assertEquals("head", response.getStringHeaders().getFirst("key"));
373 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
374 client.close();
375 }
376
377 @Test
378 public void testRxClientOptions() throws Exception
379 {
380 doTestRxClientOptions(false);
381 doTestRxClientOptions(true);
382 }
383
384 void doTestRxClientOptions(boolean useCustomInvoker) throws Exception
385 {
386 final Client client = newClient(useCustomInvoker);
387 Builder builder = client.target(generateURL("/options")).request();
388 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
389 CompletableFuture<Response> cs = (CompletableFuture<Response>) invoker.options();
390 String response = cs.get().readEntity(String.class);
391 Assert.assertEquals("options", response);
392 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
393 client.close();
394 }
395
396 @Test
397 public void testRxClientOptionsClass() throws Exception
398 {
399 doTestRxClientOptionsClass(false);
400 doTestRxClientOptionsClass(true);
401 }
402
403 void doTestRxClientOptionsClass(boolean useCustomInvoker) throws Exception
404 {
405 final Client client = newClient(useCustomInvoker);
406 Builder builder = client.target(generateURL("/options")).request();
407 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
408 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.options(String.class);
409 Assert.assertEquals("options", cs.get());
410 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
411 client.close();
412 }
413
414 @Test
415 public void testRxClientOptionsGenericType() throws Exception
416 {
417 doTestRxClientOptionsGenericType(false);
418 doTestRxClientOptionsGenericType(true);
419 }
420
421 void doTestRxClientOptionsGenericType(boolean useCustomInvoker) throws Exception
422 {
423 final Client client = newClient(useCustomInvoker);
424 Builder builder = client.target(generateURL("/options")).request();
425 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
426 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.options(STRING_TYPE);
427 Assert.assertEquals("options", cs.get());
428 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
429 client.close();
430 }
431
432 @Test
433 public void testRxClientTrace() throws Exception
434 {
435 doTestRxClientTrace(false);
436 doTestRxClientTrace(true);
437 }
438
439 void doTestRxClientTrace(boolean useCustomInvoker) throws Exception
440 {
441 final Client client = newClient(useCustomInvoker);
442 Builder builder = client.target(generateURL("/trace")).request();
443 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
444 CompletableFuture<Response> cs = (CompletableFuture<Response>) invoker.trace();
445 String response = cs.get().readEntity(String.class);
446 Assert.assertEquals("trace", response);
447 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
448 client.close();
449 }
450
451 @Test
452 public void testRxClientTraceClass() throws Exception
453 {
454 doTestRxClientTraceClass(false);
455 doTestRxClientTraceClass(true);
456 }
457
458 void doTestRxClientTraceClass(boolean useCustomInvoker) throws Exception
459 {
460 final Client client = newClient(useCustomInvoker);
461 Builder builder = client.target(generateURL("/trace")).request();
462 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
463 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.trace(String.class);
464 Assert.assertEquals("trace", cs.get());
465 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
466 client.close();
467 }
468
469 @Test
470 public void testRxClientTraceGenericType() throws Exception
471 {
472 doTestRxClientTraceGenericType(false);
473 doTestRxClientTraceGenericType(true);
474 }
475
476 void doTestRxClientTraceGenericType(boolean useCustomInvoker) throws Exception
477 {
478 final Client client = newClient(useCustomInvoker);
479 Builder builder = client.target(generateURL("/trace")).request();
480 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
481 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.trace(STRING_TYPE);
482 Assert.assertEquals("trace", cs.get());
483 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
484 client.close();
485 }
486
487 @Test
488 public void testRxClientMethod() throws Exception
489 {
490 doTestRxClientMethod(false);
491 doTestRxClientMethod(true);
492 }
493
494 void doTestRxClientMethod(boolean useCustomInvoker) throws Exception
495 {
496 final Client client = newClient(useCustomInvoker);
497 Builder builder = client.target(generateURL("/method")).request();
498 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
499 CompletableFuture<Response> cs = (CompletableFuture<Response>) invoker.method("METHOD");
500 String response = cs.get().readEntity(String.class);
501 Assert.assertEquals("method", response);
502 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
503 client.close();
504 }
505
506 @Test
507 public void testRxClientMethodClass() throws Exception
508 {
509 doTestRxClientMethodClass(false);
510 doTestRxClientMethodClass(true);
511 }
512
513 void doTestRxClientMethodClass(boolean useCustomInvoker) throws Exception
514 {
515 final Client client = newClient(useCustomInvoker);
516 Builder builder = client.target(generateURL("/method")).request();
517 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
518 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.method("METHOD", String.class);
519 Assert.assertEquals("method", cs.get());
520 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
521 client.close();
522 }
523
524 @Test
525 public void testRxClientMethodGenericType() throws Exception
526 {
527 doTestRxClientMethodGenericType(false);
528 doTestRxClientMethodGenericType(true);
529 }
530
531 void doTestRxClientMethodGenericType(boolean useCustomInvoker) throws Exception
532 {
533 final Client client = newClient(useCustomInvoker);
534 Builder builder = client.target(generateURL("/method")).request();
535 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
536 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.method("METHOD", STRING_TYPE);
537 Assert.assertEquals("method", cs.get());
538 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
539 client.close();
540 }
541
542 @Test
543 public void testRxClientMethodEntity() throws Exception
544 {
545 doTestRxClientMethodEntity(false);
546 doTestRxClientMethodEntity(true);
547 }
548
549 void doTestRxClientMethodEntity(boolean useCustomInvoker) throws Exception
550 {
551 final Client client = newClient(useCustomInvoker);
552 Builder builder = client.target(generateURL("/methodEntity")).request();
553 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
554 CompletableFuture<Response> cs = (CompletableFuture<Response>) invoker.method("METHOD", Entity.entity("methodEntity", MediaType.TEXT_PLAIN_TYPE));
555 String response = cs.get().readEntity(String.class);
556 Assert.assertEquals("methodEntity", response);
557 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
558 client.close();
559 }
560
561 @Test
562 public void testRxClientMethodClassEntity() throws Exception
563 {
564 doTestRxClientMethodClassEntity(false);
565 doTestRxClientMethodClassEntity(true);
566 }
567
568 void doTestRxClientMethodClassEntity(boolean useCustomInvoker) throws Exception
569 {
570 final Client client = newClient(useCustomInvoker);
571 Builder builder = client.target(generateURL("/methodEntity")).request();
572 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
573 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.method("METHOD", Entity.entity("methodEntity", MediaType.TEXT_PLAIN_TYPE), String.class);
574 String response = cs.get();
575 Assert.assertEquals("methodEntity", response);
576 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
577 client.close();
578 }
579
580 @Test
581 public void testRxClientMethodGenericTypeEntity() throws Exception
582 {
583 doTestRxClientMethodGenericTypeEntity(false);
584 doTestRxClientMethodGenericTypeEntity(true);
585 }
586
587 void doTestRxClientMethodGenericTypeEntity(boolean useCustomInvoker) throws Exception
588 {
589 final Client client = newClient(useCustomInvoker);
590 Builder builder = client.target(generateURL("/methodEntity")).request();
591 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
592 CompletableFuture<String> cs = (CompletableFuture<String>) invoker.method("METHOD", Entity.entity("methodEntity", MediaType.TEXT_PLAIN_TYPE), STRING_TYPE);
593 String response = cs.get();
594 Assert.assertEquals("methodEntity", response);
595 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
596 client.close();
597 }
598
599 /**
600 * @tpTestDetails end-point method returns String data after some delay (3s)
601 * client use RxInvoker. Data should not be prepared right after CompletionStage object are returned from client
602 * CompletionStage should return correct data after 3s delay
603 * @tpSince RESTEasy 3.5
604 */
605 @Test
606 public void testGetDataWithDelay() throws Exception
607 {
608 doTestGetDataWithDelay(false);
609 doTestGetDataWithDelay(true);
610 }
611
612 void doTestGetDataWithDelay(boolean useCustomInvoker) throws Exception
613 {
614 final Client client = newClient(useCustomInvoker);
615 Builder builder = client.target(generateURL("/sleep")).request();
616 RxInvoker<?> invoker = useCustomInvoker ? builder.rx(TestRxInvoker.class) : builder.rx();
617 Future<String> future = ((CompletableFuture<String>) invoker.get(String.class)).toCompletableFuture();
618 Assert.assertFalse(future.isDone());
619 String response = future.get();
620 Assert.assertEquals("get", response);
621 Assert.assertEquals(useCustomInvoker, invoker instanceof TestRxInvoker && TestRxInvoker.used);
622 client.close();
623 }
624 }
625
77 import org.apache.http.client.config.RequestConfig;
88 import org.apache.http.impl.client.CloseableHttpClient;
99 import org.apache.http.impl.client.HttpClientBuilder;
10 import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
11 import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
1012 import org.apache.logging.log4j.LogManager;
1113 import org.apache.logging.log4j.Logger;
1214 import org.jboss.arquillian.container.test.api.Deployment;
1517 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
1618 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
1719 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
20 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpAsyncClient4Engine;
1821 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine;
1922 import org.jboss.resteasy.client.jaxrs.engines.URLConnectionEngine;
2023 import org.jboss.resteasy.test.client.other.resource.ApacheHttpClient4Resource;
4043
4144 protected static final Logger logger = LogManager.getLogger(ApacheHttpClient43Test.class.getName());
4245
43 private Class engine1 = ApacheHttpClient43Engine.class;
44 private Class engine2 = URLConnectionEngine.class;
46 private Class<?> engine1 = ApacheHttpClient43Engine.class;
47 private Class<?> engine2 = URLConnectionEngine.class;
48 private Class<?> engine3 = ApacheHttpAsyncClient4Engine.class;
4549
4650 private AtomicLong counter = new AtomicLong();
4751
6064 public void testConnectionCleanupGCBase() throws Exception {
6165 testConnectionCleanupGC(engine1);
6266 testConnectionCleanupGC(engine2);
63 }
64
65 public void testConnectionCleanupGC(Class engine) throws Exception {
67 testConnectionCleanupGC(engine3);
68 }
69
70 protected void testConnectionCleanupGC(Class<?> engine) throws Exception {
6671 final Client client = createEngine(engine);
6772 counter.set(0);
6873
98103 public void testConnectionCleanupAuto() throws Exception {
99104 testConnectionCleanupAuto(engine1);
100105 testConnectionCleanupAuto(engine2);
101 }
102
103 public void testConnectionCleanupAuto(Class engine) throws Exception {
106 testConnectionCleanupAuto(engine3);
107 }
108
109 protected void testConnectionCleanupAuto(Class<?> engine) throws Exception {
104110 final Client client = createEngine(engine);
105111 counter.set(0);
106112
135141 public void testConnectionCleanupProxy() throws Exception {
136142 testConnectionCleanupProxy(engine1);
137143 testConnectionCleanupProxy(engine2);
138 }
139
140 public void testConnectionCleanupProxy(Class engine) throws Exception {
144 testConnectionCleanupProxy(engine3);
145 }
146
147 protected void testConnectionCleanupProxy(Class<?> engine) throws Exception {
141148 final ResteasyClient client = createEngine(engine);
142149 final ApacheHttpClient4Resource proxy = client.target(PortProviderUtil.generateBaseUrl(ApacheHttpClient43Test.class.getSimpleName())).proxy(ApacheHttpClient4Resource.class);
143150 counter.set(0);
176183 public void testConnectionCleanupErrorGC() throws Exception {
177184 testConnectionCleanupErrorGC(engine1);
178185 testConnectionCleanupErrorGC(engine2);
186 testConnectionCleanupErrorGC(engine3);
179187 }
180188
181189 /**
182190 * This is regression test for RESTEASY-1273
183191 */
184 public void testConnectionCleanupErrorGC(Class engine) throws Exception {
192 protected void testConnectionCleanupErrorGC(Class<?> engine) throws Exception {
185193 final ResteasyClient client = createEngine(engine);
186194 final ApacheHttpClient4Resource proxy = client.target(PortProviderUtil.generateBaseUrl(ApacheHttpClient43Test.class.getSimpleName())).proxy(ApacheHttpClient4Resource.class);
187195 counter.set(0);
219227 public void testConnectionCleanupErrorNoGC() throws Exception {
220228 testConnectionCleanupErrorNoGC(engine1);
221229 testConnectionCleanupErrorNoGC(engine2);
230 testConnectionCleanupErrorNoGC(engine3);
222231 }
223232
224233 /**
225234 * This is regression test for RESTEASY-1273
226235 */
227 public void testConnectionCleanupErrorNoGC(Class engine) throws Exception {
236 protected void testConnectionCleanupErrorNoGC(Class<?> engine) throws Exception {
228237 final ResteasyClient client = createEngine(engine);
229238 final ApacheHttpClient4Resource proxy = client.target(PortProviderUtil.generateBaseUrl(ApacheHttpClient43Test.class.getSimpleName())).proxy(ApacheHttpClient4Resource.class);
230239 counter.set(0);
267276 public void testConnectionWithRequestBody() throws InterruptedException {
268277 testConnectionWithRequestBody(engine1);
269278 testConnectionWithRequestBody(engine2);
270 }
271
272 public void testConnectionWithRequestBody(Class engine) throws InterruptedException {
279 testConnectionWithRequestBody(engine3);
280 }
281
282 protected void testConnectionWithRequestBody(Class<?> engine) throws InterruptedException {
273283 final ResteasyClient client = createEngine(engine);
274284 final ApacheHttpClient4Resource proxy = client.target(PortProviderUtil.generateBaseUrl(ApacheHttpClient43Test.class.getSimpleName())).proxy(ApacheHttpClient4Resource.class);
275285 counter.set(0);
308318 }
309319 }
310320
311 @SuppressWarnings(value = "unchecked")
312 private ResteasyClient createEngine(Class engine) {
321 private ResteasyClient createEngine(Class<?> engine) {
313322 RequestConfig reqConfig = RequestConfig.custom() // apache HttpClient specific
314323 .setConnectTimeout(5000)
315324 .setSocketTimeout(5000)
324333
325334 if (engine.isAssignableFrom(ApacheHttpClient43Engine.class)) {
326335 executor = new ApacheHttpClient43Engine(httpClient);
336 } else if (engine.isAssignableFrom(ApacheHttpAsyncClient4Engine.class)) {
337 CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create().setMaxConnTotal(3).build();
338 executor = new ApacheHttpAsyncClient4Engine(client, true);
339 } else if (engine.isAssignableFrom(URLConnectionEngine.class)) {
340 executor = new URLConnectionEngine();
327341 } else {
328 executor = new URLConnectionEngine();
342 Assert.fail("unknown engine");
343 executor = null;
329344 }
330345
331346
0 package org.jboss.resteasy.test.client.other;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine;
9 import org.jboss.resteasy.test.client.other.resource.ApacheHttpClient4Resource;
10 import org.jboss.resteasy.test.client.other.resource.ApacheHttpClient4ResourceImpl;
11 import org.jboss.resteasy.test.client.other.resource.CustomHttpClientEngineBuilder;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.Assert;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 /**
21 * @tpSubChapter Resteasy-client
22 * @tpChapter Integration tests
23 * @tpTestCaseDetails Client engine customization (RESTEASY-1599)
24 * @tpSince RESTEasy 3.0.24
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class CustomHttpClientEngineTest {
29
30 @Deployment
31 public static Archive<?> deploySimpleResource() {
32 WebArchive war = TestUtil.prepareArchive(CustomHttpClientEngineTest.class.getSimpleName());
33 war.addClass(ApacheHttpClient4Resource.class);
34 return TestUtil.finishContainerPrepare(war, null, ApacheHttpClient4ResourceImpl.class);
35 }
36
37 private String generateURL(String path) {
38 return PortProviderUtil.generateURL(path, CustomHttpClientEngineTest.class.getSimpleName());
39 }
40
41 /**
42 * @tpTestDetails Create custom ClientHttpEngine and set it to the resteasy-client
43 * @tpSince RESTEasy 3.0.24
44 */
45 @Test
46 public void test() {
47 ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder();
48 ClientHttpEngine engine = new CustomHttpClientEngineBuilder().resteasyClientBuilder(clientBuilder).build();
49 ResteasyClient client = clientBuilder.httpEngine(engine).build();
50 Assert.assertTrue(ApacheHttpClient43Engine.class.isInstance(client.httpEngine()));
51
52 ApacheHttpClient4Resource proxy = client.target(generateURL("")).proxy(ApacheHttpClient4Resource.class);
53 Assert.assertEquals("Unexpected response", "hello world", proxy.get());
54
55 client.close();
56 }
57 }
0 package org.jboss.resteasy.test.client.other.resource;
1
2 import org.apache.http.HttpHost;
3 import org.apache.http.client.HttpClient;
4 import org.apache.http.client.config.RequestConfig;
5 import org.apache.http.conn.HttpClientConnectionManager;
6 import org.apache.http.impl.client.HttpClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
8 import org.jboss.resteasy.client.jaxrs.ClientHttpEngineBuilder43;
9 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine;
10 import org.jboss.resteasy.client.jaxrs.engines.factory.ApacheHttpClient4EngineFactory;
11
12 import javax.net.ssl.HostnameVerifier;
13 import javax.net.ssl.SSLContext;
14
15 public class CustomHttpClientEngineBuilder extends ClientHttpEngineBuilder43 {
16
17 @Override
18 protected ClientHttpEngine createEngine(HttpClientConnectionManager cm, RequestConfig.Builder rcBuilder,
19 HttpHost defaultProxy, int responseBufferSize, HostnameVerifier verifier, SSLContext theContext)
20 {
21 HttpClient httpClient = HttpClientBuilder.create()
22 .setConnectionManager(cm)
23 .setDefaultRequestConfig(rcBuilder.build())
24 .setProxy(defaultProxy)
25 .disableContentCompression().build();
26 ApacheHttpClient43Engine engine = (ApacheHttpClient43Engine) ApacheHttpClient4EngineFactory.create(httpClient,
27 true);
28 engine.setResponseBufferSize(responseBufferSize);
29 engine.setHostnameVerifier(verifier);
30 // this may be null. We can't really support this with Apache Client.
31 engine.setSslContext(theContext);
32 return engine;
33 }
34 }
2323 * @tpSubChapter Resteasy-client
2424 * @tpChapter Integration tests
2525 * @tpTestCaseDetails Regression test for RESTEASY-1475.
26 * @tpSince RESTEasy 3.1.4
26 * @tpSince RESTEasy 3.0.24
2727 */
2828 @RunWith(Arquillian.class)
2929 @RunAsClient
5353
5454 /**
5555 * @tpTestDetails Verify "/" in "t;hawkular/f;jk-feed" is sent encoded
56 * @tpSince RESTEasy 3.1.4
56 * @tpSince RESTEasy 3.0.24
5757 */
5858 @Test
5959 public void testEncodeProxy() throws Exception
6868
6969 /**
7070 * @tpTestDetails Verify "/" in "t;hawkular/f;jk-feed" is sent unencoded
71 * @tpSince RESTEasy 3.1.4
71 * @tpSince RESTEasy 3.0.24
7272 */
7373 @Test
7474 public void testNoencodeProxy() throws Exception
0 package org.jboss.resteasy.test.client.proxy;
1
2
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.client.proxy.GenericProxyTest;
10 import org.jboss.resteasy.test.client.proxy.resource.*;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.AfterClass;
16 import org.junit.Assert;
17 import org.junit.BeforeClass;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 /**
22 * @tpSubChapter Resteasy-client
23 * @tpChapter Integration tests
24 * @tpTestCaseDetails Regression test for RESTEASY-1684
25 * @tpSince RESTEasy 3.0.24
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class NullEntityProxyTest {
30
31 private static ResteasyClient client;
32
33 @BeforeClass
34 public static void before() throws Exception {
35 client = new ResteasyClientBuilder().build();
36 }
37
38 @AfterClass
39 public static void after() throws Exception {
40 client.close();
41 }
42
43 @Deployment
44 public static Archive<?> deployUriInfoSimpleResource() {
45 WebArchive war = TestUtil.prepareArchive(GenericProxyTest.class.getSimpleName());
46 war.addClasses(NullEntityProxy.class, NullEntityProxyGreeting.class, NullEntityProxyGreeter.class);
47 return TestUtil.finishContainerPrepare(war, null, NullEntityProxyResource.class);
48 }
49
50 private static String generateBaseUrl() {
51 return PortProviderUtil.generateBaseUrl(GenericProxyTest.class.getSimpleName());
52 }
53
54 /**
55 * @tpTestDetails Test to send null Entity with proxy
56 * @tpSince RESTEasy 3.0.24
57 */
58 @Test
59 public void testNullEntityWithProxy() {
60 ResteasyWebTarget target = client.target(generateBaseUrl());
61 NullEntityProxy proxy = target.proxy(NullEntityProxy.class);
62 NullEntityProxyGreeting greeting = proxy.helloEntity(null);
63 Assert.assertEquals("Response has wrong content", null, greeting.getGreeter());
64 }
65 }
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ProxyFactory;
6 import org.jboss.resteasy.client.core.marshallers.ResteasyClientProxy;
57 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
68 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
79 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingResource;
5961 }
6062
6163 /**
64 * @tpTestDetails Cast one proxy to other proxy. Old client.
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testOldClient() throws Exception {
69 ProxyCastingInterfaceA a = ProxyFactory.create(ProxyCastingInterfaceA.class, generateURL("/foobar"));
70 assertEquals("FOO", a.getFoo());
71 ProxyCastingInterfaceB b = ((ResteasyClientProxy) a).as(ProxyCastingInterfaceB.class);
72 assertEquals("BAR", b.getBar());
73 }
74
75 /**
6276 * @tpTestDetails Cast one proxy to other proxy. New client.
6377 * @tpSince RESTEasy 3.0.17
6478 */
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ProxyFactory;
56 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
67 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
78 import org.jboss.resteasy.test.client.proxy.resource.ProxyInputStreamProxy;
5354 }
5455
5556 /**
57 * @tpTestDetails Old client version
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testInputStreamOldClient() throws Exception {
62 ProxyInputStreamProxy proxy = ProxyFactory.create(ProxyInputStreamProxy.class, generateURL("/"));
63 InputStream is = proxy.get();
64 byte[] bytes = ReadFromStream.readFromStream(100, is);
65 is.close();
66 String str = new String(bytes);
67 Assert.assertEquals("hello world", str);
68 }
69
70 /**
5671 * @tpTestDetails New client version
5772 * @tpSince RESTEasy 3.0.16
5873 */
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.client.proxy.resource.ProxyNullInputStreamClientResponseFilter;
8 import org.jboss.resteasy.test.client.proxy.resource.ProxyNullInputStreamResource;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17
18 /**
19 * @tpSubChapter Resteasy-client
20 * @tpChapter Integration tests
21 * @tpTestCaseDetails Test for RESTEASY-1671
22 * @tpSince RESTEasy 3.5
23 *
24 * Created by rsearls on 8/24/17.
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class ProxyNullInputStreamTest {
29
30 @Deployment
31 public static Archive<?> deploySimpleResource() {
32 WebArchive war = TestUtil.prepareArchive(ProxyNullInputStreamTest.class.getSimpleName());
33 war.addClasses(ProxyNullInputStreamResource.class,
34 ProxyNullInputStreamClientResponseFilter.class);
35 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
36 }
37
38 private String generateURL(String path) {
39 return PortProviderUtil.generateURL(path, ProxyNullInputStreamTest.class.getSimpleName());
40 }
41
42
43 @Test
44 public void testNullPointerEx () throws Exception {
45 ResteasyClient client = new ResteasyClientBuilder().register(ProxyNullInputStreamClientResponseFilter.class).build();
46 ProxyNullInputStreamResource pResource = client.target(generateURL("/test/user/mydb"))
47 .proxyBuilder(ProxyNullInputStreamResource.class)
48 .build();
49 try
50 {
51 pResource.getUserHead("myDb");
52 } catch (Exception e) {
53 Assert.assertEquals("HTTP 404 Not Found", e.getMessage());
54 }
55
56 }
57 }
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
57 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
68 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
79 import org.jboss.resteasy.test.client.proxy.resource.ProxyWithGenericReturnTypeMessageBodyWriter;
4749 }
4850
4951 /**
52 * @tpTestDetails Test for old client
53 * @tpSince RESTEasy 3.0.16
54 */
55 @Test
56 public void oldClientTest() throws Exception {
57 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/test/list/", ProxyWithGenericReturnTypeTest.class.getSimpleName()));
58 ClientResponse<String> response = request.get(String.class);
59 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
60 Assert.assertTrue("Wrong content of response, list was not decoden on server", response.getEntity(String.class).indexOf("List<String>") >= 0);
61 }
62
63 /**
5064 * @tpTestDetails Test for new client
5165 * @tpSince RESTEasy 3.0.16
5266 */
44 import org.jboss.arquillian.container.test.api.Deployment;
55 import org.jboss.arquillian.container.test.api.RunAsClient;
66 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.ProxyFactory;
8 import org.jboss.resteasy.client.core.executors.InMemoryClientExecutor;
79 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
810 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
911 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
12 import org.jboss.resteasy.spi.ResteasyProviderFactory;
1013 import org.jboss.resteasy.test.client.proxy.resource.ResponseObjectBasicObjectIntf;
1114 import org.jboss.resteasy.test.client.proxy.resource.ResponseObjectClientIntf;
1215 import org.jboss.resteasy.test.client.proxy.resource.ResponseObjectHateoasObject;
1720 import org.jboss.shrinkwrap.api.Archive;
1821 import org.jboss.shrinkwrap.api.spec.WebArchive;
1922 import org.junit.Before;
23 import org.junit.BeforeClass;
2024 import org.junit.After;
2125 import org.junit.Test;
2226 import org.junit.Assert;
3438 public class ResponseObjectTest {
3539
3640 protected static final Logger logger = LogManager.getLogger(ResponseObjectTest.class.getName());
41 private static InMemoryClientExecutor executor;
42 private static ResponseObjectClientIntf clientProxyFactory;
3743 static ResteasyClient client;
3844 ResponseObjectClientIntf responseObjectClientIntf;
3945
4147 public static Archive<?> deploy() {
4248 WebArchive war = TestUtil.prepareArchive(ResponseObjectTest.class.getSimpleName());
4349 return TestUtil.finishContainerPrepare(war, null, ResponseObjectResource.class);
50 }
51
52 @BeforeClass
53 public static void setup() {
54 ResteasyProviderFactory.setInstance(null);
55 executor = new InMemoryClientExecutor();
56 executor.getRegistry().addPerRequestResource(ResponseObjectResource.class);
57 clientProxyFactory = ProxyFactory.create(ResponseObjectClientIntf.class, "", executor);
4458 }
4559
4660 @Before
5670
5771 private String generateURL(String path) {
5872 return PortProviderUtil.generateURL(path, ResponseObjectTest.class.getSimpleName());
73 }
74
75 /**
76 * @tpTestDetails Tests ResponseObject annotation on a client interface, invoking the request with deprecated ProxyFactory instance
77 * @tpPassCrit The response contains the expected header
78 * @tpSince RESTEasy 3.0.16
79 */
80 @Test
81 public void testSimpleProxyFactory() {
82 ResponseObjectBasicObjectIntf obj = clientProxyFactory.get();
83 Assert.assertEquals(HttpResponseCodes.SC_OK, obj.status());
84 Assert.assertEquals("The response object doesn't contain the expected string", "ABC", obj.body());
85 Assert.assertEquals("The response object doesn't contain the expected header" , "text/plain;charset=UTF-8",
86 obj.responseDeprecated().getHeaders().getFirst("Content-Type"));
87 Assert.assertEquals("The response object doesn't contain the expected header", "text/plain;charset=UTF-8", obj.contentType());
88 }
89
90 /**
91 * @tpTestDetails Tests ResponseObject annotation on a client interface, and resource containg a Link object,
92 * forwarding to another resource and invoking the request with deprecated ProxyFactory instance
93 * @tpPassCrit The request was forwarded to another resource
94 * @tpSince RESTEasy 3.0.16
95 */
96 @Test
97 public void testLinkFollowProxyFactory() {
98 ResponseObjectHateoasObject obj = clientProxyFactory.performGetBasedOnHeader();
99 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, obj.status());
100 Assert.assertTrue("The resource was not forwarded", obj.nextLink().getPath().endsWith("next-link"));
101 Assert.assertEquals("The resource was not forwarded", "forwarded", obj.followNextLink());
59102 }
60103
61104 /**
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.MediaType;
7
8 @Path("hello")
9 public interface NullEntityProxy {
10 @POST
11 @Path("entity")
12 @Produces({MediaType.APPLICATION_JSON})
13 @Consumes({MediaType.APPLICATION_JSON})
14 public NullEntityProxyGreeting helloEntity(NullEntityProxyGreeter greeter);
15 }
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 public class NullEntityProxyGreeter {
3 String greeting;
4
5 public void setGreeting(String greeting) {
6 this.greeting = greeting;
7 }
8
9 public String getGreeting() {
10 return greeting;
11 }
12 }
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 public class NullEntityProxyGreeting {
3 NullEntityProxyGreeter greeter;
4
5 public NullEntityProxyGreeting(NullEntityProxyGreeter greeter) {
6 this.greeter = greeter;
7 }
8
9 public NullEntityProxyGreeting() {
10 }
11
12 public NullEntityProxyGreeter getGreeter() {
13 return greeter;
14 }
15
16 public void setGreeter(NullEntityProxyGreeter greeter) {
17 this.greeter = greeter;
18 }
19 }
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 public class NullEntityProxyResource implements NullEntityProxy {
3
4 public NullEntityProxyGreeting helloEntity(NullEntityProxyGreeter greeter) {
5 return new NullEntityProxyGreeting(greeter);
6 }
7 }
8
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.util.HttpHeaderNames;
3
4 import javax.ws.rs.client.ClientRequestContext;
5 import javax.ws.rs.client.ClientResponseContext;
6 import javax.ws.rs.client.ClientResponseFilter;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.Provider;
9
10
11 /**
12 * Created by rsearls on 8/24/17.
13 */
14 @Provider
15 public class ProxyNullInputStreamClientResponseFilter implements ClientResponseFilter {
16 public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext)
17 {
18 MultivaluedMap<String,String> headers = responseContext.getHeaders();
19 // required header to mimic and force required failure behavior
20 headers.add(HttpHeaderNames.CONTENT_TYPE, "text/plain");
21 }
22 }
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.HEAD;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5
6 /**
7 * Created by rsearls on 8/23/17.
8 */
9 @Path("test")
10 public interface ProxyNullInputStreamResource {
11 @HEAD
12 @Path("/user/{db}")
13 public void getUserHead(@PathParam("db") String db);
14 }
15
22 import org.jboss.resteasy.annotations.Body;
33 import org.jboss.resteasy.annotations.ResponseObject;
44 import org.jboss.resteasy.annotations.Status;
5 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Tests deprecated client proxy)
56
67 import javax.ws.rs.HeaderParam;
78
1415 String body();
1516
1617 org.jboss.resteasy.client.jaxrs.internal.ClientResponse response();
17
18
19 ClientResponse responseDeprecated();
20
1821 @HeaderParam("Content-Type")
1922 String contentType();
2023 }
00 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.spi.Link;
13
24 import javax.ws.rs.GET;
35 import javax.ws.rs.Path;
46 import javax.ws.rs.Produces;
57 import javax.ws.rs.core.Context;
6 import javax.ws.rs.core.Link;
78 import javax.ws.rs.core.Response;
89 import javax.ws.rs.core.UriInfo;
9
10 import org.jboss.resteasy.specimpl.LinkBuilderImpl;
11
1210 import java.net.URI;
1311
1412 @Path("test")
2422 @Path("/link-header")
2523 public Response getWithHeader(@Context UriInfo uri) {
2624 URI subUri = uri.getAbsolutePathBuilder().path("next-link").build();
27 Link link = new LinkBuilderImpl().uri(subUri).rel("nextLink").build();
25 Link link = new Link();
26 link.setHref(subUri.toASCIIString());
27 link.setRelationship("nextLink");
2828 return Response.noContent().header("Link", link.toString()).build();
2929 }
3030
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6
7 @Path("/redirect")
8 public interface ClientResponseRedirectClientResponseOld {
9 @GET
10 ClientResponse get();
11 }
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.DELETE;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.PATCH;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.PUT;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/test")
12 public class JAXRS21SyncInvokeResource {
13 @GET
14 @Produces("text/plain")
15 public String get() {
16 return "get";
17 }
18
19 @PUT
20 @Consumes("text/plain")
21 public String put(String str) {
22 return "put " + str;
23 }
24
25 @POST
26 @Consumes("text/plain")
27 public String post(String str) {
28 return "post " + str;
29 }
30
31 @DELETE
32 @Produces("text/plain")
33 public String delete() {
34 return "delete";
35 }
36
37 @PATCH
38 @Produces("text/plain")
39 @Consumes("text/plain")
40 public String patch(String str) {
41 return "patch " + str;
42 }
43 }
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.core.Response;
6
7 @Path("/")
8 public interface RedirectProxyResource
9 {
10
11 @Path("redirect/{p}")
12 @GET
13 Response redirect(@PathParam("p") String p);
14
15 @Path("redirected")
16 @GET
17 Response redirected();
18
19
20 @Path("redirectDirectResponse/{p}")
21 @GET
22 Response redirectDirectResponse(@PathParam("p") String p);
23
24 @Path("redirectedDirectResponse")
25 @GET
26 String redirectedDirectResponse();
27
28 @Path("movedPermanently/{p}")
29 @GET
30 Response movedPermanently(@PathParam("p") String p);
31
32
33 @Path("found/{p}")
34 @GET
35 Response found(@PathParam("p") String p);
36 }
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.PathParam;
6 import javax.ws.rs.core.Response;
7
8 import org.jboss.resteasy.utils.PortProviderUtil;
9
10 @Path("/")
11 public class RedirectResource
12 {
13 @Path("redirect/{p}")
14 @GET
15 public Response redirect(@PathParam("p") String p)
16 {
17 return Response.temporaryRedirect(PortProviderUtil.createURI("/redirected", p)).build();
18 }
19
20 @Path("redirected")
21 @GET
22 public Response redirected()
23 {
24 return Response.ok("OK").build();
25 }
26
27 @Path("post-redirect")
28 @POST
29 public Response postRedirect(String p)
30 {
31 return Response.seeOther(PortProviderUtil.createURI("/redirected", p)).build();
32 }
33
34 @Path("redirectDirectResponse/{p}")
35 @GET
36 public Response redirectDirectResponse(@PathParam("p") String p)
37 {
38 return Response.temporaryRedirect(PortProviderUtil.createURI("/redirectedDirectResponse", p)).build();
39 }
40
41 @Path("redirectedDirectResponse")
42 @GET
43 public String redirectedDirectResponse()
44 {
45 return "ok - direct response";
46 }
47
48
49 @Path("movedPermanently/{p}")
50 @GET
51 public Response movedPermanently(@PathParam("p") String p)
52 {
53 return Response.status(301).header("location", PortProviderUtil.createURI("/redirectedDirectResponse", p)).build();
54 }
55
56 @Path("found/{p}")
57 @GET
58 public Response found(@PathParam("p") String p)
59 {
60 return Response.status(302).header("location", PortProviderUtil.createURI("/redirectedDirectResponse", p)).build();
61 }
62 }
0 package org.jboss.resteasy.test.client.resource;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6 import java.util.concurrent.CompletableFuture;
7 import java.util.concurrent.CompletionStage;
8 import java.util.concurrent.ExecutorService;
9 import java.util.concurrent.Executors;
10
11 import javax.ws.rs.Consumes;
12 import javax.ws.rs.DELETE;
13 import javax.ws.rs.GET;
14 import javax.ws.rs.HEAD;
15 import javax.ws.rs.HttpMethod;
16 import javax.ws.rs.OPTIONS;
17 import javax.ws.rs.POST;
18 import javax.ws.rs.PUT;
19 import javax.ws.rs.Path;
20 import javax.ws.rs.PathParam;
21 import javax.ws.rs.Produces;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.core.Response;
24
25 import org.jboss.resteasy.utils.PortProviderUtil;
26
27 @Path("")
28 public class TestResource
29 {
30 @HttpMethod("TRACE")
31 @Target(value= ElementType.METHOD)
32 @Retention(value= RetentionPolicy.RUNTIME)
33 public @interface TRACE {
34 }
35
36 @HttpMethod("METHOD")
37 @Target({ElementType.METHOD})
38 @Retention(RetentionPolicy.RUNTIME)
39 public @interface METHOD {
40 }
41
42 @Path("get")
43 @GET
44 public Response get()
45 {
46 return Response.ok("get").build();
47 }
48
49 @GET
50 @Path("sleep")
51 @Produces("text/plain")
52 public CompletionStage<String> sleep() {
53 CompletableFuture<String> cs = new CompletableFuture<>();
54 ExecutorService executor = Executors.newSingleThreadExecutor();
55 executor.submit(() -> {
56 try {
57 Thread.sleep(3000L);
58 } catch (InterruptedException e) {
59 throw new RuntimeException(e);
60 }
61 cs.complete("get");
62 });
63 return cs;
64 }
65
66 @Path("put")
67 @PUT
68 @Consumes(MediaType.TEXT_PLAIN)
69 public Response put(String s)
70 {
71 return Response.ok(s).build();
72 }
73
74 @Path("post")
75 @POST
76 @Consumes(MediaType.TEXT_PLAIN)
77 public Response post(String s)
78 {
79 return Response.ok(s).build();
80 }
81
82 @Path("delete")
83 @DELETE
84 public Response delete()
85 {
86 return Response.ok("delete").build();
87 }
88
89 @Path("head")
90 @HEAD
91 public Response head()
92 {
93 return Response.noContent().header("key", "head").build();
94 }
95
96 @Path("options")
97 @OPTIONS
98 public Response options()
99 {
100 return Response.ok("options").build();
101 }
102
103 @Path("trace")
104 @TRACE
105 public Response trace()
106 {
107 return Response.ok("trace").build();
108 }
109
110 @Path("method")
111 @METHOD
112 public Response method()
113 {
114 return Response.ok("method").build();
115 }
116
117 @Path("methodEntity")
118 @METHOD
119 public Response methodEntity(String s)
120 {
121 return Response.ok(s).build();
122 }
123 }
+0
-127
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/core/ResteasyJAXRSImplTest.java less more
0 package org.jboss.resteasy.test.core;
1
2 import javax.ws.rs.client.ClientBuilder;
3 import javax.ws.rs.ext.RuntimeDelegate;
4
5 import org.jboss.arquillian.container.test.api.Deployment;
6 import org.jboss.arquillian.container.test.api.RunAsClient;
7 import org.jboss.arquillian.junit.Arquillian;
8 import org.jboss.resteasy.category.NotForForwardCompatibility;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.spi.ResteasyProviderFactory;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Assert;
15 import org.junit.Test;
16 import org.junit.experimental.categories.Category;
17 import org.junit.runner.RunWith;
18
19 /**
20 * @tpSubChapter Jaxrs implementation
21 * @tpChapter Integration tests
22 * @tpTestCaseDetails RESTEASY-1531
23 * @tpSince RESTEasy 3.1.0
24 */
25 @RunWith(Arquillian.class)
26 public class ResteasyJAXRSImplTest
27 {
28
29 @Deployment
30 public static Archive<?> deploy()
31 {
32 WebArchive war = TestUtil.prepareArchive(ResteasyJAXRSImplTest.class.getSimpleName());
33 war.addClass(NotForForwardCompatibility.class);
34 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
35 }
36
37 /**
38 * @tpTestDetails Tests that ResteasyClientBuilder implementation corresponds to JAXRS spec ClientBuilder
39 * @tpSince RESTEasy 3.1.0
40 */
41 @Test
42 @RunAsClient
43 public void testClientBuilder() throws Exception
44 {
45 testClientBuilderNewBuilder();
46 }
47
48 /**
49 * @tpTestDetails Tests that ResteasyClientBuilder implementation corresponds to JAXRS spec ClientBuilder. Tested client
50 * is bundled in the server.
51 * @tpSince RESTEasy 3.1.0
52 */
53 @Test
54 public void testInContainerClientBuilder() throws Exception
55 {
56 testClientBuilderNewBuilder();
57 }
58
59 /**
60 * @tpTestDetails Tests RuntimeDelegate instance implementation with ResteasyProviderFactory
61 * @tpSince RESTEasy 3.1.0
62 */
63 @Test
64 @RunAsClient
65 public void testRuntimeDelegate() throws Exception
66 {
67 testRuntimeDelegateGetInstance();
68 testResteasyProviderFactoryGetInstance();
69 testResteasyProviderFactoryNewInstance();
70 }
71
72 /**
73 * @tpTestDetails Tests RuntimeDelegate instance implementation with ResteasyProviderFactory in the container.
74 * @tpSince RESTEasy 3.1.0
75 */
76 @Test
77 @Category({NotForForwardCompatibility.class})
78 public void testInContainerRuntimeDelegate() throws Exception
79 {
80 testRuntimeDelegateGetInstance();
81 testResteasyProviderFactoryGetInstance();
82 testResteasyProviderFactoryNewInstance();
83 }
84
85 private void testClientBuilderNewBuilder() {
86 ClientBuilder client = ClientBuilder.newBuilder();
87 Assert.assertEquals(ResteasyClientBuilder.class.getName(), client.getClass().getName());
88 }
89
90 private void testRuntimeDelegateGetInstance() {
91 RuntimeDelegate.setInstance(null);
92 RuntimeDelegate rd = RuntimeDelegate.getInstance();
93 Assert.assertEquals(ResteasyProviderFactory.class.getName(), rd.getClass().getName());
94 RuntimeDelegate.setInstance(null);
95 }
96
97 private void testResteasyProviderFactoryGetInstance() {
98 ResteasyProviderFactory.setInstance(null);
99 ResteasyProviderFactory rpf = ResteasyProviderFactory.getInstance();
100 Assert.assertEquals(ResteasyProviderFactory.class, rpf.getClass());
101 Assert.assertEquals(rpf, ResteasyProviderFactory.getInstance());
102 ResteasyProviderFactory.setInstance(null);
103 ResteasyProviderFactory rpf2 = ResteasyProviderFactory.getInstance();
104 Assert.assertEquals(ResteasyProviderFactory.class, rpf2.getClass());
105 Assert.assertNotEquals(rpf, rpf2);
106 ResteasyProviderFactory.setInstance(null);
107 }
108
109 private void testResteasyProviderFactoryNewInstance() {
110 ResteasyProviderFactory.setInstance(null);
111 ResteasyProviderFactory rpf = ResteasyProviderFactory.newInstance();
112 ResteasyProviderFactory rpf2 = ResteasyProviderFactory.newInstance();
113 ResteasyProviderFactory rpf3 = ResteasyProviderFactory.newInstance();
114 Assert.assertEquals(ResteasyProviderFactory.class, rpf.getClass());
115 Assert.assertEquals(ResteasyProviderFactory.class, rpf2.getClass());
116 Assert.assertEquals(ResteasyProviderFactory.class, rpf3.getClass());
117 Assert.assertNotEquals(rpf, rpf2);
118 Assert.assertNotEquals(rpf, rpf3);
119 Assert.assertNotEquals(rpf2, rpf3);
120
121 ResteasyProviderFactory rpfGI = ResteasyProviderFactory.getInstance();
122 Assert.assertEquals(ResteasyProviderFactory.class, rpfGI.getClass());
123 Assert.assertNotEquals(rpfGI, rpf3);
124 }
125
126 }
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.hamcrest.Matchers;
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.resteasy.test.core.basic.resource.AnnotationInheritanceGenericsAbstract;
7 import org.jboss.resteasy.test.core.basic.resource.AnnotationInheritanceGenericsEntity;
8 import org.jboss.resteasy.test.core.basic.resource.AnnotationInheritanceGenericsImpl;
9 import org.jboss.resteasy.test.core.basic.resource.AnnotationInheritanceGenericsInterface;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Assert;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.HttpMethod;
19 import javax.ws.rs.Path;
20 import javax.ws.rs.client.Client;
21 import javax.ws.rs.client.ClientBuilder;
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.client.Invocation;
24 import javax.ws.rs.client.WebTarget;
25 import javax.ws.rs.core.GenericType;
26 import javax.ws.rs.core.MediaType;
27 import java.util.Collection;
28
29 /**
30 * @tpSubChapter Configuration
31 * @tpChapter Integration tests
32 * @tpTestCaseDetails Test for JAX-RS annotation inheritance with generics.
33 * @tpSince RESTEasy 3.5
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class AnnotationInheritanceGenericsTest {
38
39 private static final String TEST_NAME = AnnotationInheritanceGenericsTest.class.getSimpleName();
40
41 @Deployment
42 public static Archive<?> deploySimpleResource() {
43 WebArchive war = TestUtil.prepareArchive(TEST_NAME);
44 war.addClasses(
45 AnnotationInheritanceGenericsEntity.class,
46 AnnotationInheritanceGenericsInterface.class,
47 AnnotationInheritanceGenericsAbstract.class
48 );
49
50 return TestUtil.finishContainerPrepare(war, null, AnnotationInheritanceGenericsImpl.class);
51 }
52
53 @Test
54 public void testGetCollectionInterface() {
55 final Collection<AnnotationInheritanceGenericsEntity> entityList = invokeRequest(
56 AnnotationInheritanceGenericsImpl.class,
57 null,
58 HttpMethod.GET,
59 null,
60 new GenericType<Collection<AnnotationInheritanceGenericsEntity>>(){}
61 );
62
63 Assert.assertNotNull("Response entity list must not be null", entityList);
64 Assert.assertThat("Response entity list must contain exactly one element", entityList, Matchers.hasSize(1));
65
66 final AnnotationInheritanceGenericsEntity entity = entityList.iterator().next();
67 Assert.assertEquals(
68 "Response entity ID must match method id",
69 AnnotationInheritanceGenericsImpl.METHOD_ID_INTERFACE_GET_COLLECTION,
70 entity.getId());
71 }
72
73 @Test
74 public void testGetSingleInterface() {
75 final AnnotationInheritanceGenericsEntity entity = invokeRequest(
76 AnnotationInheritanceGenericsImpl.class,
77 "1",
78 HttpMethod.GET,
79 null,
80 new GenericType<AnnotationInheritanceGenericsEntity>(){}
81 );
82
83 Assert.assertNotNull("Response entity must not be null", entity);
84 Assert.assertEquals(
85 "Response entity ID must match method id",
86 AnnotationInheritanceGenericsImpl.METHOD_ID_INTERFACE_GET_SINGLE,
87 entity.getId());
88 }
89
90 @Test
91 public void testPostInterface() {
92 final AnnotationInheritanceGenericsEntity requestEntity = new AnnotationInheritanceGenericsEntity();
93
94 final AnnotationInheritanceGenericsEntity entity = invokeRequest(
95 AnnotationInheritanceGenericsImpl.class,
96 null,
97 HttpMethod.POST,
98 requestEntity,
99 new GenericType<AnnotationInheritanceGenericsEntity>(){}
100 );
101
102 Assert.assertNotNull("Response entity must not be null", entity);
103 Assert.assertEquals(
104 "Response entity ID must match method id",
105 AnnotationInheritanceGenericsImpl.METHOD_ID_INTERFACE_POST,
106 entity.getId());
107 }
108
109 @Test
110 public void testPutInterface() {
111 final AnnotationInheritanceGenericsEntity requestEntity = new AnnotationInheritanceGenericsEntity();
112
113 final AnnotationInheritanceGenericsEntity entity = invokeRequest(
114 AnnotationInheritanceGenericsImpl.class,
115 "1",
116 HttpMethod.PUT,
117 requestEntity,
118 new GenericType<AnnotationInheritanceGenericsEntity>(){}
119 );
120
121 Assert.assertNotNull("Response entity must not be null", entity);
122 Assert.assertEquals(
123 "Response entity ID must match method id",
124 AnnotationInheritanceGenericsImpl.METHOD_ID_INTERFACE_PUT,
125 entity.getId());
126 }
127
128 @Test
129 public void testPutAbstract() {
130 final AnnotationInheritanceGenericsEntity requestEntity = new AnnotationInheritanceGenericsEntity();
131
132 final AnnotationInheritanceGenericsEntity entity = invokeRequest(
133 AnnotationInheritanceGenericsImpl.class,
134 null,
135 HttpMethod.PUT,
136 requestEntity,
137 new GenericType<AnnotationInheritanceGenericsEntity>(){}
138 );
139
140 Assert.assertNotNull("Response entity must not be null", entity);
141 Assert.assertEquals(
142 "Response entity ID must match method id",
143 AnnotationInheritanceGenericsImpl.METHOD_ID_ABSTRACT_PUT,
144 entity.getId());
145 }
146
147 private static <T> T invokeRequest(
148 final Class<?> resourceClass,
149 final String pathArgument,
150 final String httpMethod,
151 final Object requestEntity,
152 final GenericType<T> responseClass)
153 {
154 final Path resourcePathAnnotation = resourceClass.getAnnotation(Path.class);
155 final String resourcePath = resourcePathAnnotation.value().startsWith("/") ? resourcePathAnnotation.value() : '/' + resourcePathAnnotation.value();
156 final String resourceUrl = PortProviderUtil.generateURL(resourcePath, TEST_NAME);
157
158 final Client client = ClientBuilder.newClient();
159 final WebTarget target = client.target(resourceUrl).path((pathArgument != null) ? pathArgument : "");
160
161 final Invocation requestInvocation;
162 if (requestEntity == null) {
163 requestInvocation = target.request().build(httpMethod);
164 } else {
165 requestInvocation = target.request(MediaType.APPLICATION_XML_TYPE).build(httpMethod, Entity.xml(requestEntity));
166 }
167
168 if (responseClass != null) {
169 final T responseEntity = requestInvocation.invoke(responseClass);
170 return responseEntity;
171 } else {
172 requestInvocation.invoke();
173 return null;
174 }
175 }
176
177 }
2121 import javax.ws.rs.core.Response;
2222
2323 import java.lang.reflect.ReflectPermission;
24 import java.net.SocketPermission;
2425 import java.util.ArrayList;
2526 import java.util.Iterator;
2627 import java.util.List;
2728 import java.util.PropertyPermission;
29 import java.util.logging.LoggingPermission;
2830
2931 /**
3032 * @tpSubChapter Core
5153 singletons.add(InternalDispatcherForwardingResource.class);
5254 // Arquillian in the deployment
5355 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
56 new LoggingPermission("control", ""),
57 new PropertyPermission("arquillian.*", "read"),
58 new PropertyPermission("ipv6", "read"),
59 new PropertyPermission("node", "read"),
60 new PropertyPermission("org.jboss.resteasy.port", "read"),
5461 new RuntimePermission("accessDeclaredMembers"),
55 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
62 new RuntimePermission("getenv.RESTEASY_PORT"),
63 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
64 ), "permissions.xml");
5665 return TestUtil.finishContainerPrepare(war, null, singletons, (Class<?>[]) null);
5766 }
5867
2020 /**
2121 * @tpSubChapter RESTEASY-1565
2222 * @tpChapter Integration tests
23 * @tpSince RESTEasy 3.1.1.Final
23 * @tpSince RESTEasy 3.0.21.Final
2424 */
2525 @RunWith(Arquillian.class)
2626 @RunAsClient
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.NotAllowedException;
3 import javax.ws.rs.PUT;
4 import java.util.Collection;
5
6 public class AnnotationInheritanceGenericsAbstract<ENTITY_TYPE, ID_TYPE> implements AnnotationInheritanceGenericsInterface<ENTITY_TYPE, ID_TYPE> {
7
8 @Override
9 public Collection<ENTITY_TYPE> get() {
10 throw new NotAllowedException((Throwable) null);
11 }
12
13 @Override
14 public ENTITY_TYPE get(final ID_TYPE id) {
15 throw new NotAllowedException((Throwable) null);
16 }
17
18 @Override
19 public ENTITY_TYPE post(final ENTITY_TYPE entity) {
20 throw new NotAllowedException((Throwable) null);
21 }
22
23 @Override
24 public ENTITY_TYPE put(final ID_TYPE id, final ENTITY_TYPE entity) {
25 throw new NotAllowedException((Throwable) null);
26 }
27
28 @PUT
29 public ENTITY_TYPE put(final ENTITY_TYPE entity) {
30 throw new NotAllowedException((Throwable) null);
31 }
32
33 }
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.xml.bind.annotation.XmlElement;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement(name = "entity")
6 public class AnnotationInheritanceGenericsEntity {
7
8 private Long id;
9
10 @XmlElement
11 public Long getId() {
12 return id;
13 }
14
15 public void setId(Long id) {
16 this.id = id;
17 }
18
19 }
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.MediaType;
6 import java.util.Collection;
7 import java.util.Collections;
8
9 @Path("genericsInheritance")
10 @Consumes({MediaType.APPLICATION_XML})
11 @Produces({MediaType.APPLICATION_XML})
12 public class AnnotationInheritanceGenericsImpl extends AnnotationInheritanceGenericsAbstract<AnnotationInheritanceGenericsEntity, Long> {
13
14 public static final Long METHOD_ID_INTERFACE_GET_COLLECTION = 1L;
15 public static final Long METHOD_ID_INTERFACE_GET_SINGLE = 2L;
16 public static final Long METHOD_ID_INTERFACE_POST = 3L;
17 public static final Long METHOD_ID_INTERFACE_PUT = 4L;
18 public static final Long METHOD_ID_ABSTRACT_PUT = 5L;
19
20 @Override
21 public Collection<AnnotationInheritanceGenericsEntity> get() {
22 final AnnotationInheritanceGenericsEntity entity = new AnnotationInheritanceGenericsEntity();
23 entity.setId(METHOD_ID_INTERFACE_GET_COLLECTION);
24
25 return Collections.singleton(entity);
26 }
27
28 @Override
29 public AnnotationInheritanceGenericsEntity get(Long id) {
30 final AnnotationInheritanceGenericsEntity entity = new AnnotationInheritanceGenericsEntity();
31 entity.setId(METHOD_ID_INTERFACE_GET_SINGLE);
32
33 return entity;
34 }
35
36 @Override
37 public AnnotationInheritanceGenericsEntity post(AnnotationInheritanceGenericsEntity entity) {
38 entity.setId(METHOD_ID_INTERFACE_POST);
39 return entity;
40 }
41
42 @Override
43 public AnnotationInheritanceGenericsEntity put(Long id, AnnotationInheritanceGenericsEntity entity) {
44 entity.setId(METHOD_ID_INTERFACE_PUT);
45 return entity;
46 }
47
48 @Override
49 public AnnotationInheritanceGenericsEntity put(AnnotationInheritanceGenericsEntity entity) {
50 entity.setId(METHOD_ID_ABSTRACT_PUT);
51 return entity;
52 }
53
54 }
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.PUT;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import java.util.Collection;
8
9 public interface AnnotationInheritanceGenericsInterface<ENTITY_TYPE, ID_TYPE> {
10
11 @GET
12 Collection<ENTITY_TYPE> get();
13
14 @GET
15 @Path("{id}")
16 ENTITY_TYPE get(@PathParam("id") final ID_TYPE id);
17
18 @POST
19 ENTITY_TYPE post(ENTITY_TYPE entity);
20
21 @PUT
22 @Path("{id}")
23 ENTITY_TYPE put(@PathParam("id") final ID_TYPE id, final ENTITY_TYPE entity);
24
25 }
00 package org.jboss.resteasy.test.core.basic.resource;
11
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
26 import org.junit.Assert;
37
4 import javax.annotation.Priority;
58 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.ext.Provider;
7 import javax.ws.rs.ext.WriterInterceptor;
8 import javax.ws.rs.ext.WriterInterceptorContext;
9
109 import java.io.IOException;
1110
12 @Provider
13 @Priority(30)
14 public class ContextAfterEncoderInterceptor implements WriterInterceptor {
15
16 @Override
17 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
18 {
19 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextAfterEncoderInterceptor don't have correct headers";
20 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("before-encoder"));
21 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("encoder"));
22 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("end"));
23 context.getHeaders().add("after-encoder", "true");
24 context.proceed();
25 }
11 @Precedence("AFTER_ENCODER")
12 @ServerInterceptor
13 public class ContextAfterEncoderInterceptor implements MessageBodyWriterInterceptor {
14 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
15 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextAfterEncoderInterceptor don't have correct headers";
16 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("before-encoder"));
17 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("encoder"));
18 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("end"));
19 context.getHeaders().add("after-encoder", "true");
20 context.proceed();
21 }
2622 }
00 package org.jboss.resteasy.test.core.basic.resource;
11
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
26 import org.junit.Assert;
37
4 import javax.annotation.Priority;
58 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.ext.Provider;
7 import javax.ws.rs.ext.WriterInterceptor;
8 import javax.ws.rs.ext.WriterInterceptorContext;
9
109 import java.io.IOException;
1110
12 @Provider
13 @Priority(10)
14 public class ContextBeforeEncoderInterceptor implements WriterInterceptor {
15
16 @Override
17 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
18 {
19 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextBeforeEncoderInterceptor don't have correct headers";
20 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("after-encoder"));
21 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("encoder"));
22 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("end"));
23 context.getHeaders().add("before-encoder", "true");
24 context.proceed();
25 }
11 @Precedence("BEFORE_ENCODER")
12 @ServerInterceptor
13 public class ContextBeforeEncoderInterceptor implements MessageBodyWriterInterceptor {
14 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
15 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextBeforeEncoderInterceptor don't have correct headers";
16 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("after-encoder"));
17 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("encoder"));
18 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("end"));
19 context.getHeaders().add("before-encoder", "true");
20 context.proceed();
21 }
2622 }
00 package org.jboss.resteasy.test.core.basic.resource;
11
2 import org.jboss.resteasy.annotations.interception.EncoderPrecedence;
3 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
26 import org.junit.Assert;
37
4 import javax.annotation.Priority;
58 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.ext.Provider;
7 import javax.ws.rs.ext.WriterInterceptor;
8 import javax.ws.rs.ext.WriterInterceptorContext;
9
109 import java.io.IOException;
1110
12 @Provider
13 @Priority(20)
14 public class ContextEncoderInterceptor implements WriterInterceptor {
15
16 @Override
17 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
18 {
19 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextEncoderInterceptor don't have correct headers";
20 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("before-encoder"));
21 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("after-encoder"));
22 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("end"));
23 context.getHeaders().add("encoder", "true");
24 context.proceed();
25 }
11 @EncoderPrecedence
12 @ServerInterceptor
13 public class ContextEncoderInterceptor implements MessageBodyWriterInterceptor {
14 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
15 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextEncoderInterceptor don't have correct headers";
16 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("before-encoder"));
17 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("after-encoder"));
18 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("end"));
19 context.getHeaders().add("encoder", "true");
20 context.proceed();
21 }
2622 }
00 package org.jboss.resteasy.test.core.basic.resource;
11
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
26 import org.junit.Assert;
37
4 import javax.annotation.Priority;
58 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.ext.Provider;
7 import javax.ws.rs.ext.WriterInterceptor;
8 import javax.ws.rs.ext.WriterInterceptorContext;
9
109 import java.io.IOException;
1110
12 @Provider
13 @Priority(40)
14 public class ContextEndInterceptor implements WriterInterceptor {
15
16 @Override
17 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
18 {
19 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextEndInterceptor don't have correct headers";
20 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("before-encoder"));
21 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("after-encoder"));
22 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("encoder"));
23 context.getHeaders().add("end", "true");
24 context.proceed();
25 }
11 @Precedence("END")
12 @ServerInterceptor
13 public class ContextEndInterceptor implements MessageBodyWriterInterceptor {
14 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
15 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextEndInterceptor don't have correct headers";
16 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("before-encoder"));
17 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("after-encoder"));
18 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("encoder"));
19 context.getHeaders().add("end", "true");
20 context.proceed();
21 }
2622 }
1313 import org.jboss.resteasy.utils.TestUtil;
1414 import org.jboss.shrinkwrap.api.Archive;
1515 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
1617 import org.junit.Assert;
1718 import org.junit.Test;
1819 import org.junit.runner.RunWith;
2021 import javax.ws.rs.client.WebTarget;
2122 import javax.ws.rs.core.Response;
2223 import java.lang.reflect.ReflectPermission;
24 import java.net.SocketPermission;
2325 import java.util.ArrayList;
2426 import java.util.List;
2527 import java.util.PropertyPermission;
28 import java.util.logging.LoggingPermission;
2629
2730 import static org.hamcrest.core.Is.is;
2831
4346 singletons.add(CorsFilter.class);
4447 // Arquillian in the deployment and use of PortProviderUtil
4548 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
46 new RuntimePermission("accessDeclaredMembers"),
49 new LoggingPermission("control", ""),
4750 new PropertyPermission("arquillian.*", "read"),
4851 new PropertyPermission("node", "read"),
4952 new PropertyPermission("ipv6", "read"),
53 new PropertyPermission("org.jboss.resteasy.port", "read"),
54 new RuntimePermission("accessDeclaredMembers"),
5055 new RuntimePermission("getenv.RESTEASY_PORT"),
51 new PropertyPermission("org.jboss.resteasy.port", "read")), "permissions.xml");
56 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
57 ), "permissions.xml");
5258 return TestUtil.finishContainerPrepare(war, null, singletons, CorsFiltersResource.class);
5359 }
5460
5561 private String generateURL(String path) {
5662 return PortProviderUtil.generateURL(path, CorsFiltersTest.class.getSimpleName());
63 }
64
65 @After
66 public void resetFilter() {
67 CorsFilter corsFilter = (CorsFilter) TestApplication.singletons.iterator().next();
68 corsFilter.getAllowedOrigins().remove("http://" + PortProviderUtil.getHost());
5769 }
5870
5971 /**
95107 client.close();
96108 }
97109
110 /**
111 * @tpTestDetails Test that the response contains the Vary: Origin header
112 * @tpInfo RESTEASY-1704
113 * @tpSince RESTEasy 3.0.25
114 */
115 @Test
116 public void testVaryOriginHeader() {
117 String testedURL = "http://" + PortProviderUtil.getHost();
118 ResteasyClient client = new ResteasyClientBuilder().build();
119 WebTarget target = client.target(generateURL("/test"));
120
121 Assert.assertThat("Wrong count of singletons were created", TestApplication.singletons.size(), is(1));
122 CorsFilter corsFilter = (CorsFilter) TestApplication.singletons.iterator().next();
123 corsFilter.getAllowedOrigins().add(testedURL);
124
125 Response response = target.request().header(CorsHeaders.ORIGIN, testedURL).get();
126 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
127 Assert.assertEquals("Response doesn't contain the Vary: Origin header", CorsHeaders.ORIGIN, response.getHeaderString(CorsHeaders.VARY));
128 response.close();
129
130 response = target.request().header(CorsHeaders.ORIGIN, testedURL).options();
131 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
132 Assert.assertEquals("Response doesn't contain the Vary: Origin header", CorsHeaders.ORIGIN, response.getHeaderString(CorsHeaders.VARY));
133 response.close();
134
135 client.close();
136 }
137
98138 }
2626 * @tpSubChapter Cookies and filters
2727 * @tpChapter Integration tests
2828 * @tpTestCaseDetails Regression test for RESTEASY-1266
29 * @tpSince RESTEasy 3.1.0.Final
29 * @tpSince RESTEasy 3.0.20.Final
3030 */
3131 @RunWith(Arquillian.class)
3232 @RunAsClient
4848
4949 /**
5050 * @tpTestDetails Tests if multiple cookies are returned by the server
51 * @tpSince RESTEasy 3.1.0.Final
51 * @tpSince RESTEasy 3.0.20.Final
5252 */
5353 @Test
5454 public void testServerHeaders() {
1616 import org.jboss.resteasy.category.NotForForwardCompatibility;
1717 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
1818 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
19 import org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter;
20 import org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor;
21 import org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor;
19 import org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter;
20 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor;
21 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor;
2222 import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
2323 import org.jboss.resteasy.test.core.interceptors.resource.GzipIGZIP;
2424 import org.jboss.resteasy.test.core.interceptors.resource.GzipResource;
4141 * @tpSubChapter GZIP interceptors
4242 * @tpChapter Integration tests
4343 * @tpTestCaseDetails Gzip compression tests
44 * @tpSince RESTEasy 3.1.0.Final
44 * @tpSince RESTEasy 3.0.20.Final
4545 */
4646 @RunWith(Arquillian.class)
4747 @RunAsClient
8282 /**
8383 * @tpTestDetails Test exceeding configured maximum size on server
8484 * @tpInfo RESTEASY-1484
85 * @tpSince RESTEasy 3.1.0.Final
85 * @tpSince RESTEasy 3.0.20.Final
8686 */
8787 @Test
8888 @Category({NotForForwardCompatibility.class})
9898
9999 /**
100100 * @tpTestDetails Test exceeding configured maximum size on client
101 * @tpSince RESTEasy 3.1.0.Final
101 * @tpSince RESTEasy 3.0.20.Final
102102 */
103103 @Test
104104 public void testMaxConfiguredSizeReceiving() throws Exception {
1313 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
1414 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
1515 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
16 import org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter;
17 import org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor;
18 import org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor;
16 import org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter;
17 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor;
18 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor;
1919 import org.jboss.resteasy.test.core.interceptors.resource.GzipProxy;
2020 import org.jboss.resteasy.test.core.interceptors.resource.GzipResource;
2121 import org.jboss.resteasy.test.core.interceptors.resource.GzipIGZIP;
283283 /**
284284 * @tpTestDetails Test exceeding default maximum size
285285 * @tpInfo RESTEASY-1484
286 * @tpSince RESTEasy 3.1.0.Final
286 * @tpSince RESTEasy 3.0.20.Final
287287 */
288288 @Test
289289 @Category({NotForForwardCompatibility.class})
00 package org.jboss.resteasy.test.core.interceptors.resource;
11
2 import java.io.IOException;
2 import org.jboss.resteasy.core.ResourceMethodInvoker;
3 import org.jboss.resteasy.core.ServerResponse;
4 import org.jboss.resteasy.spi.Failure;
5 import org.jboss.resteasy.spi.HttpRequest;
6 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
37
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerRequestFilter;
8 import javax.ws.rs.WebApplicationException;
69 import javax.ws.rs.ext.Provider;
710
811 @Provider
9 public class PreProcessorExceptionMapperPreProcessSecurityInterceptor implements ContainerRequestFilter {
10
11 @Override
12 public void filter(ContainerRequestContext requestContext) throws IOException
13 {
14 throw new PreProcessorExceptionMapperCandlepinUnauthorizedException();
15 }
12 public class PreProcessorExceptionMapperPreProcessSecurityInterceptor implements PreProcessInterceptor {
13 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
14 throw new PreProcessorExceptionMapperCandlepinUnauthorizedException();
15 }
1616 }
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5 import javax.ws.rs.Produces;
6
7 /**
8 * Created by rsearls on 9/5/17.
9 */
10 @Path("test")
11 public class TestResource1 {
12
13 @GET
14 @Path("x")
15 @Produces("text/plain")
16 public Response method() {
17 return Response.ok("ok").build();
18 }
19 }
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.Produces;
4
5 /**
6 * Created by rsearls on 9/5/17.
7 */
8 @Path("test")
9 public class TestResource2 {
10
11 @Path("x")
12 @Produces("text/plain")
13 public TestSubResource locator() {
14 return new TestSubResource();
15 }
16 }
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;
4
5 /**
6 * Created by rsearls on 9/5/17.
7 */
8 public class TestSubResource {
9
10 @POST
11 @Path("")
12 public String sub(String s) {
13 return "sub(" + s + ")";
14 }
15 }
16
44 import org.jboss.arquillian.container.test.api.Deployment;
55 import org.jboss.arquillian.container.test.api.RunAsClient;
66 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.category.NotForForwardCompatibility;
78 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
89 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
910 import org.jboss.resteasy.test.core.logging.resource.DebugLoggingEndPoint;
2223 import org.junit.Before;
2324 import org.junit.BeforeClass;
2425 import org.junit.Test;
26 import org.junit.experimental.categories.Category;
2527 import org.junit.runner.RunWith;
2628 import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
2729
3739 * @tpChapter Integration tests
3840 * @tpTestCaseDetails Test debug messages for used Interceptors and Providers.
3941 * Regression test for RESTEASY-1415 and RESTEASY-1558.
40 * @tpSince RESTEasy 3.1.0
42 * @tpSince RESTEasy 3.0.20.Final
4143 */
4244 @RunWith(Arquillian.class)
4345 @RunAsClient
46 @Category({NotForForwardCompatibility.class})
4447 public class DebugLoggingTest {
4548
4649 static ResteasyClient client;
100103
101104 /**
102105 * @tpTestDetails Check build-in providers and interceptors
103 * @tpSince RESTEasy 3.1.0
106 * @tpSince RESTEasy 3.0.20.Final
104107 */
105108 @Test
106109 public void testBuildIn() throws Exception {
126129
127130 /**
128131 * @tpTestDetails Check user's custom providers and interceptors
129 * @tpSince RESTEasy 3.1.0
132 * @tpSince RESTEasy 3.0.20.Final
130133 */
131134 @Test
132135 public void testCustom() throws Exception {
66 import org.jboss.arquillian.container.test.api.Deployment;
77 import org.jboss.arquillian.container.test.api.RunAsClient;
88 import org.jboss.arquillian.junit.Arquillian;
9 import org.jboss.resteasy.client.ProxyFactory;
910 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
1011 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
1112 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9495 }
9596
9697 /**
98 * @tpTestDetails Test for old resteasy client with proxy
99 * @tpSince RESTEasy 3.0.16
100 */
101 @Test
102 public void testFormParamOldRESTEasyClient() {
103 final ServletMappingProxy client = ProxyFactory.create(ServletMappingProxy.class, generateURL("/resteasy/rest"));
104 final String result = client.postForm("value");
105 Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, result, "value");
106 }
107
108 /**
97109 * @tpTestDetails Test for new resteasy client with proxy
98110 * @tpSince RESTEasy 3.0.16
99111 */
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
57 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
68 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
79 import org.jboss.resteasy.test.exception.resource.ExceptionMapperCustomRuntimeCustomMapper;
5658 client.close();
5759 }
5860
61 /**
62 * @tpTestDetails Check ExceptionMapper for Custom RuntimeException. Check the response contains headers and entity
63 * from custom exception mapper. Using ClientRequest/ClientResponse.
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testMapperWithClientRequest() throws Exception {
68 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/test" , ExceptionMapperCustomRuntimeExceptionTest.class.getSimpleName()));
69 ClientResponse<String> response = request.get(String.class);
70 Assert.assertEquals(Response.Status.PRECONDITION_FAILED.getStatusCode(), response.getStatus());
71 Assert.assertEquals("Wrong headers", response.getHeaders().getFirst("custom"), "header");
72 Assert.assertEquals("The response doesn't contain the entity from custom exception mapper",
73 "My custom message", response.getEntity());
74
75 response.close();
76 }
77
78
5979 }
0 package org.jboss.resteasy.test.form;
1
2 import javax.ws.rs.client.Client;
3 import javax.ws.rs.client.ClientBuilder;
4 import javax.ws.rs.client.Entity;
5 import javax.ws.rs.client.Invocation;
6 import javax.ws.rs.core.Response;
7
8 import org.jboss.arquillian.container.test.api.Deployment;
9 import org.jboss.arquillian.container.test.api.RunAsClient;
10 import org.jboss.arquillian.junit.Arquillian;
11 import org.jboss.resteasy.test.form.resource.FormEntityResource;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.AfterClass;
17 import org.junit.Assert;
18 import org.junit.BeforeClass;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 /**
23 * @tpSubChapter Form tests
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.5
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class FormEntityTest {
30
31 private static Client client;
32
33 @Deployment
34 public static Archive<?> createTestArchive() {
35 WebArchive war = TestUtil.prepareArchive(FormEntityTest.class.getSimpleName());
36 return TestUtil.finishContainerPrepare(war, null, FormEntityResource.class);
37 }
38
39 private String generateURL(String path) {
40 return PortProviderUtil.generateURL(path, FormEntityTest.class.getSimpleName());
41 }
42
43 @BeforeClass
44 public static void before() throws Exception {
45 client = ClientBuilder.newClient();
46 }
47
48 @AfterClass
49 public static void after() throws Exception {
50 client.close();
51 }
52
53 /**
54 * @tpTestDetails Retrieve form param and form entity
55 * @tpSince RESTEasy 3.5
56 */
57 @Test
58 public void testWithEqualsAndEmptyString() throws Exception
59 {
60 Invocation.Builder request = client.target(generateURL("/test/form")).request();
61 Response response = request.post(Entity.entity("fp=abc&fp2=\"\"", "application/x-www-form-urlencoded"));
62 String s = response.readEntity(String.class);
63 Assert.assertEquals(200, response.getStatus());
64 Assert.assertTrue(s.equals("abc|fp=abc&fp2=\"\"") || s.equals("abc|fp2=\"\"&fp=abc"));
65 }
66
67 /**
68 * @tpTestDetails Retrieve form param and form entity
69 * @tpSince RESTEasy 3.5
70 */
71 @Test
72 public void testWithEquals() throws Exception
73 {
74 Invocation.Builder request = client.target(generateURL("/test/form")).request();
75 Response response = request.post(Entity.entity("fp=abc&fp2=", "application/x-www-form-urlencoded"));
76 String s = response.readEntity(String.class);
77 Assert.assertEquals(200, response.getStatus());
78 Assert.assertTrue(s.equals("abc|fp=abc&fp2") || s.equals("abc|fp2&fp=abc"));
79 }
80
81 /**
82 * @tpTestDetails Retrieve form param and form entity
83 * @tpSince RESTEasy 3.5
84 */
85 @Test
86 public void testWithoutEquals() throws Exception
87 {
88 Invocation.Builder request = client.target(generateURL("/test/form")).request();
89 Response response = request.post(Entity.entity("fp=abc&fp2", "application/x-www-form-urlencoded"));
90 String s = response.readEntity(String.class);
91 Assert.assertEquals(200, response.getStatus());
92 Assert.assertTrue(s.equals("abc|fp=abc&fp2") || s.equals("abc|fp2&fp=abc"));
93 }
94 }
55 import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
66 import static org.junit.Assert.assertEquals;
77
8 import java.io.FilePermission;
89 import java.io.StringWriter;
10 import java.lang.reflect.ReflectPermission;
911 import java.nio.charset.StandardCharsets;
1012
1113 import javax.ws.rs.client.Client;
2830 import org.jboss.resteasy.test.form.resteasy1405.InputData;
2931 import org.jboss.resteasy.test.form.resteasy1405.MyResource;
3032 import org.jboss.resteasy.test.form.resteasy1405.OutputData;
33 import org.jboss.resteasy.utils.PermissionUtil;
3134 import org.jboss.resteasy.utils.PortProviderUtil;
3235 import org.jboss.resteasy.utils.TestUtil;
3336 import org.jboss.shrinkwrap.api.Archive;
4144 /**
4245 * @tpSubChapter Form tests
4346 * @tpChapter Integration tests
44 * @tpTestCaseDetails Injection of @FormParam InputPart fields in @MultipartForm parameters
45 * @tpSince RESTEasy 3.1.0
47 * @tpTestCaseDetails Injection of @FormParam InputPart fields in @MultipartForm parameters, RESTEASY-1405
48 * @tpSince RESTEasy 3.0.20.Final
4649 */
4750 @RunWith(Arquillian.class)
4851 @RunAsClient
5558 {
5659 WebArchive war = TestUtil.prepareArchive(Resteasy1405Test.class.getSimpleName());
5760 war.addClasses(ByFieldForm.class, BySetterForm.class, InputData.class, OutputData.class);
61
62 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
63 new FilePermission("<<ALL FILES>>", "read"),
64 new RuntimePermission("accessDeclaredMembers"),
65 new RuntimePermission("getClassLoader")),
66 "permissions.xml");
67
5868 return TestUtil.finishContainerPrepare(war, null, MyResource.class);
5969 }
6070
8191
8292 /**
8393 * @tpTestDetails Injection of Content-type into MultiPartForm with annotated form fields
84 * @tpSince RESTEasy 3.1.0
94 * @tpSince RESTEasy 3.0.20.Final
8595 */
8696 @Test
8797 public void testInputPartByField() throws Exception
113123
114124 /**
115125 * @tpTestDetails Injection of Content-type into MultiPartForm with annotated form setters
116 * @tpSince RESTEasy 3.1.0
126 * @tpSince RESTEasy 3.0.20.Final
117127 */
118128 @Test
119129 public void testInputPartBySetter() throws Exception
0 package org.jboss.resteasy.test.form.resource;
1
2 import javax.ws.rs.FormParam;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5
6 @Path("test")
7 public class FormEntityResource {
8
9 @POST
10 @Path("form")
11 public String formParam(@FormParam("fp") String fp, String content) {
12 return fp + "|" + content;
13 }
14 }
66 import org.jboss.arquillian.container.test.api.RunAsClient;
77 import org.jboss.arquillian.junit.Arquillian;
88 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter;
10 import org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor;
11 import org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor;
9 import org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter;
10 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor;
11 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor;
1212 import org.jboss.resteasy.test.interceptor.resource.GZIPAnnotationInterface;
1313 import org.jboss.resteasy.test.interceptor.resource.GZIPAnnotationResource;
1414 import org.jboss.resteasy.utils.PortProviderUtil;
5959 }
6060
6161 /**
62 * @tpTestDetails Test that org.jboss.resteasy.plugins.interceptors.ClientContentEncodingAnnotationFilter
63 * and org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter
62 * @tpTestDetails Test that org.jboss.resteasy.plugins.interceptors.encoding.ClientContentEncodingAnnotationFilter
63 * and org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter
6464 * are called on client side
6565 * @tpSince RESTEasy 3.0.20
6666 */
0 package org.jboss.resteasy.test.interceptor;
1
2
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.resteasy.test.client.ClientTestBase;
7 import org.jboss.resteasy.test.client.exception.resource.ClientExceptionsData;
8 import org.jboss.resteasy.test.client.exception.resource.ClientExceptionsResource;
9 import org.jboss.resteasy.test.interceptor.resource.PreMatchingClientRequestFilterImpl;
10 import org.jboss.resteasy.test.interceptor.resource.PreMatchingClientResource;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Rule;
18 import org.junit.Test;
19 import org.junit.rules.ExpectedException;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.ProcessingException;
23 import javax.ws.rs.client.Client;
24 import javax.ws.rs.client.ClientBuilder;
25 import javax.ws.rs.client.WebTarget;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @tpSubChapter Interceptor
30 * @tpChapter Integration tests
31 * @tpTestCaseDetails Tests @PreMatching annotation on ClientRequestFilter (RESTEASY-1696)
32 * @tpSince RESTEasy 3.5
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class PreMatchingClientRequestFilterTest extends ClientTestBase {
37
38 @Rule
39 public ExpectedException thrown = ExpectedException.none();
40
41 static Client client;
42
43 @Deployment
44 public static Archive<?> deploy() {
45 WebArchive war = TestUtil.prepareArchive(PreMatchingClientRequestFilterTest.class.getSimpleName());
46 //rls //war.addClass(ClientExceptionsData.class);
47 return TestUtil.finishContainerPrepare(war, null, PreMatchingClientResource.class);
48 }
49
50 @Before
51 public void before() {
52 client = ClientBuilder.newClient();
53 }
54
55 @After
56 public void close() {
57 client.close();
58 }
59
60 /**
61 * @tpTestDetails Test that annotation @PreMatching on an implementation of ClientRequestFilter
62 * is ignored. This annotation is only valid on ContainerRequestFilter implementations.
63 * @tpSince RESTEasy 3.5
64 */
65 @Test
66 public void preMatchingTest() throws Exception {
67 WebTarget base = client.target(generateURL("/") + "testIt");
68 Response response = base.register(PreMatchingClientRequestFilterImpl.class).request().get();
69 Assert.assertEquals(404, response.getStatus());
70 }
71
72 }
4040 import javax.ws.rs.client.ClientBuilder;
4141 import javax.ws.rs.core.Response;
4242 import java.lang.reflect.ReflectPermission;
43 import java.net.SocketPermission;
4344 import java.util.ArrayList;
4445 import java.util.List;
4546 import java.util.PropertyPermission;
47 import java.util.logging.LoggingPermission;
4648
4749 /**
4850 * @tpSubChapter Interceptors
8284 PriorityExecutionClientRequestFilterMin.class);
8385 // Arquillian in the deployment
8486 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
87 new LoggingPermission("control", ""),
88 new PropertyPermission("arquillian.*", "read"),
89 new PropertyPermission("ipv6", "read"),
90 new PropertyPermission("node", "read"),
91 new PropertyPermission("org.jboss.resteasy.port", "read"),
8592 new RuntimePermission("accessDeclaredMembers"),
86 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
93 new RuntimePermission("getenv.RESTEASY_PORT"),
94 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
95 ), "permissions.xml");
8796 return TestUtil.finishContainerPrepare(war, null, PriorityExecutionResource.class);
8897 }
8998
+0
-72
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/interceptor/StreamCloseTest.java less more
0 package org.jboss.resteasy.test.interceptor;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.test.interceptor.resource.InterceptorStreamResource;
5 import org.jboss.resteasy.test.interceptor.resource.TestInterceptor;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.PortProviderUtil;
8 import org.jboss.resteasy.utils.TestUtil;
9 import org.jboss.shrinkwrap.api.Archive;
10 import org.jboss.shrinkwrap.api.spec.WebArchive;
11 import org.junit.After;
12 import org.junit.Assert;
13 import org.junit.Before;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.client.Entity;
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Interceptors
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.1.2
26 * @tpTestCaseDetails Verify outpustream close is invoked on server side (https://issues.jboss.org/browse/RESTEASY-1650)
27 */
28 @RunWith(Arquillian.class)
29 public class StreamCloseTest
30 {
31 @Deployment
32 public static Archive<?> deploy()
33 {
34 WebArchive war = TestUtil.prepareArchive(StreamCloseTest.class.getSimpleName());
35 return TestUtil.finishContainerPrepare(war, null, InterceptorStreamResource.class, TestInterceptor.class, PortProviderUtil.class);
36 }
37
38 static Client client;
39
40 @Before
41 public void setup()
42 {
43 client = ClientBuilder.newClient();
44 }
45
46 @After
47 public void cleanup()
48 {
49 client.close();
50 }
51
52 private String generateURL(String path)
53 {
54 return PortProviderUtil.generateURL(path, StreamCloseTest.class.getSimpleName());
55 }
56
57 @Test
58 public void testPriority() throws Exception
59 {
60 final int count = TestInterceptor.closeCounter.get();
61 Response response = client.target(generateURL("/test")).request().post(Entity.text("test"));
62 response.bufferEntity();
63 Assert.assertEquals("Wrong response status, interceptors don't work correctly", HttpResponseCodes.SC_OK,
64 response.getStatus());
65 Assert.assertEquals("Wrong content of response, interceptors don't work correctly", "test",
66 response.readEntity(String.class));
67 response.close();
68 Assert.assertEquals(1, TestInterceptor.closeCounter.get() - count);
69
70 }
71 }
0 package org.jboss.resteasy.test.interceptor.resource;
1
2 import javax.ws.rs.client.ClientRequestContext;
3 import javax.ws.rs.client.ClientRequestFilter;
4 import javax.ws.rs.container.PreMatching;
5 import javax.ws.rs.core.Response;
6
7 /**
8 * Annotation PreMatching is not valid for ClientRequestFilterImpl.
9 * This test confirms RESTEasy ignores the annotation and logs a warning msg.
10 *
11 * Created by rsearls on 8/21/17.
12 */
13 @PreMatching
14 public class PreMatchingClientRequestFilterImpl implements ClientRequestFilter {
15
16 @Override
17 public void filter(ClientRequestContext requestContext) {
18 requestContext.abortWith(Response.status(404).build());
19 }
20 }
0 package org.jboss.resteasy.test.interceptor.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 /**
6 * Created by rsearls on 8/21/17.
7 */
8 @Path("/")
9 public class PreMatchingClientResource {
10 @GET
11 @Path("testIt")
12 public String get() {
13 return "OK";
14 }
15
16 }
+0
-34
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/interceptor/resource/TestInterceptor.java less more
0 package org.jboss.resteasy.test.interceptor.resource;
1
2 import java.io.FilterOutputStream;
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.util.concurrent.atomic.AtomicInteger;
6
7 import javax.ws.rs.WebApplicationException;
8 import javax.ws.rs.ext.Provider;
9 import javax.ws.rs.ext.WriterInterceptor;
10 import javax.ws.rs.ext.WriterInterceptorContext;
11
12 @Provider
13 public class TestInterceptor implements WriterInterceptor
14 {
15 public static volatile AtomicInteger closeCounter = new AtomicInteger(0);
16
17 @Override
18 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
19 {
20 OutputStream outputStream = new FilterOutputStream(context.getOutputStream())
21 {
22 @Override
23 public void close() throws IOException
24 {
25 closeCounter.incrementAndGet();
26 super.close();
27 }
28 };
29 context.setOutputStream(outputStream);
30 context.proceed();
31 }
32
33 }
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.category.NotForForwardCompatibility;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
67 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
78 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
89 import org.jboss.resteasy.plugins.providers.atom.Content;
2324 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelUuid;
2425 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelVersionNumber;
2526 import org.jboss.resteasy.util.HttpResponseCodes;
27 import org.jboss.resteasy.utils.PermissionUtil;
2628 import org.jboss.resteasy.utils.PortProviderUtil;
2729 import org.jboss.resteasy.utils.TestUtil;
2830 import org.jboss.shrinkwrap.api.Archive;
29 import org.jboss.shrinkwrap.api.asset.StringAsset;
3031 import org.jboss.shrinkwrap.api.spec.WebArchive;
3132 import org.junit.After;
3233 import org.junit.Assert;
4142 import javax.xml.bind.JAXBContext;
4243 import javax.xml.bind.Marshaller;
4344 import javax.xml.bind.Unmarshaller;
44 import java.io.DataOutputStream;
45 import java.io.StringReader;
46 import java.io.StringWriter;
47 import java.io.Writer;
45 import java.io.*;
46 import java.lang.reflect.ReflectPermission;
4847 import java.net.HttpURLConnection;
4948 import java.net.URI;
5049 import java.net.URL;
8281 AtomComplexModelState.class,
8382 AtomComplexModelUuid.class,
8483 AtomComplexModelVersionNumber.class);
84
85 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
86 new RuntimePermission("getClassLoader"),
87 new FilePermission("<<ALL FILES>>", "read"),
88 new ReflectPermission("suppressAccessChecks"),
89 new RuntimePermission("accessDeclaredMembers")),
90 "permissions.xml");
91
8592 return TestUtil.finishContainerPrepare(war, null, AtomComplexModelEntryResource.class);
8693 }
8794
148155 }
149156
150157 /**
151 * @tpTestDetails Check new client
152 * @tpInfo Not for forward compatibility due to 3.1.0.Final, see the migration notes
158 * @tpTestDetails Check old client
153159 * @tpSince RESTEasy 3.0.16
154160 */
155161 @Test
156 @Category({NotForForwardCompatibility.class})
157 public void testNewClient() throws Exception {
162 public void testOldClient() throws Exception {
158163 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
159164 "<entry xmlns=\"http://www.w3.org/2005/Atom\">" +
160165 "<title>testCreatePackageFromAtom7</title>" +
184189 }
185190
186191 {
187 Response response = client.target(generateURL("/entry2")).request()
188 .header("Accept", MediaType.APPLICATION_ATOM_XML)
189 .header("Content-Type", MediaType.APPLICATION_ATOM_XML)
190 .get();
192 ClientRequest request = new ClientRequest(generateURL("/entry2"));
193 request.header("Accept", MediaType.APPLICATION_ATOM_XML);
194 request.header("Content-Type", MediaType.APPLICATION_ATOM_XML);
195 ClientResponse<Entry> response = request.get(Entry.class);
191196 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
192 assertNotNull("Wrong content of response", response.readEntity(Entry.class).getAnyOtherJAXBObject(AtomAssetMetadata.class));
193 response.close();
197
198 assertNotNull("Wrong content of response", response.getEntity().getAnyOtherJAXBObject(AtomAssetMetadata.class));
194199 }
195200
196201 {
215220 }
216221
217222 {
223 ClientRequest request = new ClientRequest(generateURL("/entry4"));
224 request.header("Accept", MediaType.APPLICATION_XML);
225 request.header("Content-Type", MediaType.APPLICATION_XML);
226 ClientResponse<Entry> response = request.get(Entry.class);
227 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
228 assertNotNull("Wrong content of response", response.getEntity().getAnyOtherJAXBObject(AtomAssetMetadata.class));
229 }
230 }
231
232 /**
233 * @tpTestDetails Check new client
234 * @tpSince RESTEasy 3.0.16
235 */
236 @Test
237 public void testNewClient() throws Exception {
238 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
239 "<entry xmlns=\"http://www.w3.org/2005/Atom\">" +
240 "<title>testCreatePackageFromAtom7</title>" +
241 "<summary>desc for testCreatePackageFromAtom</summary>" +
242 "<metadata xmlns=\"\"><categories><value>c1</value></categories> <note><value>meta</value> </note></metadata>" +
243 "</entry>";
244
245 {
246 URL url = new URL(generateURL("/entry"));
247 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
248 connection.setRequestMethod("POST");
249 connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
250 connection.setRequestProperty("Content-Type", MediaType.APPLICATION_ATOM_XML);
251 connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length));
252 connection.setUseCaches(false);
253 connection.setDoInput(true);
254 connection.setDoOutput(true);
255
256 //Send request
257 DataOutputStream wr = new DataOutputStream(
258 connection.getOutputStream());
259 wr.writeBytes(xml);
260 wr.flush();
261 wr.close();
262
263 assertEquals(HttpResponseCodes.SC_OK, connection.getResponseCode());
264 }
265
266 {
267 Response response = client.target(generateURL("/entry2")).request()
268 .header("Accept", MediaType.APPLICATION_ATOM_XML)
269 .header("Content-Type", MediaType.APPLICATION_ATOM_XML)
270 .get();
271 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
272 assertNotNull("Wrong content of response", response.readEntity(Entry.class).getAnyOtherJAXBObject(AtomAssetMetadata.class));
273 response.close();
274 }
275
276 {
277 URL url = new URL(generateURL("/entry3"));
278 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
279 connection.setRequestMethod("POST");
280 connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
281 connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML);
282 connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length));
283 connection.setUseCaches(false);
284 connection.setDoInput(true);
285 connection.setDoOutput(true);
286
287 //Send request
288 DataOutputStream wr = new DataOutputStream(
289 connection.getOutputStream());
290 wr.writeBytes(xml);
291 wr.flush();
292 wr.close();
293
294 assertEquals(HttpResponseCodes.SC_OK, connection.getResponseCode());
295 }
296
297 {
218298 Response response = client.target(generateURL("/entry4")).request()
219299 .header("Accept", MediaType.APPLICATION_XML)
220300 .header("Content-Type", MediaType.APPLICATION_XML)
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
57 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
68 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
79 import org.jboss.resteasy.plugins.providers.atom.Entry;
5759 }
5860
5961 /**
62 * @tpTestDetails Test old client
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void testAtomFeedOldClient() throws Exception {
67 ClientRequest request = new ClientRequest(generateURL("/atom/feed"));
68 ClientResponse<Feed> response = request.get(Feed.class);
69 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
70 Feed feed = response.getEntity();
71 Iterator<Entry> it = feed.getEntries().iterator();
72 Entry entry1 = it.next();
73 Entry entry2 = it.next();
74 Field field = Entry.class.getDeclaredField("finder");
75 field.setAccessible(true);
76 Assert.assertNotNull("First feet is not correct", field.get(entry1));
77 Assert.assertEquals("Second feet is not correct", field.get(entry1), field.get(entry2));
78 }
79
80 /**
6081 * @tpTestDetails Test new client
6182 * @tpSince RESTEasy 3.0.16
6283 */
00 package org.jboss.resteasy.test.providers.atom.resource;
11
2 import org.jboss.logging.Logger;
2 import org.jboss.resteasy.logging.Logger;
33 import org.jboss.resteasy.plugins.providers.atom.Entry;
4 import org.jboss.resteasy.spi.DecoratorProcessor;
4 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
55
66 import javax.ws.rs.core.MediaType;
77 import javax.xml.bind.JAXBContext;
2323 import java.io.FilePermission;
2424 import java.lang.reflect.ReflectPermission;
2525 import java.util.PropertyPermission;
26 import java.util.logging.LoggingPermission;
2627
2728 /**
2829 * @tpSubChapter Providers
4344 war.addClass(NotForForwardCompatibility.class);
4445 // Arquillian in the deployment, test reads the server.log
4546 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
46 new RuntimePermission("accessDeclaredMembers"),
47 new FilePermission(TestUtil.getJbossHome() + File.separator + "standalone" + File.separator + "log" +
48 File.separator + "server.log", "read"),
49 new LoggingPermission("control", ""),
4750 new PropertyPermission("arquillian.*", "read"),
4851 new PropertyPermission("jboss.home.dir", "read"),
49 new FilePermission(TestUtil.getJbossHome() + File.separator + "standalone" + File.separator + "log" +
50 File.separator + "server.log", "read")), "permissions.xml");
52 new RuntimePermission("accessDeclaredMembers")
53 ), "permissions.xml");
5154 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
5255 }
5356
33 import org.jboss.arquillian.container.test.api.OperateOnDeployment;
44 import org.jboss.arquillian.container.test.api.RunAsClient;
55 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.resteasy.client.ProxyFactory;
67 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
78 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
89 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterLowPriorityCustomerWriter;
11 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterHignPriorityCustomerWriter;
912 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterClient;
1013 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterCurlyBraces;
1114 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterCustomer;
2730
2831 import javax.ws.rs.client.WebTarget;
2932 import javax.ws.rs.core.Response;
33
3034 import java.net.HttpURLConnection;
3135 import java.net.URL;
3236
4044 @RunAsClient
4145 public class ReaderWriterTest {
4246 static ResteasyClient client;
43
47 static final String PriorityDeploymenetName = "ReaderWriterCustomerWriterWithPriority";
4448 @Deployment(name = "ReaderWriterCustomerWriter")
4549 public static Archive<?> deployCustomWriter() {
4650 WebArchive war = TestUtil.prepareArchive(ReaderWriterCustomerWriter.class.getSimpleName());
7074 war.addClass(PortProviderUtil.class);
7175 return TestUtil.finishContainerPrepare(war, null, ReaderWriterCurlyBraces.class);
7276 }
73
77
78 @Deployment(name = PriorityDeploymenetName)
79 public static Archive<?> deployCustomWriterWithPriority() {
80 WebArchive war = TestUtil.prepareArchive(PriorityDeploymenetName);
81 war.addClass(ReaderWriterCustomer.class);
82 war.addClass(PortProviderUtil.class);
83 return TestUtil.finishContainerPrepare(war, null, ReaderWriterLowPriorityCustomerWriter.class,
84 ReaderWriterCustomerWriter.class, ReaderWriterHignPriorityCustomerWriter.class, ReaderWriterResource.class);
85 }
7486
7587 @BeforeClass
7688 public static void init() {
152164 }
153165
154166 /**
167 * @tpTestDetails Test for resource mapped to nowhere using deprecated proxy.
168 * @tpSince RESTEasy 3.0.16
169 */
170 @Test
171 public void testItDeprecatedProxy() throws Exception {
172 ReaderWriterNowhereClient client = ProxyFactory.create(ReaderWriterNowhereClient.class, PortProviderUtil.generateBaseUrl("app"));
173 client.read();
174 }
175
176 /**
155177 * @tpTestDetails Test for resource mapped to nowhere using proxy.
156178 * @tpSince RESTEasy 3.0.16
157179 */
187209 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
188210 response.close();
189211 }
190
212
213 @Test
214 @OperateOnDeployment(PriorityDeploymenetName)
215 public void testProviderWithPriority() throws Exception {
216 WebTarget base = client.target(PortProviderUtil.generateURL("/priority", PriorityDeploymenetName));
217 Response response = base.request().get();
218 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
219 Assert.assertEquals("application/xml;charset=UTF-8", response.getStringHeaders().getFirst("content-type"));
220 String s = new String(response.readEntity(byte[].class), "UTF-8");
221 Assert.assertEquals("Response contains wrong content", "<customer><name>high priority</name></customer>", s);
222 response.close();
223 }
191224 }
1818
1919 import javax.ws.rs.core.Response;
2020 import java.lang.reflect.ReflectPermission;
21 import java.net.SocketPermission;
22 import java.security.SecurityPermission;
2123 import java.util.HashMap;
2224 import java.util.Map;
2325 import java.util.PropertyPermission;
26 import java.util.logging.LoggingPermission;
2427
2528 /**
2629 * @tpSubChapter Providers
4144 Map<String, String> contextParams = new HashMap<>();
4245 contextParams.put("resteasy.use.builtin.providers", "false");
4346 // Arquillian in the deployment
44 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
47 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
48 new LoggingPermission("control", ""),
49 new PropertyPermission("arquillian.*", "read"),
50 new PropertyPermission("ipv6", "read"),
51 new PropertyPermission("node", "read"),
52 new PropertyPermission("org.jboss.resteasy.port", "read"),
53 new ReflectPermission("suppressAccessChecks"),
4554 new RuntimePermission("accessDeclaredMembers"),
46 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
55 new RuntimePermission("getenv.RESTEASY_PORT"),
56 new SecurityPermission("insertProvider"),
57 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
58 ), "permissions.xml");
4759 return TestUtil.finishContainerPrepare(war, contextParams, WriterNotBuiltinTestWriter.class, ReaderWriterResource.class);
4860 }
4961
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import java.io.IOException;
3 import java.io.OutputStream;
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.Type;
6
7 import javax.annotation.Priority;
8 import javax.ws.rs.Priorities;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.WebApplicationException;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.MultivaluedMap;
13 import javax.ws.rs.ext.MessageBodyWriter;
14 import javax.ws.rs.ext.Provider;
15
16 @Provider
17 @Produces("application/xml")
18 @Priority(Priorities.USER - 100)
19 public class ReaderWriterHignPriorityCustomerWriter extends ReaderWriterCustomerWriter implements MessageBodyWriter<ReaderWriterCustomer>
20 {
21
22 @Override
23 public void writeTo(ReaderWriterCustomer customer, Class<?> type, Type genericType, Annotation[] annotations,
24 MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
25 throws IOException, WebApplicationException
26 {
27 String out = "<customer><name>high priority</name></customer>";
28 entityStream.write(out.getBytes());
29 }
30 }
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import java.io.IOException;
3 import java.io.OutputStream;
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.Type;
6
7 import javax.annotation.Priority;
8 import javax.ws.rs.Priorities;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.WebApplicationException;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.MultivaluedMap;
13 import javax.ws.rs.ext.MessageBodyWriter;
14 import javax.ws.rs.ext.Provider;
15
16 @Provider
17 @Produces("application/xml")
18 @Priority(Priorities.USER + 100)
19 public class ReaderWriterLowPriorityCustomerWriter extends ReaderWriterCustomerWriter implements MessageBodyWriter<ReaderWriterCustomer>
20 {
21 @Override
22 public void writeTo(ReaderWriterCustomer customer, Class<?> type, Type genericType, Annotation[] annotations,
23 MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
24 throws IOException, WebApplicationException
25 {
26 String out = "<customer><name>low priority</name></customer>";
27 entityStream.write(out.getBytes());
28 }
29 }
5959
6060 }
6161
62 @Path("/priority")
63 @GET
64 @Produces("application/xml")
65 public Object getCustomerWithProviderPriority() {
66 logger.info("Get customer with application packaged prioritized provider");
67 ReaderWriterCustomer cust = new ReaderWriterCustomer();
68 cust.setName("resteasy");
69 return Response.ok(cust).build();
70 }
71
6272 }
2323 import org.junit.Before;
2424 import org.junit.Test;
2525 import org.junit.runner.RunWith;
26
27 import javax.servlet.http.HttpServletResponse;
28 import javax.ws.rs.client.Entity;
29 import javax.ws.rs.core.MediaType;
30 import javax.ws.rs.core.Response;
31 import java.io.ByteArrayOutputStream;
2632 import java.io.File;
2733 import java.io.FilePermission;
2834 import java.io.FilenameFilter;
4046
4147 protected static final Logger logger = Logger.getLogger(CleanFilesDataSourceProviderTest.class.getName());
4248 static ResteasyClient client;
49 static String serverTmpDir;
4350
4451 @Deployment()
4552 public static Archive<?> deploy() {
4653 WebArchive war = TestUtil.prepareArchive(CleanFilesDataSourceProviderTest.class.getSimpleName());
4754 // DataSource provider creates tmp file in the filesystem
4855 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new FilePermission("/tmp/-", "read"),
49 new PropertyPermission("java.io.tmpdir", "read"),
5056 new FilePermission("/tmp", "read")), "permissions.xml");
5157 return TestUtil.finishContainerPrepare(war, null, CleanFilesDataSourceProviderResource.class);
5258 }
5460 @Before
5561 public void init() {
5662 client = new ResteasyClientBuilder().build();
63 serverTmpDir = getTmpDirectory();
5764 }
5865
5966 @After
6168 client.close();
6269 }
6370
64 private String generateURL(String path) {
71 private static String generateURL(String path) {
6572 return PortProviderUtil.generateURL(path, CleanFilesDataSourceProviderTest.class.getSimpleName());
6673 }
6774
7481 */
7582 @Test
7683 public void testDataSourceProviderInputStreamOnce() throws Exception {
77 // get directory for temporary files
78 File tmpdir = new File(System.getProperty("java.io.tmpdir"));
79 Assert.assertTrue("java.io.tmpdir does not exists", tmpdir.isDirectory());
80 logger.info("Tmp directory = " + tmpdir);
81
82 // Get count of rest easy temporary files
83 String[] tmpfiles = tmpdir.list(new FilenameFilter() {
84 public boolean accept(File dir, String name) {
85 return name.startsWith("resteasy-provider-datasource");
86 }
87 });
88 int countBefore = tmpfiles.length;
89 logger.info("Count of rest easy temporary files in " + tmpdir + " before request: " + countBefore);
84 // count temporary files before
85 int countBefore = countFiles(serverTmpDir);
86 logger.info("Count of Resteasy temporary files in " + serverTmpDir + " before request: " + countBefore);
9087
9188 // http request
9289 HttpClient httpClient = HttpClients.custom().build();
10097 Assert.assertEquals("Status of client request is not correct.", HttpStatus.SC_OK, postStatus);
10198 Assert.assertEquals("Client get wrong response.", CleanFilesDataSourceProviderResource.clientResponse, postResponse);
10299
103 // Get count of rest easy temporary files again
104 tmpfiles = tmpdir.list(new FilenameFilter() {
105 public boolean accept(File dir, String name) {
106 return name.startsWith("resteasy-provider-datasource");
107 }
108 });
109 int countAfter = tmpfiles.length;
110 logger.info("Count of rest easy temporary files in " + tmpdir + " after request: " + countAfter);
100 // count temporary files after
101 int countAfter = countFiles(serverTmpDir);
102 logger.info("Count of Resteasy temporary files in " + serverTmpDir + " after request: " + countAfter);
111103
112104 // Compare
113105 Assert.assertEquals("Client request remove or add some temporary files.", countBefore, countAfter);
122114 */
123115 @Test
124116 public void testDataSourceProviderInputStreamTwice() throws Exception {
125 // get directory for temporary files
126 File tmpdir = new File(System.getProperty("java.io.tmpdir"));
127 Assert.assertTrue("java.io.tmpdir does not exists", tmpdir.isDirectory());
128 logger.info("Tmp directory = " + tmpdir);
129
130 // Get count of rest easy temporary files
131 String[] tmpfiles = tmpdir.list(new FilenameFilter() {
132 public boolean accept(File dir, String name) {
133 return name.startsWith("resteasy-provider-datasource");
134 }
135 });
136 int countBefore = tmpfiles.length;
137 logger.info("Count of rest easy temporary files in " + tmpdir + " before request: " + countBefore);
117 // count temporary files before
118 int countBefore = countFiles(serverTmpDir);
119 logger.info("Count of Resteasy temporary files in " + serverTmpDir + " before request: " + countBefore);
138120
139121 // http request
140122 HttpClient httpClient = HttpClients.custom().build();
148130 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-1904", "Status of client request is not correct."), HttpStatus.SC_OK, postStatus);
149131 Assert.assertEquals("Client get wrong response.", CleanFilesDataSourceProviderResource.clientResponse, postResponse);
150132
151 // Get count of rest easy temporary files again
152 tmpfiles = tmpdir.list(new FilenameFilter() {
133 // count temporary files after
134 int countAfter = countFiles(serverTmpDir);
135 logger.info("Count of Resteasy temporary files in " + serverTmpDir + " after request: " + countAfter);
136
137 // Compare
138 Assert.assertEquals("Client request remove or add some temporary files.", countBefore, countAfter);
139 }
140
141 /**
142 * @tpTestDetails Tests that DataSourceProvider removes temporary file it creates in the case when input stream is not read.
143 * @tpInfo RESTEASY-1670
144 * @tpSince RESTEasy 3.0.24
145 */
146 @Test
147 public void testDataSourceProviderInputStreamNotRead() throws Exception {
148 // count temporary files before
149 int countBefore = countFiles(serverTmpDir);
150 logger.info("Count of Resteasy temporary files in " + serverTmpDir + " before request: " + countBefore);
151
152 ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
153 for (int i = 0; i < 5000; i++) {
154 baos.write(i);
155 }
156 Response response = client.target(generateURL("/never")).request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM));
157 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
158
159 // count temporary files after
160 int countAfter = countFiles(serverTmpDir);
161 logger.info("Count of Resteasy temporary files in " + serverTmpDir + " after request: " + countAfter);
162
163 // Compare
164 Assert.assertEquals("Client request removed or added some temporary files.", countBefore, countAfter);
165 }
166
167 private static String getTmpDirectory() {
168 Response response = client.target(generateURL("/tmpdirpath")).request().get();
169 return response.readEntity(String.class);
170 }
171
172 private int countFiles(String dir) {
173 File tmpdir = new File(dir);
174 Assert.assertTrue(dir + " does not exists", tmpdir.isDirectory());
175 logger.info("Tmp directory = " + tmpdir);
176
177 // Get count of Resteasy temporary files
178 String[] tmpfiles = tmpdir.list(new FilenameFilter() {
153179 public boolean accept(File dir, String name) {
154180 return name.startsWith("resteasy-provider-datasource");
155181 }
156182 });
157 int countAfter = tmpfiles.length;
158 logger.info("Count of rest easy temporary files in " + tmpdir + " after request: " + countAfter);
159
160 // Compare
161 Assert.assertEquals("Client request remove or add some temporary files.", countBefore, countAfter);
183 return tmpfiles.length;
162184 }
163185 }
77 import java.nio.file.Paths;
88 import java.util.PropertyPermission;
99 import java.util.concurrent.atomic.AtomicInteger;
10
1011 import javax.ws.rs.client.Entity;
1112 import javax.ws.rs.client.WebTarget;
1213 import javax.ws.rs.core.MediaType;
138139 Path dir = Paths.get(tmpdir);
139140 final AtomicInteger counter = new AtomicInteger(0);
140141 try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "resteasy-provider-datasource*")){
141 stream.forEach(path -> counter.incrementAndGet());
142 for (Path path : stream) {
143 counter.incrementAndGet();
144 }
142145 }
143146 return counter.intValue();
144147 }
148151 String tmpdir = System.getProperty("java.io.tmpdir");
149152 Path dir = Paths.get(tmpdir);
150153 try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "resteasy-provider-datasource*")) {
151 stream.forEach(path -> logger.info(path.toString()));
154 for (Path path : stream) {
155 logger.info(path.toString());
156 }
152157 }
153158 }
154159 }
00 package org.jboss.resteasy.test.providers.datasource.resource;
11
22 import javax.activation.DataSource;
3 import javax.ws.rs.GET;
34 import javax.ws.rs.POST;
45 import javax.ws.rs.Path;
56 import javax.ws.rs.Produces;
910 public class CleanFilesDataSourceProviderResource {
1011
1112 public static String clientResponse = "response_from_client";
13
14 @GET
15 @Path("/tmpdirpath")
16 @Produces("text/plain")
17 public String get() {
18 return System.getProperty("java.io.tmpdir");
19 }
1220
1321 @POST
1422 @Path("once")
3341 is2.close();
3442 return clientResponse;
3543 }
44
45 @POST
46 @Path("never")
47 @Produces("text/plain")
48 public String postDataSource(DataSource datasource) {
49 return datasource.getContentType();
50 }
51
3652 }
2525 /**
2626 * @tpSubChapter File provider
2727 * @tpChapter Integration tests
28 * @tpSince RESTEasy 3.1.3.Final
28 * @tpSince RESTEasy 3.0.23.Final
2929 */
3030 @RunWith(Arquillian.class)
3131 @RunAsClient
4141 * @tpTestDetails Resource method contains parameter of the type File. This triggers File provider, which creates
4242 * temporary file on the server side, which is automatically deleted in the end of the resource method invocation.
4343 * @tpInfo Regression test for RESTEASY-1464
44 * @tpSince RESTEasy 3.1.3.Final
44 * @tpSince RESTEasy 3.0.23.Final
4545 */
4646 @Test
4747 @Category(NotForForwardCompatibility.class)
1212 import org.junit.After;
1313 import org.junit.Assert;
1414 import org.junit.Before;
15 import org.junit.Ignore;
1516 import org.junit.Test;
1617 import org.junit.runner.RunWith;
1718
6869 * @tpSince RESTEasy 3.0.16
6970 */
7071 @Test
72 @Ignore("[RESTEASY-1724] java.lang.IllegalStateException: Compression mode not MODE_EXPLICIT!")
7173 public void testPostJPEGIMage() throws Exception {
7274 File file = new File(TestUtil.getResourcePath(IIOImageProviderTest.class, testPngResource));
7375 Assert.assertTrue(file.exists());
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
57 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
68 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
79 import org.jboss.resteasy.test.providers.inputstream.resource.InputStreamCloseInputStream;
5355 }
5456
5557 /**
58 * @tpTestDetails Old client test
59 * @tpSince RESTEasy 3.0.16
60 */
61 @Test
62 public void oldClient() throws Exception {
63 // Resource creates and returns InputStream.
64 ClientRequest request = new ClientRequest(generateURL("/create/"));
65 ClientResponse<?> response = request.get(String.class);
66 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
67 Assert.assertEquals("hello", response.getEntity());
68
69 // Verify previously created InputStream has been closed.
70 request = new ClientRequest(generateURL("/test/"));
71 response = request.get();
72 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
73 }
74
75 /**
5676 * @tpTestDetails New client test
5777 * @tpSince RESTEasy 3.0.16
5878 */
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
55 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
7 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
68 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
79 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
810 import org.jboss.resteasy.test.providers.jackson.resource.ProxyWithGenericReturnTypeJacksonAbstractParent;
7880 Assert.assertTrue("Type property is missing.", response.readEntity(String.class).contains("type"));
7981 response.close();
8082 }
83
84 /**
85 * @tpTestDetails Test old client
86 * @tpSince RESTEasy 3.0.16
87 */
88 @Test
89 public void testOldClient() throws Exception {
90 ClientRequest request = new ClientRequest(generateURL("/test/one/"));
91 ClientResponse<String> response = request.get(String.class);
92 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
93 Assert.assertTrue("Type property is missing.", response.getEntity(String.class).contains("type"));
94 response.releaseConnection();
95
96 request = new ClientRequest(generateURL("/test/list/"));
97 response = request.get(String.class);
98 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
99 Assert.assertTrue("Type property is missing.", response.getEntity(String.class).contains("type"));
100 response.releaseConnection();
101 }
81102 }
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.category.Jaxrs21;
56 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
67 import org.jboss.resteasy.test.providers.jackson2.resource.CustomJackson2ProviderResource;
78 import org.jboss.resteasy.test.providers.jackson2.resource.CustomJackson2ProviderApplication;
1516 import org.junit.Assert;
1617 import org.junit.Before;
1718 import org.junit.Test;
19 import org.junit.experimental.categories.Category;
1820 import org.junit.runner.RunWith;
1921
2022 import javax.ws.rs.client.Client;
3234 */
3335 @RunWith(Arquillian.class)
3436 @RunAsClient
37 // Because it loads project.version of RESTEasy not the *jaxrs20 version
38 @Category(Jaxrs21.class)
3539 public class CustomJackson2ProviderTest {
3640
3741 private static Client client;
188188 * trigger processing of the response in the format callbackvalue("key":"value"). However, Jackson2JsonpInterceptor is disabled.
189189 * @tpPassCrit The resource returns json entities in correct format (without callback function wrapping)
190190 * @tpInfo RESTEASY-1486
191 * @tpSince RESTEasy 3.1.0.Final
191 * @tpSince RESTEasy 3.0.20.Final
192192 */
193193 @Test
194194 @Category({NotForForwardCompatibility.class})
8787 * @tpTestDetails Tests Jackson JsonView with jaxr-rs
8888 * @tpPassCrit The response entity contains correctly serialized values. Jax-rs resource doesn't contain JsonView annotation
8989 * @tpInfo RESTEASY-1366, JBEAP-5435
90 * @tpSince RESTEasy 3.1.0
90 * @tpSince RESTEasy 3.0.19
9191 */
9292 @Test
9393 @Category({NotForForwardCompatibility.class})
2525 * @tpChapter Integration tests
2626 * @tpTestCaseDetails Filters fields from json object. Specifies the filter implementation class in web.xml.
2727 * JsonFilterParent defines the @JsonFilter annotation. JsonFilter applies to its subclass JsonFilterChild as well.
28 * @tpSince RESTEasy 3.1.0
28 * @tpInfo RESTEASY-1442
29 * @tpSince RESTEasy 3.0.20.Final
2930 */
3031 @RunWith(Arquillian.class)
3132 @RunAsClient
3030 * @tpTestCaseDetails Filters fields from json object. Sets ObjectWriterModifier in the interceptor.
3131 * The filter filters field of Jackson2Product pojo upon value if its 'id' field. Pojo with id value < 0 is filtered
3232 * out and not returned in the response. See http://www.baeldung.com/jackson-serialize-field-custom-criteria
33 * @tpSince RESTEasy 3.1.0
33 * @tpInfo RESTESY-1442
34 * @tpSince RESTEasy 3.0.20.Final
3435 */
3536 @RunWith(Arquillian.class)
3637 @RunAsClient
6364
6465 /**
6566 * @tpTestDetails Json field id is filtered out
66 * @tpSince RESTEasy 3.1.0
67 * @tpSince RESTEasy 3.0.20.Final
6768 */
6869 @Test
6970 public void testJacksonConditionalStringPropertyFiltered() throws Exception {
7677
7778 /**
7879 * @tpTestDetails Json field id is not filtered
79 * @tpSince RESTEasy 3.1.0
80 * @tpSince RESTEasy 3.0.20.Final
8081 */
8182 @Test
8283 public void testJacksonConditionalStringPropertyNotFiltered() throws Exception {
2929 * @tpTestCaseDetails Filters fields from json object. Sets ObjectWriterModifier in the interceptor.
3030 * The filter filters field personType of Jackson2Person pojo. The ObjectWriterModifier has multiple filters registered.
3131 * Only one is set to for Json2Person pojo.
32 * @tpSince RESTEasy 3.1.0
32 * @tpInfo RESTESY-1442
33 * @tpSince RESTEasy 3.0.20.Final
3334 */
3435 @RunWith(Arquillian.class)
3536 @RunAsClient
5051
5152 /**
5253 * @tpTestDetails Correct filter is used when multiple filters available
53 * @tpSince RESTEasy 3.1.0
54 * @tpSince RESTEasy 3.0.20.Final
5455 */
5556 @Test
5657 public void testJacksonString2() throws Exception {
2626 * @author <a href="mailto:ema@redhat.com">Jim Ma</a>
2727 * @tpSubChapter Jackson2 provider
2828 * @tpChapter Integration tests
29 * @tpSince RESTEasy 3.1.0
29 * @tpInfo RESTESY-1442
30 * @tpSince RESTEasy 3.0.20.Final
3031 */
3132 @RunWith(Arquillian.class)
3233 @RunAsClient
4748
4849 /**
4950 * @tpTestDetails Filters fields from json response entity using interceptor
50 * @tpSince RESTEasy 3.1.0
51 * @tpSince RESTEasy 3.0.20.Final
5152 */
5253 @Test
5354 public void testJacksonString() throws Exception {
2626 * @author <a href="mailto:ema@redhat.com">Jim Ma</a>
2727 * @tpSubChapter Jackson2 provider
2828 * @tpChapter Integration tests
29 * @tpSince RESTEasy 3.1.0
29 * @tpInfo RESTESY-1442
30 * @tpSince RESTEasy 3.0.20.Final
3031 */
3132 @RunWith(Arquillian.class)
3233 @RunAsClient
4849
4950 /**
5051 * @tpTestDetails Filters fields from json response entity. Specifies the filter implementation class in web.xml.
51 * @tpSince RESTEasy 3.1.0
52 * @tpSince RESTEasy 3.0.20.Final
5253 */
5354 @Test
5455 public void testJacksonString() throws Exception {
2727 * @tpTestCaseDetails Filters fields from json object. Specifies the filter implementation class in web.xml.
2828 * The filter filters field of Jackson2Product pojo upon value if its 'id' field. Pojo with id value < 0 is filtered
2929 * out and not returned in the response. See http://www.baeldung.com/jackson-serialize-field-custom-criteria
30 * @tpSince RESTEasy 3.1.0
30 * @tpInfo RESTESY-1442
31 * @tpSince RESTEasy 3.0.20.Final
3132 */
3233 @RunWith(Arquillian.class)
3334 @RunAsClient
6162
6263 /**
6364 * @tpTestDetails Json field id is filtered out
64 * @tpSince RESTEasy 3.1.0
65 * @tpSince RESTEasy 3.0.20.Final
6566 */
6667 @Test
6768 public void testJacksonConditionalStringPropertyFiltered() throws Exception {
7475
7576 /**
7677 * @tpTestDetails Json field id is not filtered
77 * @tpSince RESTEasy 3.1.0
78 * @tpSince RESTEasy 3.0.20.Final
7879 */
7980 @Test
8081 public void testJacksonConditionalStringPropertyNotFiltered() throws Exception {
2525 * @tpTestCaseDetails Filters fields from json object. Specifies the filter implementation class in web.xml.
2626 * The filter filters field personType of Jackson2Person pojo. The ObjectWriterModifier has multiple filters registered.
2727 * Only one is set to for Json2Person pojo.
28 * @tpSince RESTEasy 3.1.0
28 * @tpInfo RESTESY-1442
29 * @tpSince RESTEasy 3.0.20.Final
2930 */
3031 @RunWith(Arquillian.class)
3132 @RunAsClient
4647
4748 /**
4849 * @tpTestDetails Correct filter is used when multiple filters available
49 * @tpSince RESTEasy 3.1.0
50 * @tpSince RESTEasy 3.0.20.Final
5051 */
5152 @Test
5253 public void testJacksonString() throws Exception {
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.providers.jaxb.resource.HomecontrolCustomJAXBContext;
9 import org.jboss.resteasy.test.providers.jaxb.resource.HomecontrolApplication;
10 import org.jboss.resteasy.test.providers.jaxb.resource.HomecontrolService;
11 import org.jboss.resteasy.test.providers.jaxb.resource.HomecontrolJaxbProvider;
12 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.Base64Binary;
13 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.BinaryType;
14 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.ErrorDomainType;
15 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.ErrorMessageType;
16 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.IDType;
17 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.ObjectFactory;
18 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.ErrorType;
19 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.RoleType;
20 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.UserType;
21 import org.jboss.resteasy.utils.PortProviderUtil;
22 import org.jboss.resteasy.utils.TestUtil;
23 import org.jboss.shrinkwrap.api.Archive;
24 import org.jboss.shrinkwrap.api.spec.WebArchive;
25 import org.junit.After;
26 import org.junit.Assert;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30
31 import javax.ws.rs.client.Entity;
32 import javax.ws.rs.core.Response;
33
34 /**
35 * @tpSubChapter Jaxb provider
36 * @tpChapter Integration tests
37 * @tpSince RESTEasy 3.5
38 */
39 @RunWith(Arquillian.class)
40 @RunAsClient
41 public class HomecontrolCustomJAXBContextTest {
42
43 static ResteasyClient client;
44
45 @Deployment
46 public static Archive<?> deploy() {
47 WebArchive war = TestUtil.prepareArchive(HomecontrolCustomJAXBContextTest.class.getSimpleName());
48 war.addClasses(HomecontrolCustomJAXBContext.class,
49 HomecontrolApplication.class,
50 HomecontrolService.class,
51 HomecontrolJaxbProvider.class,
52 ObjectFactory.class,
53 ErrorDomainType.class,
54 BinaryType.class,
55 ErrorType.class,
56 Base64Binary.class,
57 RoleType.class,
58 UserType.class,
59 IDType.class,
60 ErrorMessageType.class
61 );
62 war.addAsWebInfResource(HomecontrolCustomJAXBContextTest.class.getPackage(), "homecontrol/web.xml");
63 return TestUtil.finishContainerPrepare(war, null, HomecontrolCustomJAXBContextTest.class);
64 }
65
66 @Before
67 public void init() {
68 client = new ResteasyClientBuilder().build();
69 }
70
71 @After
72 public void after() throws Exception {
73 client.close();
74 }
75
76 private String generateURL(String path) {
77 return PortProviderUtil.generateURL(path, HomecontrolCustomJAXBContextTest.class.getSimpleName());
78 }
79
80 /**
81 * @tpTestDetails Test that a user provided JAXBContext implementation is use.
82 * @tpInfo RESTEASY-1754
83 * @tpSince RESTEasy 3.5
84 */
85 @Test
86 public void testMarshallering() throws Exception {
87
88 String xmlStr = "<user xmlns=\"http://creaity.de/homecontrol/rest/types/v1\"> <id>id</id>"
89 + " <credentials> <loginId>test</loginId> </credentials>"
90 + " <roles><role>USER</role></roles></user>";
91
92 ResteasyWebTarget target = client.target(generateURL("/service/users"));
93 Response response = target.request().accept("application/xml").post(Entity.xml(xmlStr));
94 UserType entity = response.readEntity(UserType.class);
95 Assert.assertNotNull(entity);
96 Assert.assertTrue("id DemoService_visited".equals(entity.getId()));
97 response.close();
98 }
99 }
3838 WebArchive war = TestUtil.prepareArchive(JaxbCacheTest.class.getSimpleName());
3939 war.addClass(JaxbCacheTest.class);
4040 // Arquillian in the deployment
41 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
42 new RuntimePermission("accessDeclaredMembers"),
43 new PropertyPermission("*", "read")), "permissions.xml");
41 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
42 new ReflectPermission("suppressAccessChecks"),
43 new RuntimePermission("accessDeclaredMembers"),
44 new PropertyPermission("*", "read")),
45 "permissions.xml");
46
4447 return TestUtil.finishContainerPrepare(war, null, JaxbCacheParent.class, JaxbCacheChild.class);
4548 }
4649
2626 import javax.xml.bind.JAXBException;
2727 import java.io.ByteArrayInputStream;
2828 import java.lang.reflect.ReflectPermission;
29 import java.net.SocketPermission;
30 import java.security.AccessController;
31 import java.security.PrivilegedAction;
2932 import java.util.HashMap;
3033 import java.util.Map;
3134 import java.util.PropertyPermission;
3437 import java.util.concurrent.Executors;
3538 import java.util.concurrent.TimeUnit;
3639 import java.util.concurrent.atomic.AtomicInteger;
40 import java.util.logging.LoggingPermission;
3741
3842 /**
3943 * @tpSubChapter Jaxb provider
7680 contextParam.put("resteasy.async.job.service.enabled", "true");
7781 // Arquillian in the deployment use if TimeoutUtil in the deployment
7882 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
83 new LoggingPermission("control", ""),
84 new PropertyPermission("arquillian.*", "read"),
85 new PropertyPermission("ipv6", "read"),
86 new PropertyPermission("node", "read"),
87 new PropertyPermission("org.jboss.resteasy.port", "read"),
88 new PropertyPermission("ts.timeout.factor", "read"),
7989 new RuntimePermission("accessDeclaredMembers"),
80 new PropertyPermission("arquillian.*", "read"),
81 new PropertyPermission("ts.timeout.factor", "read")), "permissions.xml");
90 new RuntimePermission("getClassLoader"),
91 new RuntimePermission("getenv.RESTEASY_PORT"),
92 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
93 ), "permissions.xml");
8294 return TestUtil.finishContainerPrepare(war, contextParam, JaxbMarshallingSoakAsyncService.class);
8395 }
8496
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
55 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
7 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
68 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
79 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
810 import org.jboss.resteasy.test.providers.jaxb.resource.StreamResetPlace;
103105 }
104106 }
105107
108 /**
109 * @tpTestDetails Tests streamReset method of deprecated ClientResponse class. In case exception is thrown during processing
110 * response from the server, the stream of the response must be reset before reading it again.
111 * @tpPassCrit After exception is thrown the response is parsed correctly with getEntity()
112 * @tpInfo RESTEASY-456
113 * @tpSince RESTEasy 3.0.16
114 */
115 @Test
116 public void testClientRequestResetStream() throws Exception {
117 ClientRequest request = new ClientRequest(generateURL("/test"));
118 ClientResponse<StreamResetPlace> response = request.get(StreamResetPlace.class);
119 boolean exceptionThrown = false;
120 try {
121 StreamResetPlace place = response.getEntity();
122
123 } catch (Exception e) {
124 exceptionThrown = true;
125 }
126 Assert.assertTrue("The expected exception didn't happen", exceptionThrown);
127
128 response.resetStream();
129 StreamResetPerson person = response.getEntity(StreamResetPerson.class);
130 Assert.assertNotNull("The stream was not correctly reset", person);
131 Assert.assertEquals("The response from the server is not the one expected", "bill", person.getName());
132 }
133
106134 }
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
55 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.category.NotForForwardCompatibility;
76 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
87 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
98 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
1615 import org.jboss.resteasy.utils.PortProviderUtil;
1716 import org.jboss.resteasy.utils.TestUtil;
1817 import org.jboss.shrinkwrap.api.Archive;
19 import org.jboss.shrinkwrap.api.asset.StringAsset;
2018 import org.jboss.shrinkwrap.api.spec.WebArchive;
2119 import org.junit.After;
2220 import org.junit.Assert;
3230 */
3331 @RunWith(Arquillian.class)
3432 @RunAsClient
35 @Category({NotForForwardCompatibility.class})
3633 public class XmlHeaderTest {
3734
3835 private final Logger logger = Logger.getLogger(XmlHeaderTest.class.getName());
1919 import org.jboss.arquillian.container.test.api.Deployment;
2020 import org.jboss.arquillian.container.test.api.RunAsClient;
2121 import org.jboss.arquillian.junit.Arquillian;
22 import org.jboss.resteasy.utils.PermissionUtil;
2223 import org.jboss.resteasy.utils.PortProviderUtil;
2324 import org.jboss.resteasy.utils.TestUtil;
2425 import org.jboss.shrinkwrap.api.Archive;
2627 import org.junit.Assert;
2728 import org.junit.Test;
2829 import org.junit.runner.RunWith;
30
31 import java.io.FilePermission;
32 import java.lang.reflect.ReflectPermission;
33 import java.util.PropertyPermission;
2934
3035 /**
3136 * @tpSubChapter Jaxb provider
3944 @Deployment
4045 public static Archive<?> deploy() {
4146 WebArchive war = TestUtil.prepareArchive(XmlJAXBContextFinderTest.class.getSimpleName());
47
48 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
49 new RuntimePermission("getClassLoader"),
50 new FilePermission("<<ALL FILES>>", "read"),
51 new ReflectPermission("suppressAccessChecks"),
52 new RuntimePermission("accessDeclaredMembers")), "permissions.xml");
53
4254 return TestUtil.finishContainerPrepare(war, null, BeanWrapper.class,
4355 FirstBean.class, SecondBean.class,
4456 FirstTestResource.class, SecondTestResource.class,
00 package org.jboss.resteasy.test.providers.jaxb;
11
22 import java.lang.reflect.ReflectPermission;
3 import java.net.SocketPermission;
34 import java.util.*;
5 import java.util.logging.LoggingPermission;
46
57 import javax.ws.rs.client.Entity;
68 import javax.ws.rs.core.GenericEntity;
4749 war.addClass(XmlJavaTypeAdapterTest.class);
4850 // Arquillian in the deployment and use of PortProviderUtil in the deployment
4951 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new PropertyPermission("node", "read"),
52 new LoggingPermission("control", ""),
53 new PropertyPermission("arquillian.*", "read"),
5054 new PropertyPermission("ipv6", "read"),
51 new RuntimePermission("getenv.RESTEASY_PORT"),
5255 new PropertyPermission("org.jboss.resteasy.port", "read"),
5356 new ReflectPermission("suppressAccessChecks"),
5457 new RuntimePermission("accessDeclaredMembers"),
55 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
58 new RuntimePermission("getenv.RESTEASY_PORT"),
59 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
60 ), "permissions.xml");
5661 return TestUtil.finishContainerPrepare(war, null, XmlJavaTypeAdapterAlien.class, XmlJavaTypeAdapterAlienAdapter.class,
5762 XmlJavaTypeAdapterFoo.class, XmlJavaTypeAdapterHuman.class, XmlJavaTypeAdapterResource.class, PortProviderUtil.class);
5863 }
55 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
66 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
77 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.logging.Logger;
89 import org.jboss.resteasy.test.providers.jaxb.resource.Order;
910 import org.jboss.resteasy.test.providers.jaxb.resource.Ordertype;
1011 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJaxbProvidersOrderClient;
1718 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJaxbProvidersHelper;
1819 import org.jboss.resteasy.test.providers.jaxb.resource.XmlStreamFactory;
1920 import org.jboss.resteasy.util.HttpResponseCodes;
21 import org.jboss.resteasy.utils.PermissionUtil;
2022 import org.jboss.resteasy.utils.PortProviderUtil;
2123 import org.jboss.resteasy.utils.TestUtil;
2224 import org.jboss.shrinkwrap.api.Archive;
3234 import javax.xml.bind.JAXBContext;
3335 import javax.xml.bind.Unmarshaller;
3436 import java.io.File;
37 import java.io.FilePermission;
3538 import java.io.InputStream;
39 import java.lang.reflect.ReflectPermission;
3640
3741 /**
3842 * @tpSubChapter Jaxb provider
4347 @RunAsClient
4448 public class XmlJaxbProvidersTest {
4549
50 private static final Logger logger = Logger.getLogger(XmlJaxbProvidersTest.class);
4651 private XmlJaxbProvidersOrderClient proxy;
4752 static ResteasyClient client;
4853
5560 war.addClass(XmlJaxbProvidersTest.class);
5661 war.addAsResource(XmlJaxbProvidersTest.class.getPackage(), "orders/order_123.xml");
5762 war.as(ZipExporter.class).exportTo(new File("target", XmlJaxbProvidersTest.class.getSimpleName() + ".war"), true);
63
64 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
65 new FilePermission("<<ALL FILES>>", "read"),
66 new RuntimePermission("accessDeclaredMembers"),
67 new ReflectPermission("suppressAccessChecks"),
68 new RuntimePermission("getClassLoader")),
69 "permissions.xml");
70
5871 return TestUtil.finishContainerPrepare(war, null, XmlJaxbProvidersOrderResource.class, Order.class, Ordertype.class,
5972 ShipTo.class, Shiptotype.class, Item.class, Itemtype.class, JAXBCache.class, XmlJaxbProvidersHelper.class, XmlStreamFactory.class);
6073 }
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4 import java.util.HashSet;
5 import java.util.Set;
6
7 @ApplicationPath("/service")
8 public class HomecontrolApplication extends Application {
9
10
11 @Override
12 public Set<Class<?>> getClasses() {
13
14 Set<Class<?>> result = new HashSet<Class<?>>();
15 result.add(HomecontrolService.class);
16 return result;
17 }
18
19 @Override
20 public Set<Object> getSingletons() {
21 Set<Object> result = new HashSet<>();
22 result.add(new HomecontrolJaxbProvider());
23 return result;
24 }
25 }
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.*;
3
4 public class HomecontrolCustomJAXBContext extends JAXBContext {
5
6 private JAXBContext delegate;
7
8 public HomecontrolCustomJAXBContext(Class<?> type) {
9 try {
10 this.delegate = JAXBContext.newInstance(type.getPackage().getName());
11 } catch (JAXBException e) {
12 throw new IllegalStateException("Error creating JAXBContext", e);
13 }
14 }
15
16 @Override
17 public Unmarshaller createUnmarshaller() throws JAXBException {
18 System.out.println("Creating unmarshaller");
19 return this.delegate.createUnmarshaller();
20 }
21
22 @Override
23 public Marshaller createMarshaller() throws JAXBException {
24 System.out.println("Creating marshaller");
25 return this.delegate.createMarshaller();
26 }
27
28 @Override
29 public Validator createValidator() throws JAXBException {
30 return this.delegate.createValidator();
31 }
32 }
33
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.Produces;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.ext.ContextResolver;
6 import javax.ws.rs.ext.Provider;
7 import javax.xml.bind.JAXBContext;
8
9 @Provider
10 @Produces(MediaType.APPLICATION_XML)
11 @Consumes(MediaType.APPLICATION_XML)
12 public class HomecontrolJaxbProvider implements ContextResolver<JAXBContext> {
13
14 @Override
15 public JAXBContext getContext(Class<?> type) {
16 return new HomecontrolCustomJAXBContext(type);
17 }
18 }
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.ObjectFactory;
3 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.UserType;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.Response;
12 import javax.ws.rs.ext.Provider;
13 import javax.xml.bind.JAXBElement;
14
15 @Provider
16 @Path("users")
17 @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
18 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
19 public class HomecontrolService {
20
21 @POST
22 public JAXBElement<UserType> demo(UserType type) {
23 type.setId(type.getId() + " DemoService_visited");
24 return new ObjectFactory().createUser(type);
25 }
26
27 @GET
28 public Response get () {
29 return Response.ok().build();
30 }
31 }
00 package org.jboss.resteasy.test.providers.jaxb.resource;
11
2 import org.jboss.resteasy.core.ExceptionAdapter;
23 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.core.ExceptionAdapter;
44
55 import javax.xml.bind.JAXBContext;
66 import javax.xml.bind.JAXBException;
00 package org.jboss.resteasy.test.providers.jaxb.resource;
11
22 import org.jboss.resteasy.annotations.DecorateTypes;
3 import org.jboss.resteasy.spi.DecoratorProcessor;
3 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
44
55 import javax.ws.rs.core.MediaType;
66 import javax.xml.bind.Marshaller;
00 package org.jboss.resteasy.test.providers.jaxb.resource;
11
22 import org.jboss.resteasy.annotations.DecorateTypes;
3 import org.jboss.resteasy.spi.DecoratorProcessor;
3 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
44 import org.junit.Assert;
55
66 import javax.ws.rs.core.MediaType;
0 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
1
2 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.BinaryType;
3
4 import javax.xml.bind.annotation.*;
5
6
7 /**
8 * <p>Java-Klasse für base64Binary complex type.
9 *
10 * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
11 *
12 * <pre>
13 * &lt;complexType name="base64Binary"&gt;
14 * &lt;simpleContent&gt;
15 * &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema&gt;base64Binary"&gt;
16 * &lt;attribute ref="{http://www.w3.org/2005/05/xmlmime}contentType"/&gt;
17 * &lt;/extension&gt;
18 * &lt;/simpleContent&gt;
19 * &lt;/complexType&gt;
20 * </pre>
21 *
22 *
23 */
24 @XmlAccessorType(XmlAccessType.FIELD)
25 @XmlType(name = "base64Binary", propOrder = {
26 "value"
27 })
28 @XmlSeeAlso({
29 BinaryType.class
30 })
31 public class Base64Binary {
32
33 @XmlValue
34 protected byte[] value;
35 @XmlAttribute(name = "contentType", namespace = "http://www.w3.org/2005/05/xmlmime")
36 protected String contentType;
37
38 /**
39 * Ruft den Wert der value-Eigenschaft ab.
40 *
41 * @return
42 * possible object is
43 * byte[]
44 */
45 public byte[] getValue() {
46 return value;
47 }
48
49 /**
50 * Legt den Wert der value-Eigenschaft fest.
51 *
52 * @param value
53 * allowed object is
54 * byte[]
55 */
56 public void setValue(byte[] value) {
57 this.value = value;
58 }
59
60 /**
61 * Ruft den Wert der contentType-Eigenschaft ab.
62 *
63 * @return
64 * possible object is
65 * {@link String }
66 *
67 */
68 public String getContentType() {
69 return contentType;
70 }
71
72 /**
73 * Legt den Wert der contentType-Eigenschaft fest.
74 *
75 * @param value
76 * allowed object is
77 * {@link String }
78 *
79 */
80 public void setContentType(String value) {
81 this.contentType = value;
82 }
83
84 }
0 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
1
2
3 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.Base64Binary;
4
5 import javax.xml.bind.annotation.XmlAccessType;
6 import javax.xml.bind.annotation.XmlAccessorType;
7 import javax.xml.bind.annotation.XmlType;
8
9
10 /**
11 * <p>Java-Klasse für BinaryType complex type.
12 *
13 * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
14 *
15 * <pre>
16 * &lt;complexType name="BinaryType"&gt;
17 * &lt;simpleContent&gt;
18 * &lt;restriction base="&lt;http://www.w3.org/2005/05/xmlmime&gt;base64Binary"&gt;
19 * &lt;attribute ref="{http://www.w3.org/2005/05/xmlmime}contentType use="required""/&gt;
20 * &lt;/restriction&gt;
21 * &lt;/simpleContent&gt;
22 * &lt;/complexType&gt;
23 * </pre>
24 *
25 *
26 */
27 @XmlAccessorType(XmlAccessType.FIELD)
28 @XmlType(name = "BinaryType")
29 public class BinaryType
30 extends Base64Binary {
31
32
33 }
0 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
1
2
3 import javax.xml.bind.annotation.XmlEnum;
4 import javax.xml.bind.annotation.XmlType;
5
6
7 /**
8 * <p>Java-Klasse für ErrorDomainType.
9 *
10 * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
11 * <p>
12 * <pre>
13 * &lt;simpleType name="ErrorDomainType"&gt;
14 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt;
15 * &lt;enumeration value="SERVER"/&gt;
16 * &lt;enumeration value="REQUEST"/&gt;
17 * &lt;/restriction&gt;
18 * &lt;/simpleType&gt;
19 * </pre>
20 *
21 */
22 @XmlType(name = "ErrorDomainType")
23 @XmlEnum
24 public enum ErrorDomainType {
25
26
27 /**
28 * The error happend on the server side and can't be corrected with changing the request
29 * format
30 *
31 *
32 */
33 SERVER,
34
35 /**
36 * The error happend because of the request or the requests content.
37 *
38 */
39 REQUEST;
40
41 public String value() {
42 return name();
43 }
44
45 public static ErrorDomainType fromValue(String v) {
46 return valueOf(v);
47 }
48
49 }
0 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
1
2
3 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.ErrorType;
4 import javax.xml.bind.annotation.*;
5 import javax.xml.datatype.XMLGregorianCalendar;
6
7
8 /**
9 * <p>Java-Klasse für ErrorMessageType complex type.
10 *
11 * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
12 *
13 * <pre>
14 * &lt;complexType name="ErrorMessageType"&gt;
15 * &lt;complexContent&gt;
16 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
17 * &lt;sequence&gt;
18 * &lt;element name="type" type="{http://creaity.de/homecontrol/rest/types/v1}ErrorType"/&gt;
19 * &lt;element name="domain" type="{http://creaity.de/homecontrol/rest/types/v1}ErrorDomainType"/&gt;
20 * &lt;element name="message" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
21 * &lt;element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}dateTime"/&gt;
22 * &lt;/sequence&gt;
23 * &lt;/restriction&gt;
24 * &lt;/complexContent&gt;
25 * &lt;/complexType&gt;
26 * </pre>
27 *
28 *
29 */
30 @XmlAccessorType(XmlAccessType.FIELD)
31 @XmlType(name = "ErrorMessageType", propOrder = {
32 "type",
33 "domain",
34 "message",
35 "timestamp"
36 })
37 public class ErrorMessageType {
38
39 @XmlElement(required = true)
40 @XmlSchemaType(name = "string")
41 protected ErrorType type;
42 @XmlElement(required = true)
43 @XmlSchemaType(name = "string")
44 protected ErrorDomainType domain;
45 @XmlElement(required = true)
46 protected String message;
47 @XmlElement(required = true)
48 @XmlSchemaType(name = "dateTime")
49 protected XMLGregorianCalendar timestamp;
50
51 /**
52 * Ruft den Wert der type-Eigenschaft ab.
53 *
54 * @return
55 * possible object is
56 * {@link ErrorType }
57 *
58 */
59 public ErrorType getType() {
60 return type;
61 }
62
63 /**
64 * Legt den Wert der type-Eigenschaft fest.
65 *
66 * @param value
67 * allowed object is
68 * {@link ErrorType }
69 *
70 */
71 public void setType(ErrorType value) {
72 this.type = value;
73 }
74
75 /**
76 * Ruft den Wert der domain-Eigenschaft ab.
77 *
78 * @return
79 * possible object is
80 * {@link ErrorDomainType }
81 *
82 */
83 public ErrorDomainType getDomain() {
84 return domain;
85 }
86
87 /**
88 * Legt den Wert der domain-Eigenschaft fest.
89 *
90 * @param value
91 * allowed object is
92 * {@link ErrorDomainType }
93 *
94 */
95 public void setDomain(ErrorDomainType value) {
96 this.domain = value;
97 }
98
99 /**
100 * Ruft den Wert der message-Eigenschaft ab.
101 *
102 * @return
103 * possible object is
104 * {@link String }
105 *
106 */
107 public String getMessage() {
108 return message;
109 }
110
111 /**
112 * Legt den Wert der message-Eigenschaft fest.
113 *
114 * @param value
115 * allowed object is
116 * {@link String }
117 *
118 */
119 public void setMessage(String value) {
120 this.message = value;
121 }
122
123 /**
124 * Ruft den Wert der timestamp-Eigenschaft ab.
125 *
126 * @return
127 * possible object is
128 * {@link XMLGregorianCalendar }
129 *
130 */
131 public XMLGregorianCalendar getTimestamp() {
132 return timestamp;
133 }
134
135 /**
136 * Legt den Wert der timestamp-Eigenschaft fest.
137 *
138 * @param value
139 * allowed object is
140 * {@link XMLGregorianCalendar }
141 *
142 */
143 public void setTimestamp(XMLGregorianCalendar value) {
144 this.timestamp = value;
145 }
146
147 }
0 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
1
2 import javax.xml.bind.annotation.XmlEnum;
3 import javax.xml.bind.annotation.XmlType;
4
5
6 /**
7 * <p>Java-Klasse für ErrorType.
8 *
9 * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
10 * <p>
11 * <pre>
12 * &lt;simpleType name="ErrorType"&gt;
13 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt;
14 * &lt;enumeration value="NOT_FOUND"/&gt;
15 * &lt;enumeration value="VALIDATION"/&gt;
16 * &lt;enumeration value="INTERNAL_SERVER_ERROR"/&gt;
17 * &lt;enumeration value="SECURITY"/&gt;
18 * &lt;/restriction&gt;
19 * &lt;/simpleType&gt;
20 * </pre>
21 *
22 */
23 @XmlType(name = "ErrorType")
24 @XmlEnum
25 public enum ErrorType {
26
27
28 /**
29 * The requested resource was not found
30 *
31 */
32 NOT_FOUND,
33
34 /**
35 * The requested format did not match the specification
36 *
37 */
38 VALIDATION,
39
40 /**
41 * An error happend during the request processing
42 *
43 */
44 INTERNAL_SERVER_ERROR,
45
46 /**
47 * Request can't be processed, because the caller has insufficient authorization
48 *
49 *
50 */
51 SECURITY;
52
53 public String value() {
54 return name();
55 }
56
57 public static ErrorType fromValue(String v) {
58 return valueOf(v);
59 }
60
61 }
62
0 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlType;
6
7
8 /**
9 * <p>Java-Klasse für IDType complex type.
10 * <p>
11 * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
12 * <p>
13 * <pre>
14 * &lt;complexType name="IDType"&gt;
15 * &lt;complexContent&gt;
16 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
17 * &lt;sequence&gt;
18 * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
19 * &lt;/sequence&gt;
20 * &lt;/restriction&gt;
21 * &lt;/complexContent&gt;
22 * &lt;/complexType&gt;
23 * </pre>
24 */
25 @XmlAccessorType(XmlAccessType.FIELD)
26 @XmlType(name = "IDType", propOrder = {
27 "id"
28 })
29 public class IDType {
30
31 @XmlElement(required = true)
32 protected String id;
33
34 /**
35 * Ruft den Wert der id-Eigenschaft ab.
36 *
37 * @return possible object is
38 * {@link String }
39 */
40 public String getId() {
41 return id;
42 }
43
44 /**
45 * Legt den Wert der id-Eigenschaft fest.
46 *
47 * @param value allowed object is
48 * {@link String }
49 */
50 public void setId(String value) {
51 this.id = value;
52 }
53
54 }
55
0 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
1
2 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.UserType;
3 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.RoleType;
4 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.ErrorType;
5 import org.jboss.resteasy.test.providers.jaxb.resource.homecontrol.ErrorMessageType;
6
7 import javax.xml.bind.JAXBElement;
8 import javax.xml.bind.annotation.XmlElementDecl;
9 import javax.xml.bind.annotation.XmlRegistry;
10 import javax.xml.namespace.QName;
11
12
13 /**
14 * This object contains factory methods for each
15 * Java content interface and Java element interface
16 * generated in the de.creaity.homecontrol.service.rest.jaxb.v1 package.
17 * <p>An ObjectFactory allows you to programatically
18 * construct new instances of the Java representation
19 * for XML content. The Java representation of XML
20 * content can consist of schema derived interfaces
21 * and classes representing the binding of schema
22 * type definitions, element declarations and model
23 * groups. Factory methods for each of these are
24 * provided in this class.
25 *
26 */
27 @XmlRegistry
28 public class ObjectFactory {
29
30 private final static QName _User_QNAME = new QName("http://creaity.de/homecontrol/rest/types/v1", "user");
31 private final static QName _Error_QNAME = new QName("http://creaity.de/homecontrol/rest/types/v1", "error");
32 private final static QName _Id_QNAME = new QName("http://creaity.de/homecontrol/rest/types/v1", "id");
33
34 /**
35 * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: de.creaity.homecontrol.service.rest.jaxb.v1
36 *
37 */
38 public ObjectFactory() {
39 }
40
41 /**
42 * Create an instance of {@link UserType }
43 *
44 */
45 public UserType createUserType() {
46 return new UserType();
47 }
48
49 /**
50 * Create an instance of {@link ErrorMessageType }
51 *
52 */
53 public ErrorMessageType createErrorMessageType() {
54 return new ErrorMessageType();
55 }
56
57 /**
58 * Create an instance of {@link IDType }
59 */
60 public IDType createIDType() {
61 return new IDType();
62 }
63
64 /**
65 * Create an instance of {@link BinaryType }
66 *
67 */
68 public BinaryType createBinaryType() {
69 return new BinaryType();
70 }
71
72 /**
73 * Create an instance of {@link UserType.Credentials }
74 *
75 */
76 public UserType.Credentials createUserTypeCredentials() {
77 return new UserType.Credentials();
78 }
79
80 /**
81 * Create an instance of {@link JAXBElement }{@code <}{@link UserType }{@code >}}
82 *
83 */
84 @XmlElementDecl(namespace = "http://creaity.de/homecontrol/rest/types/v1", name = "user")
85 public JAXBElement<UserType> createUser(UserType value) {
86 return new JAXBElement<UserType>(_User_QNAME, UserType.class, null, value);
87 }
88
89 /**
90 * Create an instance of {@link JAXBElement }{@code <}{@link ErrorMessageType }{@code >}}
91 *
92 */
93 @XmlElementDecl(namespace = "http://creaity.de/homecontrol/rest/types/v1", name = "error")
94 public JAXBElement<ErrorMessageType> createError(ErrorMessageType value) {
95 return new JAXBElement<ErrorMessageType>(_Error_QNAME, ErrorMessageType.class, null, value);
96 }
97
98 /**
99 * Create an instance of {@link JAXBElement }{@code <}{@link IDType }{@code >}}
100 *
101 */
102 @XmlElementDecl(namespace = "http://creaity.de/homecontrol/rest/types/v1", name = "id")
103 public JAXBElement<IDType> createId(IDType value) {
104 return new JAXBElement<IDType>(_Id_QNAME, IDType.class, null, value);
105 }
106
107 }
0 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
1
2 import javax.xml.bind.annotation.XmlEnum;
3 import javax.xml.bind.annotation.XmlType;
4
5
6 /**
7 * <p>Java-Klasse für RoleType.
8 *
9 * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
10 * <p>
11 * <pre>
12 * &lt;simpleType name="RoleType"&gt;
13 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt;
14 * &lt;enumeration value="USER"/&gt;
15 * &lt;enumeration value="ADMIN"/&gt;
16 * &lt;enumeration value="BACKUP_USER"/&gt;
17 * &lt;enumeration value="BACKUP_ADMIN"/&gt;
18 * &lt;/restriction&gt;
19 * &lt;/simpleType&gt;
20 * </pre>
21 *
22 */
23 @XmlType(name = "RoleType")
24 @XmlEnum
25 public enum RoleType {
26
27
28 /**
29 * standard role which is needed to access the homecontrol application
30 *
31 *
32 */
33 USER,
34
35 /**
36 * Administration user for administrate the whole homecontrol application
37 *
38 *
39 */
40 ADMIN,
41
42 /**
43 * User for the backup module of homecontrol
44 *
45 *
46 */
47 BACKUP_USER,
48
49 /**
50 * Admin user for administrating the backup module of homecontrol
51 *
52 */
53 BACKUP_ADMIN;
54
55 public String value() {
56 return name();
57 }
58
59 public static RoleType fromValue(String v) {
60 return valueOf(v);
61 }
62
63 }
0 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
1
2 import javax.xml.bind.annotation.*;
3 import java.util.ArrayList;
4 import java.util.List;
5
6
7 /**
8 * <p>Java-Klasse für UserType complex type.
9 *
10 * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
11 *
12 * <pre>
13 * &lt;complexType name="UserType"&gt;
14 * &lt;complexContent&gt;
15 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
16 * &lt;sequence&gt;
17 * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
18 * &lt;element name="credentials"&gt;
19 * &lt;complexType&gt;
20 * &lt;complexContent&gt;
21 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
22 * &lt;sequence&gt;
23 * &lt;element name="loginId" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
24 * &lt;element name="password" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
25 * &lt;/sequence&gt;
26 * &lt;/restriction&gt;
27 * &lt;/complexContent&gt;
28 * &lt;/complexType&gt;
29 * &lt;/element&gt;
30 * &lt;element name="roles"&gt;
31 * &lt;complexType&gt;
32 * &lt;complexContent&gt;
33 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
34 * &lt;sequence&gt;
35 * &lt;element name="role" type="{http://creaity.de/homecontrol/rest/types/v1}RoleType" maxOccurs="unbounded"/&gt;
36 * &lt;/sequence&gt;
37 * &lt;/restriction&gt;
38 * &lt;/complexContent&gt;
39 * &lt;/complexType&gt;
40 * &lt;/element&gt;
41 * &lt;/sequence&gt;
42 * &lt;/restriction&gt;
43 * &lt;/complexContent&gt;
44 * &lt;/complexType&gt;
45 * </pre>
46 *
47 *
48 */
49 @XmlAccessorType(XmlAccessType.FIELD)
50 @XmlType(name = "UserType", propOrder = {
51 "id",
52 "credentials",
53 "roles"
54 })
55 public class UserType {
56 @XmlElement(namespace = "http://creaity.de/homecontrol/rest/types/v1")
57 protected String id;
58 @XmlElement(required = true)
59 protected UserType.Credentials credentials;
60 @XmlElementWrapper(required = true)
61 @XmlElement(name = "role", namespace = "http://creaity.de/homecontrol/rest/types/v1")
62 protected List<RoleType> roles = new ArrayList<RoleType>();
63
64 /**
65 * Ruft den Wert der id-Eigenschaft ab.
66 *
67 * @return
68 * possible object is
69 * {@link String }
70 *
71 */
72 public String getId() {
73 return id;
74 }
75
76 /**
77 * Legt den Wert der id-Eigenschaft fest.
78 *
79 * @param value
80 * allowed object is
81 * {@link String }
82 *
83 */
84 public void setId(String value) {
85 this.id = value;
86 }
87
88 /**
89 * Ruft den Wert der credentials-Eigenschaft ab.
90 *
91 * @return
92 * possible object is
93 * {@link UserType.Credentials }
94 *
95 */
96 public UserType.Credentials getCredentials() {
97 return credentials;
98 }
99
100 /**
101 * Legt den Wert der credentials-Eigenschaft fest.
102 *
103 * @param value
104 * allowed object is
105 * {@link UserType.Credentials }
106 *
107 */
108 public void setCredentials(UserType.Credentials value) {
109 this.credentials = value;
110 }
111
112 public List<RoleType> getRoles() {
113 return roles;
114 }
115
116 public void setRoles(List<RoleType> roles) {
117 this.roles = roles;
118 }
119
120
121 /**
122 * <p>Java-Klasse für anonymous complex type.
123 *
124 * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
125 *
126 * <pre>
127 * &lt;complexType&gt;
128 * &lt;complexContent&gt;
129 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
130 * &lt;sequence&gt;
131 * &lt;element name="loginId" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
132 * &lt;element name="password" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
133 * &lt;/sequence&gt;
134 * &lt;/restriction&gt;
135 * &lt;/complexContent&gt;
136 * &lt;/complexType&gt;
137 * </pre>
138 *
139 *
140 */
141 @XmlAccessorType(XmlAccessType.FIELD)
142 @XmlType(name = "", propOrder = {
143 "loginId",
144 "password"
145 })
146 public static class Credentials {
147
148 @XmlElement(required = true)
149 protected String loginId;
150 protected String password;
151
152 /**
153 * Ruft den Wert der loginId-Eigenschaft ab.
154 *
155 * @return
156 * possible object is
157 * {@link String }
158 *
159 */
160 public String getLoginId() {
161 return loginId;
162 }
163
164 /**
165 * Legt den Wert der loginId-Eigenschaft fest.
166 *
167 * @param value
168 * allowed object is
169 * {@link String }
170 *
171 */
172 public void setLoginId(String value) {
173 this.loginId = value;
174 }
175
176 /**
177 * Ruft den Wert der password-Eigenschaft ab.
178 *
179 * @return
180 * possible object is
181 * {@link String }
182 *
183 */
184 public String getPassword() {
185 return password;
186 }
187
188 /**
189 * Legt den Wert der password-Eigenschaft fest.
190 *
191 * @param value
192 * allowed object is
193 * {@link String }
194 *
195 */
196 public void setPassword(String value) {
197 this.password = value;
198 }
199
200 }
201
202 }
0 @javax.xml.bind.annotation.XmlSchema(namespace = "http://creaity.de/homecontrol/rest/types/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
1 package org.jboss.resteasy.test.providers.jaxb.resource.homecontrol;
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ProxyFactory;
56 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
67 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
78 import org.jboss.resteasy.test.providers.jettison.resource.CRUDEntityWebservice;
7374
7475 assertEquals("Wrong response from proxy", "user", newUser.getUsername());
7576 }
77
78 /**
79 * @tpTestDetails Test for old client
80 * @tpSince RESTEasy 3.0.16
81 */
82 @Test
83 public void testOldClient() {
84 UserEntity u = new UserEntity();
85 u.setUsername("user");
86
87 UserEntityWebservice serviceClient = ProxyFactory.create(UserEntityWebservice.class, generateBaseUrl());
88 UserEntity newUser = serviceClient.create(u);
89
90 assertEquals("Wrong response from proxy", "user", newUser.getUsername());
91 }
7692 }
0 package org.jboss.resteasy.test.providers.jsonb.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.category.Jaxrs21;
7 import org.jboss.resteasy.test.providers.jsonb.basic.resource.Cat;
8 import org.jboss.resteasy.test.providers.jsonb.basic.resource.JsonBindingResource;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.After;
14 import org.junit.Assert;
15 import org.junit.Before;
16 import org.junit.Test;
17 import org.junit.experimental.categories.Category;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.client.Client;
21 import javax.ws.rs.client.ClientBuilder;
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.client.WebTarget;
24 import javax.ws.rs.core.MediaType;
25
26 import static org.hamcrest.CoreMatchers.is;
27
28 /**
29 * @tpSubChapter Json-binding provider.
30 * @tpChapter Integration test
31 * @tpSince RESTEasy 3.5
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 @Category(Jaxrs21.class)
36 public class JsonBindingAnnotationsJacksonTest {
37
38
39 private static final String WAR_WITH_JSONB = "war_with_jsonb";
40 private static final String WAR_WITHOUT_JSONB = "war_without_jsonb";
41
42 protected static final Logger logger = Logger.getLogger(JsonBindingAnnotationsJacksonTest.class.getName());
43
44 static Client client;
45
46 @Deployment(name = WAR_WITH_JSONB)
47 public static Archive<?> deployWithJsonB() {
48 return deploy(WAR_WITH_JSONB, true);
49 }
50
51 @Deployment(name = WAR_WITHOUT_JSONB)
52 public static Archive<?> deployWithoutJsonB() {
53 return deploy(WAR_WITHOUT_JSONB, false);
54 }
55
56 public static Archive<?> deploy(String archiveName, boolean useJsonB) {
57 WebArchive war = TestUtil.prepareArchive(archiveName);
58 war.addClass(JsonBindingTest.class);
59 if (useJsonB) {
60 war.addAsManifestResource("jboss-deployment-structure-json-b.xml", "jboss-deployment-structure.xml");
61 }
62 return TestUtil.finishContainerPrepare(war, null, JsonBindingResource.class, Cat.class);
63 }
64
65 @Deployment
66 public static Archive<?> deploy() {
67 WebArchive war = TestUtil.prepareArchive(JsonBindingAnnotationsJacksonTest.class.getSimpleName());
68 war.addClass(JsonBindingAnnotationsJacksonTest.class);
69 return TestUtil.finishContainerPrepare(war, null, JsonBindingResource.class, Cat.class);
70 }
71
72 @Before
73 public void init() {
74 client = ClientBuilder.newClient();
75 }
76
77 @After
78 public void after() throws Exception {
79 client.close();
80 client = null;
81 }
82
83 /**
84 * @tpTestDetails JSON-B is not used on client, JSON-B is used on server
85 * client send a value in variable with @JsonbTransient annotation
86 * server should not receive a value in this variable (JSON-B on server should filter it)
87 * end-point returns a value in this variable, but server should ignore this variable
88 * check that server returns object without variable with @JsonbTransient annotation to client
89 *
90 * @tpPassCrit The resource returns object with correct values
91 * @tpSince RESTEasy 3.5
92 */
93 @Test
94 public void jsonbOnServerNotOnClientTest() throws Exception {
95 String charset = "UTF-8";
96 WebTarget target = client.target(PortProviderUtil.generateURL("/test/jsonBinding/cat/transient", WAR_WITH_JSONB));
97 MediaType mediaType = MediaType.APPLICATION_JSON_TYPE.withCharset(charset);
98 Entity<Cat> entity = Entity.entity(
99 new Cat("Rosa", "semi-british", "tabby", true, JsonBindingResource.CLIENT_TRANSIENT_VALUE), mediaType);
100 Cat json = target.request().post(entity, Cat.class);
101 logger.info("Request entity: " + entity);
102 Assert.assertThat("Variable with JsonbTransient annotation should be transient, if JSON-B is used",
103 json.getTransientVar(), is(Cat.DEFAULT_TRANSIENT_VAR_VALUE));
104 }
105
106 /**
107 * @tpTestDetails JSON-B is not used on both server and client
108 * check that @JsonbTransient annotation is ignored
109 *
110 * @tpPassCrit The resource returns object with correct values
111 * @tpSince RESTEasy 3.5
112 */
113 @Test
114 public void jsonbNotOnServerNotOnClientTest() throws Exception {
115 String charset = "UTF-8";
116 WebTarget target = client.target(PortProviderUtil.generateURL("/test/jsonBinding/cat/not/transient", WAR_WITHOUT_JSONB));
117 MediaType mediaType = MediaType.APPLICATION_JSON_TYPE.withCharset(charset);
118 Entity<Cat> entity = Entity.entity(
119 new Cat("Rosa", "semi-british", "tabby", true, JsonBindingResource.CLIENT_TRANSIENT_VALUE), mediaType);
120 Cat json = target.request().post(entity, Cat.class);
121 logger.info("Request entity: " + entity);
122 Assert.assertThat("Variable with JsonbTransient annotation should not be transient, if JSON-B is not used",
123 json.getTransientVar(), is(JsonBindingResource.RETURNED_TRANSIENT_VALUE));
124 }
125 }
0 package org.jboss.resteasy.test.providers.jsonb.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.category.Jaxrs21;
7 import org.jboss.resteasy.test.providers.jsonb.basic.resource.Cat;
8 import org.jboss.resteasy.test.providers.jsonb.basic.resource.JsonBindingCustomRepeaterProvider;
9 import org.jboss.resteasy.test.providers.jsonb.basic.resource.JsonBindingResource;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.AfterClass;
15 import org.junit.Assert;
16 import org.junit.BeforeClass;
17 import org.junit.Test;
18 import org.junit.experimental.categories.Category;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.Client;
22 import javax.ws.rs.client.ClientBuilder;
23 import javax.ws.rs.client.Entity;
24 import javax.ws.rs.client.WebTarget;
25 import javax.ws.rs.core.MediaType;
26
27 import static org.hamcrest.CoreMatchers.is;
28
29 /**
30 * @tpSubChapter Json-binding provider.JAX-RS 2.1 spec (JSR-370), section 11.2.7 states,
31 * "Note that if JSON-B and JSON-P are both supported in the same environment, entity providers for
32 * JSON-B take precedence over those for JSON-P for all types except JsonValue and its sub-types."
33 * The sub-types of JsonValue are JsonArray, JsonNumber, JsonObject, JsonString, JsonStructure.
34 * Resteasy's JSON-P providers currently supports this. A general object such as Cat will be processed by
35 * the JSON-B provider.
36 * @tpChapter Integration test
37 * @tpSince RESTEasy 3.5
38 */
39 @RunWith(Arquillian.class)
40 @RunAsClient
41 @Category(Jaxrs21.class)
42 public class JsonBindingTest {
43
44 protected static final Logger logger = Logger.getLogger(JsonBindingTest.class.getName());
45
46 static Client client;
47
48 private static final String WAR_WITH_JSONB = "war_with_jsonb";
49 private static final String CUSTOM_JSON_PROVIDER = "custom_json_provider";
50
51 @Deployment(name = WAR_WITH_JSONB)
52 public static Archive<?> deployWithJsonB() {
53 return deploy(WAR_WITH_JSONB, true);
54 }
55
56 @Deployment(name = CUSTOM_JSON_PROVIDER)
57 public static Archive<?> deployWithoutJsonB() {
58 return deploy(CUSTOM_JSON_PROVIDER, false);
59 }
60
61 public static Archive<?> deploy(String archiveName, boolean useJsonB) {
62 WebArchive war = TestUtil.prepareArchive(archiveName);
63 war.addClass(JsonBindingTest.class);
64 war.addClass(Cat.class);
65 if (useJsonB) {
66 war.addAsManifestResource("jboss-deployment-structure-json-b.xml", "jboss-deployment-structure.xml");
67 return TestUtil.finishContainerPrepare(war, null, JsonBindingResource.class);
68 }
69 return TestUtil.finishContainerPrepare(war, null, JsonBindingResource.class, JsonBindingCustomRepeaterProvider.class);
70 }
71
72 @BeforeClass
73 public static void init() {
74 client = ClientBuilder.newClient();
75 }
76
77 @AfterClass
78 public static void after() throws Exception {
79 client.close();
80 client = null;
81 }
82
83 /**
84 * @tpTestDetails Client sends POST request with a JSON annotated entity. The object should be returned back by the
85 * response and should contain the same field values as original request.
86 *
87 * JSON-B is activated on both server and client side
88 * Client should not ignore @JsonbTransient annotation and should not send a value in this variable
89 * Check that server returns object without a value in variable with @JsonbTransient annotation
90 *
91 * @tpPassCrit The resource returns object with correct values
92 * @tpSince RESTEasy 3.5
93 */
94 @Test
95 public void jsonbOnServerAndClientTest() throws Exception {
96 String charset = "UTF-8";
97 WebTarget target = client.target(PortProviderUtil.generateURL("/test/jsonBinding/cat/transient", WAR_WITH_JSONB));
98 MediaType mediaType = MediaType.APPLICATION_JSON_TYPE.withCharset(charset);
99 Entity<Cat> entity = Entity.entity(
100 new Cat("Rosa", "semi-british", "tabby", true, JsonBindingResource.CLIENT_TRANSIENT_VALUE), mediaType);
101 Cat json = target.request().post(entity, Cat.class);
102 logger.info("Request entity: " + entity);
103 Assert.assertTrue("Failed to return the correct name", "Alfred".equals(json.getName()));
104 Assert.assertThat("Variable with JsonbTransient annotation should be transient, if JSON-B is used",
105 json.getTransientVar(), is(Cat.DEFAULT_TRANSIENT_VAR_VALUE));
106
107 String jsonbResponse = target.request().post(entity).readEntity(String.class);
108 Assert.assertEquals("JsonBindingProvider is not enabled", "{\"color\":\"ginger\",\"sort\":\"semi-british\",\"name\":\"Alfred\",\"domesticated\":true}", jsonbResponse);
109 }
110
111 /**
112 * @tpTestDetails JSON-B is used on client, JSON-B is not used on server, server uses test's custom json provider
113 * client should not ignore @JsonbTransient annotation and should not send a value in this variable
114 * server verify that client doesn't sent a value in a variable with @JsonbTransient annotation
115 * server returns json data with a value in a variable with @JsonbTransient annotation
116 * client should not ignore @JsonbTransient annotation and should not receive a value in this variable
117 *
118 * @tpPassCrit The resource returns object with correct values
119 * @tpSince RESTEasy 3.5
120 */
121 @Test
122 public void jsonbOnClientTest() throws Exception {
123 String charset = "UTF-8";
124 WebTarget target = client.target(PortProviderUtil.generateURL("/test/jsonBinding/client/test/transient", CUSTOM_JSON_PROVIDER));
125 MediaType mediaType = MediaType.APPLICATION_JSON_TYPE.withCharset(charset);
126 Entity<Cat> entity = Entity.entity(
127 new Cat("Rosa", "semi-british", "tabby", true,
128 JsonBindingResource.CLIENT_TRANSIENT_VALUE), mediaType);
129 Cat response = target.request().post(entity, Cat.class);
130 Assert.assertThat("Failed to return the correct name", response.getName(), is("Rosa"));
131 Assert.assertThat("Variable with JsonbTransient annotation should be transient, if JSON-B is used",
132 response.getTransientVar(), is(Cat.DEFAULT_TRANSIENT_VAR_VALUE));
133 }
134
135
136 }
0 package org.jboss.resteasy.test.providers.jsonb.basic.resource;
1
2 import javax.json.bind.annotation.JsonbPropertyOrder;
3 import javax.json.bind.annotation.JsonbTransient;
4
5 /**
6 * Created by rsearls.
7 */
8 @JsonbPropertyOrder({"color", "sort", "name", "domesticated"})
9 public class Cat {
10
11 public static final Integer DEFAULT_TRANSIENT_VAR_VALUE = -1;
12
13 private String name;
14 private String sort;
15 private String color;
16 private boolean domesticated;
17
18 /**
19 * This variable should be processed by Jackson2, but this variable should be ignored by JSON-B.
20 */
21 @JsonbTransient
22 private int transientVar;
23
24 // json-b needs the default constructor
25 public Cat() {
26 super();
27 transientVar = DEFAULT_TRANSIENT_VAR_VALUE;
28 }
29
30 public Cat(String name, String sort, String color, boolean domesticated, int transientVar) {
31 this.name = name;
32 this.sort = sort;
33 this.color = color;
34 this.domesticated = domesticated;
35 this.transientVar = transientVar;
36 }
37
38 public String getName() {
39 return name;
40 }
41
42 public Cat setName(String name) {
43 this.name = name;
44 return this;
45 }
46
47 public String getSort() {
48 return sort;
49 }
50
51 public Cat setSort(String sort) {
52 this.sort = sort;
53 return this;
54 }
55
56 public String getColor() {
57 return color;
58 }
59
60 public Cat setColor(String color) {
61 this.color = color;
62 return this;
63 }
64
65 public boolean isDomesticated() {
66 return domesticated;
67 }
68
69 public Cat setDomesticated(boolean domesticated) {
70 this.domesticated = domesticated;
71 return this;
72 }
73
74 public int getTransientVar() {
75 return transientVar;
76 }
77
78 public void setTransientVar(int transientVar) {
79 this.transientVar = transientVar;
80 }
81
82 @Override
83 public String toString() {
84 return "Cat - custom toString format {" +
85 "name='" + name + '\'' +
86 ", sort='" + sort + '\'' +
87 ", color='" + color + '\'' +
88 ", domesticated=" + domesticated +
89 ", transientVar=" + transientVar +
90 '}';
91 }
92 }
93
0 package org.jboss.resteasy.test.providers.jsonb.basic.resource;
1
2 import org.jboss.resteasy.plugins.providers.ProviderHelper;
3 import org.jboss.resteasy.util.NoContent;
4 import org.jboss.resteasy.util.TypeConverter;
5
6 import javax.annotation.Priority;
7 import javax.ws.rs.Consumes;
8 import javax.ws.rs.Priorities;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.WebApplicationException;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.MultivaluedMap;
13 import javax.ws.rs.ext.MessageBodyReader;
14 import javax.ws.rs.ext.MessageBodyWriter;
15 import javax.ws.rs.ext.Provider;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.OutputStream;
19 import java.io.UnsupportedEncodingException;
20 import java.lang.annotation.Annotation;
21 import java.lang.reflect.Type;
22 import java.nio.charset.StandardCharsets;
23
24 /**
25 * This test provider is based on DefaultTextPlain provider
26 */
27 @SuppressWarnings("unchecked")
28 @Provider
29 @Produces({"application/json", "application/*+json", "text/json", "*/*"})
30 @Consumes({"application/json", "application/*+json", "text/json", "*/*"})
31 @Priority(Priorities.USER)
32 public class JsonBindingCustomRepeaterProvider implements MessageBodyReader, MessageBodyWriter
33 {
34 public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType)
35 {
36 // StringTextStar should pick up strings
37 return !String.class.equals(type) && TypeConverter.isConvertable(type);
38 }
39
40 public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
41 {
42 InputStream delegate = NoContent.noContentCheck(httpHeaders, entityStream);
43 String value = ProviderHelper.readString(delegate, mediaType);
44 return TypeConverter.getType(type, value);
45 }
46
47 public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType)
48 {
49 // StringTextStar should pick up strings
50 return !String.class.equals(type) && !type.isArray();
51 }
52
53 public long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType)
54 {
55 String charset = mediaType.getParameters().get("charset");
56 if (charset != null)
57 try
58 {
59 return o.toString().getBytes(charset).length;
60 } catch (UnsupportedEncodingException e)
61 {
62 // Use default encoding.
63 }
64 return o.toString().getBytes(StandardCharsets.UTF_8).length;
65 }
66
67 public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
68 {
69 String charset = mediaType.getParameters().get("charset");
70 if (charset == null) entityStream.write(o.toString().getBytes(StandardCharsets.UTF_8));
71 else entityStream.write(o.toString().getBytes(charset));
72 }
73 }
0 package org.jboss.resteasy.test.providers.jsonb.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6
7 @Path("/test/jsonBinding")
8 public class JsonBindingResource {
9
10 public static final Integer RETURNED_TRANSIENT_VALUE = 12345;
11
12 public static final Integer CLIENT_TRANSIENT_VALUE = 54321;
13
14 @Path("cat/transient")
15 @POST
16 @Produces("application/json")
17 @Consumes("application/json")
18 public Cat getCatTransient(Cat cat) throws Exception {
19 // check received message for transient variable
20 if (cat.getTransientVar() != Cat.DEFAULT_TRANSIENT_VAR_VALUE) {
21 throw new Exception("JsonbTransient annotation doesn't work");
22 }
23 // update response
24 cat.setName("Alfred");
25 cat.setColor("ginger");
26 cat.setTransientVar(RETURNED_TRANSIENT_VALUE);
27 return cat;
28 }
29
30
31 @Path("cat/not/transient")
32 @POST
33 @Produces("application/json")
34 @Consumes("application/json")
35 public Cat getCatNotTransient(Cat cat) throws Exception {
36 // check received message for transient variable
37 if (cat.getTransientVar() == Cat.DEFAULT_TRANSIENT_VAR_VALUE) {
38 throw new Exception("JsonbTransient annotation works, but it shouldn't work");
39 }
40 // update response
41 cat.setName("Alfred");
42 cat.setColor("ginger");
43 cat.setTransientVar(RETURNED_TRANSIENT_VALUE);
44 return cat;
45 }
46
47 @Path("client/test/transient")
48 @POST
49 @Produces("application/json")
50 @Consumes("application/json")
51 public String repeaterTransient(String data) throws Exception {
52 if (data.contains(CLIENT_TRANSIENT_VALUE.toString())) {
53 throw new Exception("JsonbTransient annotation doesn't work");
54 }
55 return "{\"color\":\"tabby\",\"sort\":\"semi-british\",\"name\":\"Rosa\",\"domesticated\":true,\"transientVar\":\""
56 + RETURNED_TRANSIENT_VALUE + "\"}";
57 }
58 }
6565 response = request.get();
6666 Assert.assertTrue(Boolean.parseBoolean(response.readEntity(String.class)));
6767 }
68 @Test
69 //RESTEASY-1730: Could not find MessageBodyWriter for response object of type: java.lang.Boolean of media type: application/octet-stream
70 public void testGetBoolean() throws Exception {
71 Invocation.Builder request = client.target(generateURL("/test/getbool")).request();
72 Response response = request.get();
73 String entity = response.readEntity(String.class);
74 Assert.assertEquals(200, response.getStatus());
75 Assert.assertEquals("true", entity);
76 }
6877 }
1919 public Response used() {
2020 return Response.ok(Boolean.toString(MessageBodyWriterObjectMessageBodyWriter.used)).build();
2121 }
22 @GET
23 @Path("/getbool")
24 public boolean testBoolean() {
25 return true;
26 }
2227 }
1313 import javax.ws.rs.client.Client;
1414 import javax.ws.rs.client.ClientBuilder;
1515 import javax.ws.rs.client.Entity;
16 import javax.ws.rs.client.Invocation.Builder;
1716 import javax.ws.rs.client.WebTarget;
1817 import javax.ws.rs.core.GenericType;
1918 import javax.ws.rs.core.MediaType;
2827 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
2928 import org.jboss.resteasy.annotations.providers.multipart.PartType;
3029 import org.jboss.resteasy.annotations.providers.multipart.XopWithMultipartRelated;
30 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
31 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
3132 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
3233 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
3334 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
6768
6869 protected final Logger logger = LogManager.getLogger(ContextProvidersTest.class.getName());
6970
71 protected enum Version {
72 TWO,
73 THREE
74 }
75
7076 public static final Annotation PART_TYPE_APPLICATION_XML = new S1() {
7177 private static final long serialVersionUID = 1L;
7278
103109 */
104110 @Test
105111 public void testGetFormData() throws Exception {
106 doTestGetFormData();
107 }
108
109 public void doTestGetFormData() throws Exception {
112 doTestGetFormData(Version.TWO);
113 doTestGetFormData(Version.THREE);
114 }
115
116 public void doTestGetFormData(Version version) throws Exception {
110117 try {
111 MultipartFormDataInput entity = get("/get/form", MultipartFormDataInput.class);
118 MultipartFormDataInput entity = get(version, "/get/form", MultipartFormDataInput.class);
112119
113120 // Get parts by name.
114121 ContextProvidersCustomer c = entity.getFormDataPart("bill", ContextProvidersCustomer.class, null);
145152 */
146153 @Test
147154 public void testGetMixed() throws Exception {
148 doTestGetMixed();
149 }
150
151 void doTestGetMixed() throws Exception {
155 doTestGetMixed(Version.TWO);
156 doTestGetMixed(Version.THREE);
157 }
158
159 void doTestGetMixed(Version version) throws Exception {
152160 try {
153 MultipartInput entity = get("/get/mixed", MultipartInput.class);
161 MultipartInput entity = get(version, "/get/mixed", MultipartInput.class);
154162
155163 // Iterate over list of parts.
156164 List<InputPart> parts = entity.getParts();
176184 */
177185 @Test
178186 public void testGetList() throws Exception {
179 doTestGetList();
180 }
181
182 void doTestGetList() throws Exception {
187 doTestGetList(Version.TWO);
188 doTestGetList(Version.THREE);
189 }
190
191 void doTestGetList(Version version) throws Exception {
183192 try {
184 MultipartInput entity = get("/get/list", MultipartInput.class);
193 MultipartInput entity = get(version, "/get/list", MultipartInput.class);
185194
186195 // Iterate over list of parts.
187196 List<InputPart> parts = entity.getParts();
205214 */
206215 @Test
207216 public void testGetMap() throws Exception {
208 doTestGetMap();
209 }
210
211 public void doTestGetMap() throws Exception {
217 doTestGetMap(Version.TWO);
218 doTestGetMap(Version.THREE);
219 }
220
221 public void doTestGetMap(Version version) throws Exception {
212222 try {
213 MultipartFormDataInput entity = get("/get/map", MultipartFormDataInput.class);
223 MultipartFormDataInput entity = get(version, "/get/map", MultipartFormDataInput.class);
214224
215225 // Get parts by name.
216226 ContextProvidersCustomer c = entity.getFormDataPart("bill", ContextProvidersCustomer.class, null);
244254 */
245255 @Test
246256 public void testGetRelated() throws Exception {
247 doTestGetRelated();
248 }
249
250 void doTestGetRelated() throws Exception {
257 doTestGetRelated(Version.TWO);
258 doTestGetRelated(Version.THREE);
259 }
260
261 void doTestGetRelated(Version version) throws Exception {
251262 try {
252 MultipartRelatedInput entity = get("/get/related", MultipartRelatedInput.class);
263 MultipartRelatedInput entity = get(version, "/get/related", MultipartRelatedInput.class);
253264
254265 // Iterate over map of parts.
255266 Map<String, InputPart> map = entity.getRelatedMap();
278289 */
279290 @Test
280291 public void testGetMultipartForm() throws Exception {
281 doTestGetMultipartForm();
282 }
283
284 void doTestGetMultipartForm() throws Exception {
292 doTestGetMultipartForm(Version.TWO);
293 doTestGetMultipartForm(Version.THREE);
294 }
295
296 void doTestGetMultipartForm(Version version) throws Exception {
285297 Annotation[] annotations = new Annotation[1];
286298 annotations[0] = MULTIPART_FORM;
287 ContextProvidersCustomerForm form = get("/get/multipartform", ContextProvidersCustomerForm.class, annotations);
299 ContextProvidersCustomerForm form = get(version, "/get/multipartform", ContextProvidersCustomerForm.class, annotations);
288300 ContextProvidersCustomer customer = form.getCustomer();
289301 Assert.assertEquals("Wrong response", "Bill", customer.getName());
290302 }
296308 */
297309 @Test
298310 public void testGetXop() throws Exception {
299 doTestGetXop();
300 }
301
302 void doTestGetXop() throws Exception {
311 doTestGetXop(Version.TWO);
312 doTestGetXop(Version.THREE);
313 }
314
315 void doTestGetXop(Version version) throws Exception {
303316 Annotation[] annotations = new Annotation[1];
304317 annotations[0] = XOP_WITH_MULTIPART_RELATED;
305 ContextProvidersXop xop = get("/get/xop", ContextProvidersXop.class, annotations);
318 ContextProvidersXop xop = get(version, "/get/xop", ContextProvidersXop.class, annotations);
306319 Assert.assertEquals("Wrong response", "goodbye world", new String(xop.getBytes()));
307320 }
308321
313326 */
314327 @Test
315328 public void testPostMixed() throws Exception {
316 doTestPostMixed();
329 doTestPostMixed(Version.TWO);
330 doTestPostMixed(Version.THREE);
317331 }
318332
319333 @SuppressWarnings("unchecked")
320 void doTestPostMixed() throws Exception {
334 void doTestPostMixed(Version version) throws Exception {
321335 MultipartOutput output = new MultipartOutput();
322336 output.addPart(new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE);
323337 output.addPart("Bob", MediaType.TEXT_PLAIN_TYPE);
324338 Annotation[] annotations = new Annotation[1];
325339 annotations[0] = PART_TYPE_APPLICATION_XML;
326340 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
327 names = post("/post/mixed", output, MULTIPART_MIXED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
341 names = post(version, "/post/mixed", output, MULTIPART_MIXED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
328342 Assert.assertEquals(2, names.size());
329343 Assert.assertTrue(names.contains(new ContextProvidersName("Bill")));
330344 Assert.assertTrue(names.contains(new ContextProvidersName("Bob")));
337351 */
338352 @Test
339353 public void testPostFormData() throws Exception {
340 doTestPostFormData();
354 doTestPostFormData(Version.TWO);
355 doTestPostFormData(Version.THREE);
341356 }
342357
343358 @SuppressWarnings("unchecked")
344 public void doTestPostFormData() throws Exception {
359 public void doTestPostFormData(Version version) throws Exception {
345360
346361 MultipartFormDataOutput output = new MultipartFormDataOutput();
347362 output.addFormData("bill", new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE);
349364 Annotation[] annotations = new Annotation[1];
350365 annotations[0] = PART_TYPE_APPLICATION_XML;
351366 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
352 names = post("/post/form", output, MULTIPART_FORM_DATA, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
367 names = post(version, "/post/form", output, MULTIPART_FORM_DATA, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
353368 Assert.assertThat("Wrong count of customers from response", new Integer(names.size()), is(2));
354369 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bill")));
355370 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bob")));
362377 */
363378 @Test
364379 public void testPostList() throws Exception {
365 doTestPostList();
380 doTestPostList(Version.TWO);
381 doTestPostList(Version.THREE);
366382 }
367383
368384 @SuppressWarnings("unchecked")
369 public void doTestPostList() throws Exception {
385 public void doTestPostList(Version version) throws Exception {
370386 List<ContextProvidersCustomer> customers = new ArrayList<ContextProvidersCustomer>();
371387 customers.add(new ContextProvidersCustomer("Bill"));
372388 customers.add(new ContextProvidersCustomer("Bob"));
373389 Annotation[] annotations = new Annotation[1];
374390 annotations[0] = PART_TYPE_APPLICATION_XML;
375391 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
376 names = post("/post/list", customers, MULTIPART_MIXED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
392 names = post(version, "/post/list", customers, MULTIPART_MIXED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
377393 Assert.assertThat("Wrong count of customers from response", new Integer(names.size()), is(2));
378394 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bill")));
379395 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bob")));
386402 */
387403 @Test
388404 public void testPostMap() throws Exception {
389 doTestPostMap();
405 doTestPostMap(Version.TWO);
406 doTestPostMap(Version.THREE);
390407 }
391408
392409 @SuppressWarnings("unchecked")
393 public void doTestPostMap() throws Exception {
410 public void doTestPostMap(Version version) throws Exception {
394411 Map<String, ContextProvidersCustomer> customers = new HashMap<String, ContextProvidersCustomer>();
395412 customers.put("bill", new ContextProvidersCustomer("Bill"));
396413 customers.put("bob", new ContextProvidersCustomer("Bob"));
397414 Annotation[] annotations = new Annotation[1];
398415 annotations[0] = PART_TYPE_APPLICATION_XML;
399416 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
400 names = post("/post/map", customers, MULTIPART_FORM_DATA, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
417 names = post(version, "/post/map", customers, MULTIPART_FORM_DATA, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
401418 Assert.assertThat("Wrong count of customers from response", new Integer(names.size()), is(2));
402419 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("bill:Bill")));
403420 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("bob:Bob")));
410427 */
411428 @Test
412429 public void testPostRelated() throws Exception {
413 doTestPostRelated();
430 doTestPostRelated(Version.TWO);
431 doTestPostRelated(Version.THREE);
414432 }
415433
416434 @SuppressWarnings("unchecked")
417 void doTestPostRelated() throws Exception {
435 void doTestPostRelated(Version version) throws Exception {
418436 MultipartRelatedOutput output = new MultipartRelatedOutput();
419437 output.setStartInfo("text/html");
420438 output.addPart("Bill", new MediaType("image", "png"), "bill", "binary");
422440 Annotation[] annotations = new Annotation[1];
423441 annotations[0] = PART_TYPE_APPLICATION_XML;
424442 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
425 names = post("/post/related", output, MULTIPART_RELATED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
443 names = post(version, "/post/related", output, MULTIPART_RELATED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
426444 Assert.assertThat("Wrong count of customers from response", new Integer(names.size()), is(2));
427445 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bill")));
428446 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bob")));
435453 */
436454 @Test
437455 public void testPostMultipartForm() throws Exception {
438 doTestPostMultipartForm();
439 }
440
441 void doTestPostMultipartForm() throws Exception {
456 doTestPostMultipartForm(Version.TWO);
457 doTestPostMultipartForm(Version.THREE);
458 }
459
460 void doTestPostMultipartForm(Version version) throws Exception {
442461 ContextProvidersCustomerForm form = new ContextProvidersCustomerForm();
443462 form.setCustomer(new ContextProvidersCustomer("Bill"));
444463 Annotation[] annotations = new Annotation[1];
445464 annotations[0] = MULTIPART_FORM;
446 String name = post("/post/multipartform", form, MULTIPART_FORM_DATA, String.class, null, annotations);
465 String name = post(version, "/post/multipartform", form, MULTIPART_FORM_DATA, String.class, null, annotations);
447466 Assert.assertEquals("Wrong response", "Bill", name);
448467 }
449468
454473 */
455474 @Test
456475 public void testPostXop() throws Exception {
457 doTestPostXop();
458 }
459
460 void doTestPostXop() throws Exception {
476 doTestPostXop(Version.TWO);
477 doTestPostXop(Version.THREE);
478 }
479
480 void doTestPostXop(Version version) throws Exception {
461481 ContextProvidersXop xop = new ContextProvidersXop("hello world".getBytes());
462482 Annotation[] annotations = new Annotation[1];
463483 annotations[0] = XOP_WITH_MULTIPART_RELATED;
464 String s = post("/post/xop", xop, MULTIPART_RELATED, String.class, null, annotations);
484 String s = post(version, "/post/xop", xop, MULTIPART_RELATED, String.class, null, annotations);
465485 Assert.assertEquals("Wrong response", "hello world", s);
466486 }
467487
468 <T> T get(String path, Class<T> clazz) throws Exception {
469 return get(path, clazz, null);
470 }
471
472 <T> T get(String path, Class<T> clazz, Annotation[] annotations) throws Exception {
473 try {
474 Client client = ClientBuilder.newClient();
475 WebTarget target = client.target(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
476 Response response = target.request().get();
477 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
478 T entity = response.readEntity(clazz, annotations);
479 client.close();
480 return entity;
488 <T> T get(Version version, String path, Class<T> clazz) throws Exception {
489 return get(version, path, clazz, null);
490 }
491
492 <T> T get(Version version, String path, Class<T> clazz, Annotation[] annotations) throws Exception {
493 try {
494 switch (version) {
495 case TWO: {
496 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
497
498 ClientResponse<T> response = request.get(clazz);
499 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
500 T entity = response.getEntity(clazz, null, annotations);
501 return entity;
502 }
503
504 case THREE: {
505 Client client = ClientBuilder.newClient();
506 WebTarget target = client.target(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
507 Response response = target.request().get();
508 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
509 T entity = response.readEntity(clazz, annotations);
510 client.close();
511 return entity;
512 }
513
514 default:
515 throw new Exception("Unknown version of response: " + version);
516 }
481517 } catch (Exception e) {
482518 throw new RuntimeException(TestUtil.getErrorMessageForKnownIssue("RESTEASY-1119"), e);
483519 }
484520 }
485521
486522 @SuppressWarnings({"unchecked"})
487 <S, T> T post(String path, S payload, MediaType mediaType, Class<T> returnType, Type genericReturnType, Annotation[] annotations) throws Exception {
488 Client client = ClientBuilder.newClient();
489 WebTarget target = client.target(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
490 Entity<S> entity = Entity.entity(payload, mediaType, annotations);
491 Response response = target.request().post(entity);
492 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
493 T result = null;
494 if (genericReturnType != null) {
495 result = response.readEntity(new GenericType<T>(genericReturnType));
496 } else {
497 result = response.readEntity(returnType);
498 }
499 client.close();
500 return result;
523 <S, T> T post(Version version, String path, S payload, MediaType mediaType, Class<T> returnType, Type genericReturnType, Annotation[] annotations) throws Exception {
524 switch (version) {
525 case TWO: {
526 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
527 request.body(mediaType, payload, payload.getClass(), null, annotations);
528 ClientResponse<T> response = request.post();
529 T entity = null;
530 if (genericReturnType != null) {
531 entity = response.getEntity(returnType, genericReturnType);
532 } else {
533 entity = response.getEntity(returnType);
534 }
535
536 return entity;
537 }
538
539 case THREE: {
540 Client client = ClientBuilder.newClient();
541 WebTarget target = client.target(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
542 Entity<S> entity = Entity.entity(payload, mediaType, annotations);
543 Response response = target.request().post(entity);
544 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
545 T result = null;
546 if (genericReturnType != null) {
547 result = response.readEntity(new GenericType<T>(genericReturnType));
548 } else {
549 result = response.readEntity(returnType);
550 }
551 client.close();
552 return result;
553 }
554
555 default:
556 throw new Exception("Unknown version of response: " + version);
557 }
501558 }
502559
503560 public abstract static class S1 extends AnnotationLiteral<PartType> implements PartType {
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
57 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeEncodingOverwriteService;
6 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeEncodingOverwriteSetterContainerRequestFilter;
7 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteNewInterceptor;
8 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeEncodingOverwriteSetterPreProcessorInterceptor;
89 import org.jboss.resteasy.utils.PortProviderUtil;
910 import org.jboss.resteasy.utils.TestUtil;
1011 import org.jboss.shrinkwrap.api.Archive;
3940 WebArchive war = TestUtil.prepareArchive(InputPartDefaultContentTypeEncodingOverwriteTest.class.getSimpleName());
4041 war.addClasses(InputPartDefaultContentTypeEncodingOverwriteTest.class);
4142 war.addClasses(TestUtil.class, PortProviderUtil.class);
42 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultContentTypeEncodingOverwriteSetterContainerRequestFilter.class,
43 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultContentTypeEncodingOverwriteSetterPreProcessorInterceptor.class,
4344 InputPartDefaultContentTypeEncodingOverwriteService.class);
4445 }
4546
6364 private static final String TEST_URI = generateURL("");
6465
6566 /**
67 * @tpTestDetails Test for old client
68 * @tpSince RESTEasy 3.0.16
69 */
70 @Test
71 public void testContentTypeOldClient() throws Exception {
72 String message = "--boo\r\n"
73 + "Content-Disposition: form-data; name=\"foo\"\r\n"
74 + "Content-Transfer-Encoding: 8bit\r\n\r\n" + "bar\r\n"
75 + "--boo--\r\n";
76
77 ClientRequest request = new ClientRequest(TEST_URI + "/mime");
78 request.body("multipart/form-data; boundary=boo", message.getBytes());
79 ClientResponse<String> response = request.post(String.class);
80 Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10);
81 Assert.assertEquals("Response text is wrong",
82 MediaType.valueOf(TEXT_PLAIN_WITH_CHARSET_UTF_8),
83 MediaType.valueOf(response.getEntity()));
84 }
85
86 /**
6687 * @tpTestDetails Test for new client
6788 * @tpSince RESTEasy 3.0.16
6889 */
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteContainerBean;
8 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteOldInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteService;
10 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteXmlBean;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.AfterClass;
16 import org.junit.Assert;
17 import org.junit.BeforeClass;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.Client;
22 import javax.ws.rs.client.ClientBuilder;
23 import javax.ws.rs.client.Entity;
24 import javax.ws.rs.client.WebTarget;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @tpSubChapter Multipart provider
30 * @tpChapter Integration tests
31 * @tpTestCaseDetails MultiPart provider should be able to process xml, if wildcard is set. Wildcard is set in deprecated version of interceptor.
32 * @tpSince RESTEasy 3.0.16
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest {
37
38 public static final String WILDCARD_WITH_CHARSET_UTF_8 = MediaType.APPLICATION_XML + "; charset=UTF-8"; // this mediatype works correctly
39 private static Client client;
40
41 @Deployment
42 public static Archive<?> createTestArchive() {
43 WebArchive war = TestUtil.prepareArchive(InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.class.getSimpleName());
44 war.addClasses(InputPartDefaultContentTypeWildcardOverwriteContainerBean.class);
45 war.addClasses(InputPartDefaultContentTypeWildcardOverwriteXmlBean.class, InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.class);
46 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultContentTypeWildcardOverwriteOldInterceptor.class,
47 InputPartDefaultContentTypeWildcardOverwriteService.class);
48 }
49
50 @BeforeClass
51 public static void before() throws Exception
52 {
53 client = ClientBuilder.newClient();
54 }
55
56 @AfterClass
57 public static void after() throws Exception
58 {
59 client.close();
60 }
61
62 /**
63 * @tpTestDetails Test for old client
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testContentTypeOldClient() throws Exception {
68 String message = "--boo\r\n"
69 + "Content-Disposition: form-data; name=\"foo\"\r\n"
70 + "Content-Transfer-Encoding: 8bit\r\n\r\n"
71 + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
72 + "<inputPartDefaultContentTypeWildcardOverwriteXmlBean><myInt>27</myInt><myString>Lorem Ipsum</myString></inputPartDefaultContentTypeWildcardOverwriteXmlBean>\r\n"
73 + "--boo--\r\n";
74
75 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/mime", InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.class.getSimpleName()));
76
77 request.body("multipart/form-data; boundary=boo", message.getBytes("utf-8"));
78 ClientResponse<String> response = request.post(String.class);
79 Assert.assertEquals("MultiPart provider is unable to process xml, if media type is set in interceptor",
80 20, response.getStatus() / 10);
81 Assert.assertEquals("Response text is wrong", "27", response.getEntity());
82 }
83
84 /**
85 * @tpTestDetails Test for new client
86 * @tpSince RESTEasy 3.0.16
87 */
88 @Test
89 public void testContentTypeNewClient() throws Exception {
90 String message = "--boo\r\n"
91 + "Content-Disposition: form-data; name=\"foo\"\r\n"
92 + "Content-Transfer-Encoding: 8bit\r\n\r\n"
93 + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
94 + "<inputPartDefaultContentTypeWildcardOverwriteXmlBean><myInt>27</myInt><myString>Lorem Ipsum</myString></inputPartDefaultContentTypeWildcardOverwriteXmlBean>\r\n"
95 + "--boo--\r\n";
96
97
98 WebTarget target = client.target(PortProviderUtil.generateURL("/mime", InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.class.getSimpleName()));
99 Entity entity = Entity.entity(message, "multipart/form-data; boundary=boo");
100 Response response = target.request().post(entity);
101
102 Assert.assertEquals("MultiPart provider is unable to process xml, if media type is set in interceptor",
103 20, response.getStatus() / 10);
104 Assert.assertEquals("Response text is wrong", "27", response.readEntity(String.class));
105 }
106 }
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
57 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteContainerBean;
68 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteNewInterceptor;
79 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteService;
5961 }
6062
6163 /**
64 * @tpTestDetails Test for old client
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testContentTypeOldClient() throws Exception {
69 String message = "--boo\r\n"
70 + "Content-Disposition: form-data; name=\"foo\"\r\n"
71 + "Content-Transfer-Encoding: 8bit\r\n\r\n"
72 + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
73 + "<inputPartDefaultContentTypeWildcardOverwriteXmlBean><myInt>27</myInt><myString>Lorem Ipsum</myString></inputPartDefaultContentTypeWildcardOverwriteXmlBean>\r\n"
74 + "--boo--\r\n";
75
76 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/mime", InputPartDefaultContentTypeWildcardOverwriteNewInterceptorTest.class.getSimpleName()));
77
78 request.body("multipart/form-data; boundary=boo", message.getBytes("utf-8"));
79 ClientResponse<String> response = request.post(String.class);
80 Assert.assertEquals("MultiPart provider is unable to process xml, if media type is set in interceptor",
81 20, response.getStatus() / 10);
82 Assert.assertEquals("Response text is wrong", "27", response.getEntity());
83 }
84
85 /**
6286 * @tpTestDetails Test for new client
6387 * @tpSince RESTEasy 3.0.16
6488 */
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ProxyFactory;
56 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
67 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
78 import org.jboss.resteasy.test.providers.multipart.resource.MyServiceProxy;
6465 Assert.assertNull(bean.getSomeBinary());
6566 }
6667
68 /**
69 * @tpTestDetails Test old client
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test
73 public void testOldClient() throws Exception {
74 MyServiceProxy proxy = ProxyFactory.create(MyServiceProxy.class, generateBaseUrl());
75
76 NullPartBean bean = proxy.createMyBean(); // should just be ok
77 Assert.assertNotNull(bean);
78 Assert.assertNull(bean.getSomeBinary());
79 }
80
81
6782 }
00 package org.jboss.resteasy.test.providers.multipart.resource;
11
2 import java.io.IOException;
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
310
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerRequestFilter;
11 import javax.ws.rs.WebApplicationException;
612 import javax.ws.rs.ext.Provider;
713
8 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
1114 @Provider
12 public class InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16 implements ContainerRequestFilter {
13
14 @Override
15 public void filter(ContainerRequestContext requestContext) throws IOException
16 {
17 requestContext.setProperty(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_US_ASCII);
18 requestContext.setProperty(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_16);
19 }
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_US_ASCII);
19 request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_16);
20 return null;
21 }
2022 }
00 package org.jboss.resteasy.test.providers.multipart.resource;
11
2 import java.io.IOException;
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
310
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerRequestFilter;
11 import javax.ws.rs.WebApplicationException;
612 import javax.ws.rs.ext.Provider;
713
8 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
1114 @Provider
12 public class InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8 implements ContainerRequestFilter {
13
14 @Override
15 public void filter(ContainerRequestContext requestContext) throws IOException
16 {
17 requestContext.setProperty(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_US_ASCII);
18 requestContext.setProperty(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_8);
19 }
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_US_ASCII);
19 request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_8);
20 return null;
21 }
2022 }
00 package org.jboss.resteasy.test.providers.multipart.resource;
11
2 import java.io.IOException;
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
310
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerRequestFilter;
11 import javax.ws.rs.WebApplicationException;
612 import javax.ws.rs.ext.Provider;
713
8 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
1114 @Provider
12 public class InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16 implements ContainerRequestFilter {
13
14 @Override
15 public void filter(ContainerRequestContext requestContext) throws IOException
16 {
17 requestContext.setProperty(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_UTF_16);
18 }
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_UTF_16);
19 return null;
20 }
1921 }
00 package org.jboss.resteasy.test.providers.multipart.resource;
11
2 import java.io.IOException;
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
310
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerRequestFilter;
11 import javax.ws.rs.WebApplicationException;
612 import javax.ws.rs.ext.Provider;
713
8 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
1114 @Provider
12 public class InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8 implements ContainerRequestFilter {
13
14 @Override
15 public void filter(ContainerRequestContext requestContext) throws IOException
16 {
17 requestContext.setProperty(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_UTF_8);
18 }
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_UTF_8);
19 return null;
20 }
1921 }
00 package org.jboss.resteasy.test.providers.multipart.resource;
11
2 import java.io.IOException;
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
310
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerRequestFilter;
11 import javax.ws.rs.WebApplicationException;
612 import javax.ws.rs.ext.Provider;
713
8 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
1114 @Provider
12 public class InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16 implements ContainerRequestFilter {
13
14 @Override
15 public void filter(ContainerRequestContext requestContext) throws IOException
16 {
17 requestContext.setProperty(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_16);
18 }
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_16);
19 return null;
20 }
1921 }
00 package org.jboss.resteasy.test.providers.multipart.resource;
11
2 import java.io.IOException;
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
310
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerRequestFilter;
11 import javax.ws.rs.WebApplicationException;
612 import javax.ws.rs.ext.Provider;
713
8 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
1114 @Provider
12 public class InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8 implements ContainerRequestFilter {
13
14 @Override
15 public void filter(ContainerRequestContext requestContext) throws IOException
16 {
17 requestContext.setProperty(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_8);
18 }
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_8);
19 return null;
20 }
1921 }
+0
-22
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultContentTypeEncodingOverwriteSetterContainerRequestFilter.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import java.io.IOException;
3
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerRequestFilter;
6 import javax.ws.rs.ext.Provider;
7
8 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultContentTypeEncodingOverwriteTest;
10
11 @Provider
12 public class InputPartDefaultContentTypeEncodingOverwriteSetterContainerRequestFilter implements ContainerRequestFilter {
13
14 @Override
15 public void filter(ContainerRequestContext requestContext) throws IOException
16 {
17 requestContext.setProperty(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY,
18 InputPartDefaultContentTypeEncodingOverwriteTest.TEXT_PLAIN_WITH_CHARSET_UTF_8);
19 }
20
21 }
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultContentTypeEncodingOverwriteTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultContentTypeEncodingOverwriteSetterPreProcessorInterceptor implements
17 PreProcessInterceptor {
18
19 public ServerResponse preProcess(HttpRequest request,
20 ResourceMethodInvoker method) throws Failure, WebApplicationException {
21 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY,
22 InputPartDefaultContentTypeEncodingOverwriteTest.TEXT_PLAIN_WITH_CHARSET_UTF_8);
23 return null;
24 }
25
26 }
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultContentTypeWildcardOverwriteOldInterceptor implements
17 PreProcessInterceptor {
18
19
20 public ServerResponse preProcess(HttpRequest request,
21 ResourceMethodInvoker method) throws Failure, WebApplicationException {
22 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY,
23 InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.WILDCARD_WITH_CHARSET_UTF_8);
24 return null;
25 }
26
27 }
0 package org.jboss.resteasy.test.providers.priority;
1
2 import static org.junit.Assert.assertEquals;
3
4 import java.util.ArrayList;
5 import java.util.List;
6
7 import javax.ws.rs.client.WebTarget;
8 import javax.ws.rs.core.Response;
9
10 import org.jboss.arquillian.container.test.api.Deployment;
11 import org.jboss.arquillian.container.test.api.RunAsClient;
12 import org.jboss.arquillian.junit.Arquillian;
13 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
14 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
15 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityExceptionMapperAAA;
16 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityExceptionMapperBBB;
17 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityExceptionMapperCCC;
18 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFoo;
19 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFooParamConverter;
20 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFooParamConverterProviderAAA;
21 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFooParamConverterProviderBBB;
22 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFooParamConverterProviderCCC;
23 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityResource;
24 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityTestException;
25 import org.jboss.resteasy.utils.PortProviderUtil;
26 import org.jboss.resteasy.utils.TestUtil;
27 import org.jboss.shrinkwrap.api.Archive;
28 import org.jboss.shrinkwrap.api.spec.WebArchive;
29 import org.junit.After;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.junit.runner.RunWith;
33
34 /**
35 * @tpSubChapter ExceptionMappers and ParamConverterProviders
36 * @tpChapter Integration tests
37 * @tpSince RESTEasy 3.5
38 */
39 @RunWith(Arquillian.class)
40 @RunAsClient
41 public class ProviderPriorityProvidersInApplicationTest {
42
43 static ResteasyClient client;
44
45 @Deployment
46 public static Archive<?> deploy() {
47 WebArchive war = TestUtil.prepareArchive(ProviderPriorityProvidersInApplicationTest.class.getSimpleName());
48 war.addClasses(ProviderPriorityFoo.class,
49 ProviderPriorityFooParamConverter.class,
50 ProviderPriorityTestException.class
51 );
52 List<Class<?>> singletons = new ArrayList<Class<?>>();
53 singletons.add(ProviderPriorityExceptionMapperCCC.class);
54 singletons.add(ProviderPriorityFooParamConverterProviderCCC.class);
55 return TestUtil.finishContainerPrepare(war, null, singletons,
56 ProviderPriorityResource.class,
57 ProviderPriorityExceptionMapperAAA.class,
58 ProviderPriorityExceptionMapperBBB.class,
59 ProviderPriorityExceptionMapperCCC.class,
60 ProviderPriorityFooParamConverterProviderAAA.class,
61 ProviderPriorityFooParamConverterProviderBBB.class,
62 ProviderPriorityFooParamConverterProviderCCC.class
63 );
64 }
65
66 @Before
67 public void init() {
68 client = new ResteasyClientBuilder().build();
69 }
70
71 @After
72 public void after() throws Exception {
73 client.close();
74 }
75
76 private String generateURL(String path) {
77 return PortProviderUtil.generateURL(path, ProviderPriorityProvidersInApplicationTest.class.getSimpleName());
78 }
79
80 /**
81 * @tpTestDetails Tests that ExceptionMappers are sorted by priority
82 * @tpSince RESTEasy 3.5
83 */
84 // @Test
85 public void testExceptionMapper() throws Exception {
86 WebTarget base = client.target(generateURL("/exception"));
87 Response response = base.request().get();
88 assertEquals(444, response.getStatus());
89 assertEquals("CCC", response.readEntity(String.class));
90 }
91
92 /**
93 * @tpTestDetails Tests that ParamConverterProviders are sorted by priority
94 * @tpSince RESTEasy 3.5
95 */
96 @Test
97 public void testParamConverterProvider() throws Exception {
98 WebTarget base = client.target(generateURL("/paramconverter/dummy"));
99 Response response = base.request().get();
100 assertEquals(200, response.getStatus());
101 assertEquals("CCC", response.readEntity(String.class));
102 }
103 }
0 package org.jboss.resteasy.test.providers.priority;
1
2 import static org.junit.Assert.assertEquals;
3
4 import java.util.ArrayList;
5 import java.util.List;
6
7 import javax.ws.rs.client.WebTarget;
8 import javax.ws.rs.core.Response;
9
10 import org.jboss.arquillian.container.test.api.Deployment;
11 import org.jboss.arquillian.container.test.api.RunAsClient;
12 import org.jboss.arquillian.junit.Arquillian;
13 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
14 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
15 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityExceptionMapperAAA;
16 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityExceptionMapperBBB;
17 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityExceptionMapperCCC;
18 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFoo;
19 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFooParamConverter;
20 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFooParamConverterProviderAAA;
21 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFooParamConverterProviderBBB;
22 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityFooParamConverterProviderCCC;
23 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityResource;
24 import org.jboss.resteasy.test.providers.priority.resource.ProviderPriorityTestException;
25 import org.jboss.resteasy.utils.PortProviderUtil;
26 import org.jboss.resteasy.utils.TestUtil;
27 import org.jboss.shrinkwrap.api.Archive;
28 import org.jboss.shrinkwrap.api.spec.WebArchive;
29 import org.junit.After;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.junit.runner.RunWith;
33
34 /**
35 * @tpSubChapter ExceptionMappers and ParamConverterProviders registered programatically
36 * @tpChapter Integration tests
37 * @tpSince RESTEasy 3.5
38 */
39 @RunWith(Arquillian.class)
40 @RunAsClient
41 public class ProviderPriorityProvidersRegisteredProgramaticallyTest {
42
43 static ResteasyClient client;
44
45 @Deployment
46 public static Archive<?> deploy() {
47 WebArchive war = TestUtil.prepareArchive(ProviderPriorityProvidersRegisteredProgramaticallyTest.class.getSimpleName());
48 war.addClasses(ProviderPriorityFoo.class,
49 ProviderPriorityFooParamConverter.class,
50 ProviderPriorityTestException.class,
51 ProviderPriorityExceptionMapperCCC.class,
52 ProviderPriorityFooParamConverterProviderCCC.class
53 );
54 List<Class<?>> singletons = new ArrayList<Class<?>>();
55 singletons.add(ProviderPriorityExceptionMapperCCC.class);
56 singletons.add(ProviderPriorityFooParamConverterProviderCCC.class);
57 return TestUtil.finishContainerPrepare(war, null, singletons,
58 ProviderPriorityResource.class,
59 ProviderPriorityExceptionMapperAAA.class,
60 ProviderPriorityExceptionMapperBBB.class,
61 ProviderPriorityFooParamConverterProviderAAA.class,
62 ProviderPriorityFooParamConverterProviderBBB.class
63 );
64 }
65
66 @Before
67 public void init() {
68 client = new ResteasyClientBuilder().build();
69 }
70
71 @After
72 public void after() throws Exception {
73 client.close();
74 }
75
76 private String generateURL(String path) {
77 return PortProviderUtil.generateURL(path, ProviderPriorityProvidersRegisteredProgramaticallyTest.class.getSimpleName());
78 }
79
80 /**
81 * @tpTestDetails Tests that Programatically registered ExceptionMappers and
82 * ParamConverterProviders are sorted by priority
83 * @tpSince RESTEasy 3.5
84 */
85 @Test
86 public void testProgramaticRegistration() throws Exception {
87 WebTarget base = client.target(generateURL(""));
88 base.path("/register");
89 Response response = base.path("/register").request().get();
90 assertEquals(200, response.getStatus());
91 assertEquals("ok", response.readEntity(String.class));
92
93 response = base.path("/exception").request().get();
94 assertEquals(444, response.getStatus());
95 assertEquals("CCC", response.readEntity(String.class));
96
97 response = base.path("/paramconverter/dummy").request().get();
98 assertEquals(200, response.getStatus());
99 assertEquals("CCC", response.readEntity(String.class));
100 }
101 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class ProviderPriorityExceptionMapperAAA implements ExceptionMapper<ProviderPriorityTestException> {
8
9 @Override
10 public Response toResponse(ProviderPriorityTestException exception) {
11 return Response.ok().status(444).entity("AAA").build();
12 }
13 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.core.Response;
4 import javax.ws.rs.ext.ExceptionMapper;
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 @Priority(20)
9 public class ProviderPriorityExceptionMapperBBB implements ExceptionMapper<ProviderPriorityTestException> {
10
11 @Override
12 public Response toResponse(ProviderPriorityTestException exception) {
13 return Response.ok().status(444).entity("BBB").build();
14 }
15 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.core.Response;
4 import javax.ws.rs.ext.ExceptionMapper;
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 @Priority(10)
9 public class ProviderPriorityExceptionMapperCCC implements ExceptionMapper<ProviderPriorityTestException> {
10
11 @Override
12 public Response toResponse(ProviderPriorityTestException exception) {
13 return Response.ok().status(444).entity("CCC").build();
14 }
15 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 public class ProviderPriorityFoo {
3 private String foo;
4
5 public ProviderPriorityFoo(String foo) {this.foo = foo;}
6
7 public String getFoo() {return foo;}
8 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 import javax.ws.rs.ext.ParamConverter;
3
4 public class ProviderPriorityFooParamConverter implements ParamConverter<ProviderPriorityFoo> {
5 private String foo;
6
7 public ProviderPriorityFooParamConverter(String foo) {
8 this.foo = foo;
9 }
10
11 @Override
12 public ProviderPriorityFoo fromString(String value)
13 {
14 return new ProviderPriorityFoo(foo);
15 }
16
17 @Override
18 public String toString(ProviderPriorityFoo value)
19 {
20 return value.getFoo();
21 }
22 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4
5 import javax.ws.rs.ext.ParamConverter;
6 import javax.ws.rs.ext.ParamConverterProvider;
7 import javax.ws.rs.ext.Provider;
8
9 @Provider
10 public class ProviderPriorityFooParamConverterProviderAAA implements ParamConverterProvider {
11
12 @SuppressWarnings("unchecked")
13 @Override
14 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
15 return (ParamConverter<T>) new ProviderPriorityFooParamConverter("AAA");
16 }
17 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4
5 import javax.annotation.Priority;
6 import javax.ws.rs.ext.ParamConverter;
7 import javax.ws.rs.ext.ParamConverterProvider;
8 import javax.ws.rs.ext.Provider;
9
10 @Provider
11 @Priority(20)
12 public class ProviderPriorityFooParamConverterProviderBBB implements ParamConverterProvider {
13
14 @SuppressWarnings("unchecked")
15 @Override
16 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
17 return (ParamConverter<T>) new ProviderPriorityFooParamConverter("BBB");
18 }
19 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4
5 import javax.annotation.Priority;
6 import javax.ws.rs.ext.ParamConverter;
7 import javax.ws.rs.ext.ParamConverterProvider;
8 import javax.ws.rs.ext.Provider;
9
10 @Provider
11 @Priority(10)
12 public class ProviderPriorityFooParamConverterProviderCCC implements ParamConverterProvider {
13
14 @SuppressWarnings("unchecked")
15 @Override
16 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
17 return (ParamConverter<T>) new ProviderPriorityFooParamConverter("CCC");
18 }
19 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 import javax.enterprise.context.RequestScoped;
3 import javax.inject.Inject;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.core.Response;
8
9 import org.jboss.resteasy.spi.ResteasyProviderFactory;
10
11 @RequestScoped
12 @Path("")
13 public class ProviderPriorityResource {
14
15 @Inject ProviderPriorityFooParamConverterProviderCCC paramConvertrProvider;
16 @Inject ProviderPriorityExceptionMapperCCC exceptionMapper;
17
18 @GET
19 @Path("exception")
20 public Response exception() throws Exception {
21 throw new ProviderPriorityTestException();
22 }
23
24 @GET
25 @Path("paramconverter/{foo}")
26 public String paramConverter(@PathParam("foo") ProviderPriorityFoo foo) throws Exception {
27 return foo.getFoo();
28 }
29
30
31 @GET
32 @Path("register")
33 public Response register() throws Exception {
34 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
35 factory.registerProviderInstance(paramConvertrProvider);
36 factory.registerProviderInstance(exceptionMapper);
37 return Response.ok("ok").build();
38 }
39 }
0 package org.jboss.resteasy.test.providers.priority.resource;
1
2 public class ProviderPriorityTestException extends Exception {
3 private static final long serialVersionUID = 1L;
4 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.io.IOException;
3 import java.util.concurrent.ExecutorService;
4
5 import javax.ws.rs.DELETE;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.container.ResourceContext;
11 import javax.ws.rs.core.Context;
12 import javax.ws.rs.core.MediaType;
13 import javax.ws.rs.sse.Sse;
14 import javax.ws.rs.sse.SseBroadcaster;
15 import javax.ws.rs.sse.SseEventSink;
16
17 @Path("/sse")
18 public class AnotherSseResource
19 {
20
21 private final Object outputLock = new Object();
22 private final Object sseBroadcasterLock = new Object();
23
24 @Context
25 private Sse sse;
26
27 private volatile SseEventSink eventSink;
28
29 private volatile SseBroadcaster sseBroadcaster;
30
31 private final SseResource sseResource;
32
33 public AnotherSseResource(SseResource sseResource) {
34 this.sseResource = sseResource;
35 }
36
37 @GET
38 @Path("/subscribe")
39 @Produces(MediaType.SERVER_SENT_EVENTS)
40 public void subscribe(@Context SseEventSink sink) throws IOException
41 {
42
43 if (sink == null)
44 {
45 throw new IllegalStateException("No client connected.");
46 }
47 eventSink = sink;
48 synchronized (this.sseBroadcasterLock) {
49 //subscribe
50 if (sseBroadcaster == null)
51 {
52 sseBroadcaster = sse.newBroadcaster();
53 }
54 }
55 this.sseResource.subscribe(sink);
56 sseBroadcaster.register(sink);
57 }
58
59 @POST
60 @Path("/broadcast")
61 public void broadcast(String message) throws IOException
62 {
63 if (this.sseBroadcaster == null)
64 {
65 throw new IllegalStateException("No Sse broadcaster created.");
66 }
67 this.sseBroadcaster.broadcast(sse.newEvent(message));
68 }
69
70 @DELETE
71 @Produces(MediaType.TEXT_PLAIN)
72 public boolean close() throws IOException
73 {
74 synchronized (outputLock)
75 {
76 if (eventSink != null)
77 {
78 try (SseEventSink sink = eventSink)
79 {
80 //do nothing and this is intented to test eventSink's try-with-resources autoCloseable
81 }
82 }
83 }
84 return eventSink.isClosed();
85 }
86
87 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.io.IOException;
3
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerResponseContext;
6 import javax.ws.rs.container.ContainerResponseFilter;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.Provider;
9
10 @Provider
11 public class CORSFilter implements ContainerResponseFilter
12 {
13 @Override
14 public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
15 {
16 MultivaluedMap<String, Object> headers = response.getHeaders();
17 headers.add("Access-Control-Allow-Origin", "*");
18 headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
19 headers.add("Access-Control-Allow-Credentials", "true");
20 headers.add("Access-Control-Max-Age", "1209600");
21 headers.add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, ETag, if-none-match");
22 headers.add("Access-Control-Expose-Headers", "origin, content-type, accept, authorization, ETag, if-none-match");
23 headers.add("x-foo-by", "rs");
24 }
25 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.io.IOException;
3 import java.util.concurrent.CompletableFuture;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.sse.Sse;
11 import javax.ws.rs.sse.SseEventSink;
12
13 @Path("/sse-escaping")
14 public class EscapingSseResource
15 {
16
17 @Context
18 private Sse sse;
19
20 @GET
21 @Produces(MediaType.SERVER_SENT_EVENTS)
22 public void subscribe(@Context SseEventSink sink) throws IOException
23 {
24
25 if (sink == null)
26 {
27 throw new IllegalStateException("No client connected.");
28 }
29 try (SseEventSink s = sink)
30 {
31 CompletableFuture.allOf(s.send(sse.newEvent("foo1\nbar")).toCompletableFuture(),
32 s.send(sse.newEvent("foo2\r\nbar")).toCompletableFuture(),
33 s.send(sse.newEvent("foo3\rbar")).toCompletableFuture()).get();
34 }
35 catch (Exception e)
36 {
37 throw new IOException(e);
38 }
39 }
40 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.concurrent.ExecutorService;
3 import java.util.concurrent.Executors;
4 import java.util.concurrent.TimeUnit;
5
6 import javax.servlet.ServletContextEvent;
7 import javax.servlet.ServletContextListener;
8 import javax.servlet.annotation.WebListener;
9
10 import org.jboss.logging.Logger;
11
12 @WebListener
13 public class ExecutorServletContextListener implements ServletContextListener
14 {
15
16 public static final String TEST_EXECUTOR = "testExecutor";
17
18 private final static Logger logger = Logger.getLogger(ExecutorServletContextListener.class);
19
20 private ExecutorService executors = null;
21
22 @Override
23 public void contextInitialized(ServletContextEvent sce)
24 {
25 executors = Executors.newCachedThreadPool();
26 sce.getServletContext().setAttribute(TEST_EXECUTOR, executors);
27
28 }
29
30 @Override
31 public void contextDestroyed(ServletContextEvent sce)
32 {
33 Object executors = sce.getServletContext().getAttribute(TEST_EXECUTOR);
34 if (executors != null)
35 {
36 ExecutorService service = ((ExecutorService) executors);
37 service.shutdownNow();
38 try
39 {
40 if (!service.awaitTermination(10, TimeUnit.SECONDS))
41 {
42 logger.warn("ExecutorService for server sent events isn't termitted in 10 secs");
43 }
44 }
45 catch (InterruptedException e)
46 {
47 //
48 }
49 }
50
51 }
52
53 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 public class GreenHouse
3 {
4 private long timestamp;
5
6 private int temperature;
7
8 private int humidity;
9
10 public GreenHouse()
11 {
12 }
13
14 public GreenHouse(long timestamp, int temperature, int humidity)
15 {
16 this.timestamp = timestamp;
17 this.temperature = temperature;
18 this.humidity = humidity;
19 }
20
21 public long getTimestamp()
22 {
23 return timestamp;
24 }
25
26 public void setTimestamp(long timestamp)
27 {
28 this.timestamp = timestamp;
29 }
30
31 public int getTempe()
32 {
33 return temperature;
34 }
35
36 public void setTempe(int temperature)
37 {
38 this.temperature = temperature;
39 }
40
41 public int getHumid()
42 {
43 return humidity;
44 }
45
46 public void setHumid(int humidity)
47 {
48 this.humidity = humidity;
49 }
50 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.HashSet;
3 import java.util.Set;
4
5 import javax.ws.rs.core.Application;
6 import javax.ws.rs.ext.Provider;
7
8 @Provider
9 public class SseApplication extends Application
10 {
11 private Set<Object> singletons = new HashSet<Object>();
12
13 public Set<Object> getSingletons()
14 {
15 if (singletons.isEmpty())
16 {
17 SseResource sseResource = new SseResource();
18 singletons.add(sseResource);
19 singletons.add(new AnotherSseResource(sseResource));
20 singletons.add(new EscapingSseResource());
21 }
22 return singletons;
23 }
24
25 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import javax.ws.rs.client.Client;
3 import javax.ws.rs.client.ClientBuilder;
4 import javax.ws.rs.client.Invocation;
5 import javax.ws.rs.client.WebTarget;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.Response;
8
9 import org.jboss.arquillian.container.test.api.Deployment;
10 import org.jboss.arquillian.container.test.api.RunAsClient;
11 import org.jboss.arquillian.junit.Arquillian;
12 import org.jboss.resteasy.category.Jaxrs21;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Assert;
19 import org.junit.Test;
20 import org.junit.experimental.categories.Category;
21 import org.junit.runner.RunWith;
22
23 @RunWith(Arquillian.class)
24 @RunAsClient
25 @Category(Jaxrs21.class)
26 public class SseCORSFilterTest
27 {
28 @Deployment
29 public static Archive<?> deploy()
30 {
31 WebArchive war = TestUtil.prepareArchive(SseCORSFilterTest.class.getSimpleName());
32 war.addClass(SseCORSFilterTest.class);
33 war.addAsWebInfResource("org/jboss/resteasy/test/providers/sse/filter/web.xml", "web.xml");
34 war.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
35 return TestUtil.finishContainerPrepare(war, null, SseFilterApplication.class, SseResource.class,
36 CORSFilter.class, ExecutorServletContextListener.class);
37 }
38
39 private String generateURL(String path)
40 {
41 return PortProviderUtil.generateURL(path, SseCORSFilterTest.class.getSimpleName());
42 }
43
44 @Test
45 public void testSseEventWithFilter() throws Exception
46 {
47
48 Client client = ClientBuilder.newClient();
49 WebTarget target = client.target(generateURL("/service/server-sent-events/events"));
50 Response response = target.request().get();
51 Assert.assertEquals("response OK is expected", 200, response.getStatus());
52 Assert.assertTrue("CORS http header is expected in event response",
53 response.getHeaders().get("Access-Control-Allow-Origin").contains("*"));
54 Assert.assertEquals("text/event-stream is expected", response.getMediaType(), MediaType.SERVER_SENT_EVENTS_TYPE);
55
56 Client isOpenClient = ClientBuilder.newClient();
57 Invocation.Builder isOpenRequest = isOpenClient.target(generateURL("/service/server-sent-events/isopen"))
58 .request();
59 javax.ws.rs.core.Response isOpenResponse = isOpenRequest.get();
60 Assert.assertTrue("EventSink open is expected ", isOpenResponse.readEntity(Boolean.class));
61 Assert.assertTrue("CORS http header is expected in isOpenResponse",
62 isOpenResponse.getHeaders().get("Access-Control-Allow-Origin").contains("*"));
63 isOpenClient.close();
64 client.close();
65 }
66 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.concurrent.CountDownLatch;
3 import java.util.concurrent.TimeUnit;
4
5 import javax.ws.rs.client.Client;
6 import javax.ws.rs.client.ClientBuilder;
7 import javax.ws.rs.client.WebTarget;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Response;
10 import javax.ws.rs.core.Response.Status;
11 import javax.ws.rs.sse.SseEventSource;
12
13 import org.jboss.arquillian.container.test.api.Deployment;
14 import org.jboss.arquillian.container.test.api.RunAsClient;
15 import org.jboss.arquillian.junit.Arquillian;
16 import org.jboss.resteasy.category.Jaxrs21;
17 import org.jboss.resteasy.utils.PortProviderUtil;
18 import org.jboss.resteasy.utils.TestUtil;
19 import org.jboss.shrinkwrap.api.Archive;
20 import org.jboss.shrinkwrap.api.spec.WebArchive;
21 import org.junit.Assert;
22 import org.junit.Test;
23 import org.junit.experimental.categories.Category;
24 import org.junit.runner.RunWith;
25
26 /**
27 *
28 * @author Nicolas NESMON
29 *
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 @Category(Jaxrs21.class)
34 public class SseEnablingTest {
35
36 @Deployment
37 public static Archive<?> deploy() {
38 WebArchive war = TestUtil.prepareArchive(SseEnablingTest.class.getSimpleName());
39 war.addClass(SseEnablingTestResource.class);
40 return TestUtil.finishContainerPrepare(war, null, SseEnablingTestResource.class);
41 }
42
43 private String generateURL() {
44 return PortProviderUtil.generateBaseUrl(SseEnablingTest.class.getSimpleName());
45 }
46
47 // Client
48 // Accept: application/xml, text/event-stream
49 //
50 // Server
51 // @GET
52 // @Produces(MediaType.APPLICATION_XML)
53 // public Response resourceMethod(@Context SseEventSink sseEventSink){
54 // ...
55 // }
56 @Test
57 public void testAcceptXmlSseServerXml() throws Exception {
58 Client client = ClientBuilder.newClient();
59 try {
60 WebTarget baseTarget = client.target(generateURL()).path(SseEnablingTestResource.PATH);
61 try (Response response = baseTarget.path(SseEnablingTestResource.RESOURCE_METHOD_1_PATH)
62 .request(MediaType.APPLICATION_XML_TYPE, MediaType.SERVER_SENT_EVENTS_TYPE).get()) {
63 checkResponse(response);
64 }
65 } finally {
66 client.close();
67 }
68 }
69
70 // Client
71 // Accept: application/xml;q=0.9, text/event-stream;q=0.5
72 //
73 // Server
74 // @GET
75 // @Produces({MediaType.APPLICATION_XML, MediaType.SERVER_SENT_EVENTS})
76 // public Response resourceMethod(@Context SseEventSink sseEventSink){
77 // ...
78 // }
79 @Test
80 public void testSseAcceptWithQualityFactors() throws Exception {
81 Client client = ClientBuilder.newClient();
82 try {
83 WebTarget baseTarget = client.target(generateURL()).path(SseEnablingTestResource.PATH);
84 try (Response response = baseTarget.path(SseEnablingTestResource.RESOURCE_METHOD_2_PATH)
85 .request("application/xml;q=0.9", "text/event-stream;q=0.5").get()) {
86 checkResponse(response);
87 }
88 } finally {
89 client.close();
90 }
91 }
92
93 // Client
94 // Accept: application/xml, text/event-stream
95 //
96 // Server
97 // @GET
98 // @Produces({"application/xml;qs=0.9", "text/event-stream;qs=0.5"})
99 // public Response resourceMethod(@Context SseEventSink sseEventSink){
100 // ...
101 // }
102 @Test
103 public void testSseServerQualityFactors() throws Exception {
104 Client client = ClientBuilder.newClient();
105 try {
106 WebTarget baseTarget = client.target(generateURL()).path(SseEnablingTestResource.PATH);
107 try (Response response = baseTarget.path(SseEnablingTestResource.RESOURCE_METHOD_3_PATH)
108 .request(MediaType.APPLICATION_XML_TYPE, MediaType.SERVER_SENT_EVENTS_TYPE).get()) {
109 checkResponse(response);
110 }
111 } finally {
112 client.close();
113 }
114 }
115
116 // Client
117 // Accept: application/xml;q=0.9, application/json;q=0.5
118 //
119 // Server
120 // @GET
121 // @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,
122 // MediaType.SERVER_SENT_EVENTS})
123 // public Response resourceMethod(@Context SseEventSink sseEventSink){
124 // ...
125 // }
126 @Test
127 public void testAcceptXmlJsonServerXmlJsonSse() throws Exception {
128 Client client = ClientBuilder.newClient();
129 try {
130 WebTarget baseTarget = client.target(generateURL()).path(SseEnablingTestResource.PATH);
131 try (Response response = baseTarget.path(SseEnablingTestResource.RESOURCE_METHOD_4_PATH)
132 .request("application/xml;q=0.9", "application/json;q=0.5").get()) {
133 checkResponse(response);
134 }
135 } finally {
136 client.close();
137 }
138 }
139
140 // Client
141 // Accept: text/event-stream
142 //
143 // Server
144 // @GET
145 // @Produces(MediaType.SERVER_SENT_EVENTS)
146 // public Response resourceMethod(){
147 // ...
148 // }
149 @Test
150 public void testAcceptSseServerSseNoContent() throws Exception {
151 Client client = ClientBuilder.newClient();
152 try {
153 WebTarget baseTarget = client.target(generateURL()).path(SseEnablingTestResource.PATH);
154 int responseSTatus = baseTarget.path(SseEnablingTestResource.RESOURCE_METHOD_5_PATH)
155 .request(MediaType.SERVER_SENT_EVENTS_TYPE).get().getStatus();
156 Assert.assertEquals(Status.NO_CONTENT.getStatusCode(), responseSTatus);
157 } finally {
158 client.close();
159 }
160 }
161
162 // Client
163 // Accept: text/event-stream
164 //
165 // Server
166 // @GET
167 // @Produces(MediaType.SERVER_SENT_EVENTS)
168 // public void resourceMethod(@Context SseEventSink sseEventSink){
169 // ...
170 // }
171 @Test
172 public void testAcceptSseServerSseEvent() throws Exception {
173
174 Client client = ClientBuilder.newClient();
175 try {
176 WebTarget baseTarget = client.target(generateURL()).path(SseEnablingTestResource.PATH);
177 try (SseEventSource eventSource = SseEventSource
178 .target(baseTarget.path(SseEnablingTestResource.RESOURCE_METHOD_6_PATH)).build()) {
179 CountDownLatch countDownLatch = new CountDownLatch(1);
180 eventSource.register(event -> {
181 countDownLatch.countDown();
182 }, e -> {
183 throw new RuntimeException(e);
184 });
185 eventSource.open();
186 boolean result = countDownLatch.await(30, TimeUnit.SECONDS);
187 Assert.assertTrue("Waiting for event to be delivered has timed out.", result);
188 }
189 } finally {
190 client.close();
191 }
192 }
193
194 private void checkResponse(Response response) {
195 Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());
196 MediaType contentType = response.getMediaType();
197 Assert.assertEquals(MediaType.APPLICATION_XML_TYPE.getType(), contentType.getType());
198 Assert.assertEquals(MediaType.APPLICATION_XML_TYPE.getSubtype(), contentType.getSubtype());
199 Assert.assertEquals(SseEnablingTestResource.OK_MESSAGE, response.readEntity(String.class));
200 }
201
202 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.InternalServerErrorException;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.Context;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.Response;
9 import javax.ws.rs.sse.Sse;
10 import javax.ws.rs.sse.SseEventSink;
11
12 /**
13 *
14 * @author Nicolas NESMON
15 *
16 */
17 @Path(SseEnablingTestResource.PATH)
18 public class SseEnablingTestResource {
19
20 public static final String PATH = "sseEnablingTest";
21 public static final String RESOURCE_METHOD_1_PATH = "resourceMethod1";
22 public static final String RESOURCE_METHOD_2_PATH = "resourceMethod2";
23 public static final String RESOURCE_METHOD_3_PATH = "resourceMethod3";
24 public static final String RESOURCE_METHOD_4_PATH = "resourceMethod4";
25 public static final String RESOURCE_METHOD_5_PATH = "resourceMethod5";
26 public static final String RESOURCE_METHOD_6_PATH = "resourceMethod6";
27
28 public static String OK_MESSAGE = "OK";
29
30 // Will be called by client with "Accept: application/xml,
31 // text/event-stream"
32 @Path(RESOURCE_METHOD_1_PATH)
33 @GET
34 @Produces(MediaType.APPLICATION_XML)
35 public Response resourceMethod_1(@Context SseEventSink sseEventSink) {
36 if (sseEventSink == null) {
37 return Response.ok(OK_MESSAGE).build();
38 }
39 throw new InternalServerErrorException();
40 }
41
42 // Will be called by client with "Accept: application/xml;q=0.9,
43 // text/event-stream;q=0.5"
44 @Path(RESOURCE_METHOD_2_PATH)
45 @GET
46 @Produces({ MediaType.APPLICATION_XML, MediaType.SERVER_SENT_EVENTS })
47 public Response resourceMethod_2(@Context SseEventSink sseEventSink) {
48 if (sseEventSink == null) {
49 return Response.ok(OK_MESSAGE).build();
50 }
51 throw new InternalServerErrorException();
52 }
53
54 // Will be called by client with "Accept: application/xml,
55 // text/event-stream"
56 @Path(RESOURCE_METHOD_3_PATH)
57 @GET
58 @Produces({ "application/xml;qs=0.9", "text/event-stream;qs=0.5" })
59 public Response resourceMethod_3(@Context SseEventSink sseEventSink) {
60 if (sseEventSink == null) {
61 return Response.ok(OK_MESSAGE).build();
62 }
63 throw new InternalServerErrorException();
64 }
65
66 // Will be called by client with "Accept: application/xml;q=0.9,
67 // application/json;q=0.5"
68 @Path(RESOURCE_METHOD_4_PATH)
69 @GET
70 @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.SERVER_SENT_EVENTS })
71 public Response resourceMethod_4(@Context SseEventSink sseEventSink) {
72 if (sseEventSink == null) {
73 return Response.ok(OK_MESSAGE).build();
74 }
75 throw new InternalServerErrorException();
76 }
77
78 // Will be called by client with "Accept: text/event-stream"
79 @Path(RESOURCE_METHOD_5_PATH)
80 @GET
81 @Produces(MediaType.SERVER_SENT_EVENTS)
82 public Response resourceMethod_5() {
83 return Response.noContent().build();
84 }
85
86 // Will be called by client with "Accept: text/event-stream"
87 @Path(RESOURCE_METHOD_6_PATH)
88 @GET
89 @Produces(MediaType.SERVER_SENT_EVENTS)
90 public void resourceMethod_6(@Context SseEventSink sseEventSink, @Context Sse sse) {
91 sseEventSink.send(sse.newEvent("data"));
92 sseEventSink.close();
93 }
94
95 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.Arrays;
3
4 import javax.ws.rs.client.Client;
5 import javax.ws.rs.client.ClientBuilder;
6 import javax.ws.rs.client.WebTarget;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.Response;
9 import javax.ws.rs.core.Response.Status;
10
11 import org.jboss.arquillian.container.test.api.Deployment;
12 import org.jboss.arquillian.container.test.api.RunAsClient;
13 import org.jboss.arquillian.junit.Arquillian;
14 import org.jboss.logging.Logger;
15 import org.jboss.resteasy.category.Jaxrs21;
16 import org.jboss.resteasy.utils.PortProviderUtil;
17 import org.jboss.resteasy.utils.TestUtil;
18 import org.jboss.shrinkwrap.api.Archive;
19 import org.jboss.shrinkwrap.api.spec.WebArchive;
20 import org.junit.After;
21 import org.junit.Assert;
22 import org.junit.Test;
23 import org.junit.experimental.categories.Category;
24 import org.junit.runner.RunWith;
25
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 @Category(Jaxrs21.class)
29 public class SseEventSinkClosingTest {
30
31 @Deployment
32 public static Archive<?> deploy() {
33 WebArchive war = TestUtil.prepareArchive(SseEventSinkClosingTest.class.getSimpleName());
34 war.addClass(SseEventSinkClosingTestResource.class);
35 war.addClass(SseEventSinkClosingTestResource.ContainerFilter.class);
36 return TestUtil.finishContainerPrepare(war, null, Arrays.asList(SseEventSinkClosingTestResource.class),
37 SseEventSinkClosingTestResource.ContainerFilter.class);
38 }
39
40 private String generateURL() {
41 return PortProviderUtil.generateBaseUrl(SseEventSinkClosingTest.class.getSimpleName());
42 }
43
44 @After
45 public void reset() throws Exception {
46 Client client = ClientBuilder.newClient();
47 try {
48 client.target(generateURL()).path(SseEventSinkClosingTestResource.BASE_PATH)
49 .path(SseEventSinkClosingTestResource.RESET_RESPONSE_FILTER_INVOCATION_COUNT_PATH).request()
50 .delete();
51 } finally {
52 client.close();
53 }
54 }
55
56 @Test
57 public void testFilterForEventSent() throws Exception {
58
59 Client client = ClientBuilder.newClient();
60 try {
61
62 WebTarget baseTarget = client.target(generateURL()).path(SseEventSinkClosingTestResource.BASE_PATH);
63
64 try (Response response = baseTarget.path(SseEventSinkClosingTestResource.SEND_AND_CLOSE_PATH)
65 .request(MediaType.SERVER_SENT_EVENTS_TYPE).get()) {
66 Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());
67 }
68
69 try (Response response = baseTarget
70 .path(SseEventSinkClosingTestResource.GET_RESPONSE_FILTER_INVOCATION_COUNT_PATH)
71 .request(MediaType.TEXT_PLAIN_TYPE).get()) {
72 Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());
73 Assert.assertEquals(Integer.valueOf(1), response.readEntity(Integer.class));
74 }
75
76 } finally {
77 client.close();
78 }
79
80 }
81
82 @Test
83 public void testFilterForMethodReturn() throws Exception {
84
85 Client client = ClientBuilder.newClient();
86 try {
87
88 WebTarget baseTarget = client.target(generateURL()).path(SseEventSinkClosingTestResource.BASE_PATH);
89
90 try (Response response = baseTarget.path(SseEventSinkClosingTestResource.CLOSE_WITHOUT_SENDING_PATH)
91 .request(MediaType.SERVER_SENT_EVENTS_TYPE).get()) {
92 Assert.assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
93 }
94
95 try (Response response = baseTarget
96 .path(SseEventSinkClosingTestResource.GET_RESPONSE_FILTER_INVOCATION_COUNT_PATH)
97 .request(MediaType.TEXT_PLAIN_TYPE).get()) {
98 Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());
99 Assert.assertEquals(Integer.valueOf(1), response.readEntity(Integer.class));
100 }
101
102 } finally {
103 client.close();
104 }
105
106 }
107
108 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.io.IOException;
3 import java.util.concurrent.atomic.AtomicInteger;
4
5 import javax.ws.rs.DELETE;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.container.ContainerRequestContext;
10 import javax.ws.rs.container.ContainerRequestFilter;
11 import javax.ws.rs.container.ContainerResponseContext;
12 import javax.ws.rs.container.ContainerResponseFilter;
13 import javax.ws.rs.core.Context;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.core.Response;
16 import javax.ws.rs.ext.Provider;
17 import javax.ws.rs.sse.Sse;
18 import javax.ws.rs.sse.SseEventSink;
19
20 import org.jboss.resteasy.spi.ResteasyProviderFactory;
21
22 /**
23 *
24 * @author Nicolas NESMON
25 *
26 */
27 @Path(SseEventSinkClosingTestResource.BASE_PATH)
28 public class SseEventSinkClosingTestResource {
29
30 @Provider
31 public static class ContainerFilter implements ContainerRequestFilter, ContainerResponseFilter {
32
33 @Override
34 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
35 throws IOException {
36 AtomicInteger responseFilterInvocationCounter = (AtomicInteger) requestContext
37 .getProperty(RESPONSE_FILTER_INVOCATION_COUNTER_PROPERTY);
38 if (responseFilterInvocationCounter != null) {
39 responseFilterInvocationCounter.incrementAndGet();
40 }
41 }
42
43 @Override
44 public void filter(ContainerRequestContext containerRequestContext) throws IOException {
45 ResteasyProviderFactory.pushContext(ContainerRequestContext.class, containerRequestContext);
46 }
47
48 }
49
50 public static final String BASE_PATH = "sseEventSinkClosing";
51 public static final String SEND_AND_CLOSE_PATH = "sendAndClose";
52 public static final String CLOSE_WITHOUT_SENDING_PATH = "closeWithoutSending";
53 public static final String GET_RESPONSE_FILTER_INVOCATION_COUNT_PATH = "getResponseFilterInvocationCount";
54 public static final String RESET_RESPONSE_FILTER_INVOCATION_COUNT_PATH = "resetResponseFilterInvocationCount";
55
56 private static final String RESPONSE_FILTER_INVOCATION_COUNTER_PROPERTY = "counter";
57
58 private final AtomicInteger responseFilterCountInvocation = new AtomicInteger();
59
60 @GET
61 @Path(SEND_AND_CLOSE_PATH)
62 @Produces(MediaType.SERVER_SENT_EVENTS)
63 public void sendAndClose(@Context ContainerRequestContext requestContext, @Context Sse sse,
64 @Context SseEventSink sseEventSink) {
65 requestContext.setProperty(RESPONSE_FILTER_INVOCATION_COUNTER_PROPERTY, this.responseFilterCountInvocation);
66 sseEventSink.send(sse.newEvent("message"));
67 sseEventSink.close();
68 }
69
70 @GET
71 @Path(CLOSE_WITHOUT_SENDING_PATH)
72 @Produces(MediaType.SERVER_SENT_EVENTS)
73 public void closedWithoutSending(@Context ContainerRequestContext requestContext, @Context Sse sse,
74 @Context SseEventSink sseEventSink) {
75 requestContext.setProperty(RESPONSE_FILTER_INVOCATION_COUNTER_PROPERTY, this.responseFilterCountInvocation);
76 sseEventSink.close();
77 }
78
79 @GET
80 @Path(GET_RESPONSE_FILTER_INVOCATION_COUNT_PATH)
81 @Produces(MediaType.TEXT_PLAIN)
82 public Response getResponseFilterInvocationCount() {
83 return Response.ok(this.responseFilterCountInvocation.get()).build();
84 }
85
86 @DELETE
87 @Path(RESET_RESPONSE_FILTER_INVOCATION_COUNT_PATH)
88 public void resetResponseFilterInvocationCount() {
89 this.responseFilterCountInvocation.set(0);
90 }
91
92 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.ArrayList;
3 import java.util.List;
4 import java.util.concurrent.CountDownLatch;
5 import java.util.concurrent.TimeUnit;
6 import java.util.concurrent.atomic.AtomicInteger;
7
8 import javax.ws.rs.client.Client;
9 import javax.ws.rs.client.ClientBuilder;
10 import javax.ws.rs.client.Entity;
11 import javax.ws.rs.client.Invocation;
12 import javax.ws.rs.client.WebTarget;
13 import javax.ws.rs.sse.SseEventSource;
14
15 import org.jboss.arquillian.container.test.api.Deployment;
16 import org.jboss.arquillian.container.test.api.RunAsClient;
17 import org.jboss.arquillian.junit.Arquillian;
18 import org.jboss.logging.Logger;
19 import org.jboss.resteasy.category.Jaxrs21;
20 import org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl;
21 import org.jboss.resteasy.utils.PortProviderUtil;
22 import org.jboss.resteasy.utils.TestUtil;
23 import org.jboss.shrinkwrap.api.Archive;
24 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
25 import org.jboss.shrinkwrap.api.spec.WebArchive;
26 import org.junit.After;
27 import org.junit.Assert;
28 import org.junit.Test;
29 import org.junit.experimental.categories.Category;
30 import org.junit.runner.RunWith;
31
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 @Category(Jaxrs21.class)
35 public class SseEventSinkTest
36 {
37
38 private final static Logger logger = Logger.getLogger(SseEventSinkTest.class);
39
40 @Deployment
41 public static Archive<?> deploy()
42 {
43 WebArchive war = TestUtil.prepareArchive(SseTest.class.getSimpleName());
44 war.addClass(SseEventSinkTest.class);
45 war.addAsWebInfResource("org/jboss/resteasy/test/providers/sse/web.xml", "web.xml");
46 war.addAsWebResource("org/jboss/resteasy/test/providers/sse/index.html", "index.html");
47 war.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
48 return TestUtil.finishContainerPrepare(war, null, SseApplication.class, GreenHouse.class, SseResource.class,
49 AnotherSseResource.class, EscapingSseResource.class, ExecutorServletContextListener.class);
50 }
51
52 private String generateURL(String path)
53 {
54 return PortProviderUtil.generateURL(path, SseTest.class.getSimpleName());
55 }
56
57 @After
58 public void stopSendEvent() throws Exception
59 {
60 Client isOpenClient = ClientBuilder.newClient();
61 Invocation.Builder isOpenRequest = isOpenClient.target(generateURL("/service/server-sent-events/stopevent"))
62 .request();
63 isOpenRequest.get();
64
65 }
66
67 @Test
68 public void testCloseByEvnetSource() throws Exception
69 {
70 final CountDownLatch latch = new CountDownLatch(5);
71 final List<String> results = new ArrayList<String>();
72 final AtomicInteger errors = new AtomicInteger(0);
73 Client client = ClientBuilder.newClient();
74 WebTarget target = client.target(generateURL("/service/server-sent-events/events"));
75 SseEventSource eventSource = SseEventSource.target(target).build();
76
77 Assert.assertEquals(SseEventSourceImpl.class, eventSource.getClass());
78 eventSource.register(event -> {
79 results.add(event.readData(String.class));
80 latch.countDown();
81 }, ex -> {
82 errors.incrementAndGet();
83 logger.error(ex.getMessage(), ex);
84 throw new RuntimeException(ex);
85 });
86 eventSource.open();
87
88 boolean waitResult = latch.await(30, TimeUnit.SECONDS);
89 Assert.assertEquals(0, errors.get());
90 Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
91 Client isOpenClient = ClientBuilder.newClient();
92 Invocation.Builder isOpenRequest = isOpenClient.target(generateURL("/service/server-sent-events/isopen"))
93 .request();
94
95 javax.ws.rs.core.Response response = isOpenRequest.get();
96 Assert.assertTrue("EventSink open is expected ", response.readEntity(Boolean.class));
97
98 eventSource.close();
99 Assert.assertFalse("Closed eventSource state is expceted", eventSource.isOpen());
100
101 WebTarget messageTarget = ClientBuilder.newClient().target(generateURL("/service/server-sent-events"));
102 for (int counter = 0; counter < 5; counter++)
103 {
104 String msg = "messageAfterClose";
105 messageTarget.request().post(Entity.text(msg));
106 }
107
108 Assert.assertTrue("EventSource should not receive msg after it is closed",
109 results.indexOf("messageAfterClose") == -1);
110 Assert.assertFalse("EventSink close is expected ", isOpenRequest.get().readEntity(Boolean.class));
111
112 }
113 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.HashSet;
3 import java.util.Set;
4
5 import javax.ws.rs.core.Application;
6 import javax.ws.rs.ext.Provider;
7
8 @Provider
9 public class SseFilterApplication extends Application
10 {
11 private Set<Object> singletons = new HashSet<Object>();
12
13 public Set<Object> getSingletons()
14 {
15 if (singletons.isEmpty())
16 {
17 singletons.add(new SseResource());
18 singletons.add(new CORSFilter());
19 }
20 return singletons;
21 }
22
23 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.Collections;
3 import java.util.Set;
4
5 import javax.ws.rs.ApplicationPath;
6 import javax.ws.rs.core.Application;
7
8 /**
9 *
10 * @author Nicolas NESMON
11 *
12 */
13 @ApplicationPath("/")
14 public class SsePostResourceMethodInvokerApplication extends Application {
15
16 @Override
17 public Set<Object> getSingletons() {
18 return Collections.singleton(new SsePostResourceMethodInvokerTestResource());
19 }
20
21 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.Arrays;
3 import java.util.concurrent.TimeUnit;
4 import java.util.concurrent.TimeoutException;
5
6 import javax.ws.rs.InternalServerErrorException;
7 import javax.ws.rs.client.Client;
8 import javax.ws.rs.client.ClientBuilder;
9 import javax.ws.rs.client.WebTarget;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.Response;
12 import javax.ws.rs.core.Response.Status;
13
14 import org.jboss.arquillian.container.test.api.Deployment;
15 import org.jboss.arquillian.container.test.api.OperateOnDeployment;
16 import org.jboss.arquillian.container.test.api.RunAsClient;
17 import org.jboss.arquillian.junit.Arquillian;
18 import org.jboss.resteasy.category.Jaxrs21;
19 import org.jboss.resteasy.utils.PortProviderUtil;
20 import org.jboss.resteasy.utils.TestUtil;
21 import org.jboss.shrinkwrap.api.Archive;
22 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
23 import org.jboss.shrinkwrap.api.spec.WebArchive;
24 import org.junit.Assert;
25 import org.junit.Test;
26 import org.junit.experimental.categories.Category;
27 import org.junit.runner.RunWith;
28
29 /**
30 *
31 * @author Nicolas NESMON
32 *
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 @Category(Jaxrs21.class)
37 public class SsePostResourceMethodInvokerTest {
38
39 private static final String WITHOUT_EXCEPTION_REQUEST_FILTER = "withoutExceptionRequestFilter";
40 private static final String WITH_EXCEPTION_REQUEST_FILTER = "withExceptionRequestFilter";
41
42 @Deployment(name = WITH_EXCEPTION_REQUEST_FILTER)
43 public static Archive<?> deployWithoutExceptionRequestFilter() throws Exception {
44 WebArchive war = TestUtil.prepareArchive(WITH_EXCEPTION_REQUEST_FILTER);
45 return TestUtil.finishContainerPrepare(war, null, Arrays.asList(SsePostResourceMethodInvokerTestResource.class),
46 SsePostResourceMethodInvokerTestResource.ExceptionRequestFilter.class);
47 }
48
49 @Deployment(name = WITHOUT_EXCEPTION_REQUEST_FILTER)
50 public static Archive<?> deployWithExceptionRequestFilter() throws Exception {
51 WebArchive war = TestUtil.prepareArchive(WITHOUT_EXCEPTION_REQUEST_FILTER);
52 war.addAsWebInfResource("org/jboss/resteasy/test/providers/sse/synch-web.xml", "web.xml");
53 war.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
54 return TestUtil.finishContainerPrepare(war, null, SsePostResourceMethodInvokerTestResource.class,
55 SsePostResourceMethodInvokerApplication.class);
56 }
57
58 private static String generateURL(String tesName) {
59 return PortProviderUtil.generateBaseUrl(tesName);
60 }
61
62 @Test()
63 @OperateOnDeployment(WITHOUT_EXCEPTION_REQUEST_FILTER)
64 public void Should_Return200OkResponse_When_ResourceMethodExitFirst() throws Exception {
65 Client client = ClientBuilder.newClient();
66 try {
67 WebTarget baseTarget = client.target(generateURL(WITHOUT_EXCEPTION_REQUEST_FILTER))
68 .path(SsePostResourceMethodInvokerTestResource.BASE_PATH);
69 try {
70 Response response = baseTarget.request(MediaType.SERVER_SENT_EVENTS_TYPE).buildGet().submit().get(10,
71 TimeUnit.SECONDS);
72 try {
73 Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());
74 } finally {
75 client.close();
76 }
77 } catch (TimeoutException e) {
78 Assert.fail("Sse initial 200 ok response is expected when resource method resource returns first.");
79 }
80 } finally {
81 client = ClientBuilder.newClient();
82 try {
83 client.target(generateURL(WITHOUT_EXCEPTION_REQUEST_FILTER))
84 .path(SsePostResourceMethodInvokerTestResource.BASE_PATH)
85 .path(SsePostResourceMethodInvokerTestResource.CLOSE_PATH).request().delete();
86 } finally {
87 client.close();
88 }
89 }
90 }
91
92 @Test(expected = InternalServerErrorException.class)
93 @OperateOnDeployment(WITH_EXCEPTION_REQUEST_FILTER)
94 public void Should_ThrowIntenalServerError_When_AnyFilterAfterSseFilterThrowsIOException() throws Exception {
95 Client client = ClientBuilder.newClient();
96 try {
97 client.target(generateURL(WITH_EXCEPTION_REQUEST_FILTER))
98 .path(SsePostResourceMethodInvokerTestResource.BASE_PATH).request(MediaType.SERVER_SENT_EVENTS_TYPE)
99 .get(String.class);
100 } finally {
101 client.close();
102 }
103 }
104
105 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.io.IOException;
3
4 import javax.annotation.Priority;
5 import javax.ws.rs.DELETE;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.container.ContainerRequestContext;
10 import javax.ws.rs.container.ContainerRequestFilter;
11 import javax.ws.rs.core.Context;
12 import javax.ws.rs.core.MediaType;
13 import javax.ws.rs.ext.Provider;
14 import javax.ws.rs.sse.SseEventSink;
15
16 /**
17 *
18 * @author Nicolas NESMON
19 *
20 */
21 @Path(SsePostResourceMethodInvokerTestResource.BASE_PATH)
22 public class SsePostResourceMethodInvokerTestResource {
23
24 @Provider
25 @Priority(Integer.MAX_VALUE)
26 public static class ExceptionRequestFilter implements ContainerRequestFilter {
27
28 @Override
29 public void filter(ContainerRequestContext containerRequestContext) throws IOException {
30 throw new IOException();
31 }
32
33 }
34
35 public static final String BASE_PATH = "ssePostResourceMethodInvoker";
36 public static final String CLOSE_PATH = "close";
37
38 private final Object outputLock = new Object();
39
40 private SseEventSink eventSink;
41
42 @GET
43 @Produces(MediaType.SERVER_SENT_EVENTS)
44 public void getEventSink(@Context SseEventSink sseEventSink) {
45 synchronized (this.outputLock) {
46 if (this.eventSink != null) {
47 throw new IllegalStateException("Server sink already served.");
48 }
49 this.eventSink = sseEventSink;
50 }
51 }
52
53 @DELETE
54 @Path(CLOSE_PATH)
55 public void close() {
56 synchronized (this.outputLock) {
57 if (this.eventSink != null) {
58 this.eventSink.close();
59 this.eventSink = null;
60 }
61 }
62 }
63
64 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.category.Jaxrs21;
6 import org.jboss.resteasy.test.providers.sse.resource.SseReconnectResource;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.Assert;
13 import org.junit.Test;
14 import org.junit.experimental.categories.Category;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.ServiceUnavailableException;
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.client.WebTarget;
21 import javax.ws.rs.core.Response;
22 import javax.ws.rs.sse.SseEvent;
23 import javax.ws.rs.sse.SseEventSource;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.concurrent.CountDownLatch;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.atomic.AtomicInteger;
29
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 @Category(Jaxrs21.class)
33 public class SseReconnectTest {
34
35 @Deployment
36 public static Archive<?> deploy() {
37 WebArchive war = TestUtil.prepareArchive(SseReconnectTest.class.getSimpleName());
38 return TestUtil.finishContainerPrepare(war, null, SseReconnectResource.class);
39 }
40
41 private String generateURL(String path)
42 {
43 return PortProviderUtil.generateURL(path, SseReconnectTest.class.getSimpleName());
44 }
45
46 /**
47 * @tpTestDetails Check SseEvent.getReconnectDelay() returns SseEvent.RECONNECT_NOT_SET,
48 * when OutboundSseEvent.reconnectDelay() is not set.
49 * @tpInfo RESTEASY-1680
50 * @tpSince RESTEasy 3.5.0
51 */
52 @Test
53 public void testReconnectDelayIsNotSet() throws Exception {
54 Client client = ClientBuilder.newClient();
55 try {
56 WebTarget baseTarget = client.target(generateURL("/reconnect/defaultReconnectDelay"));
57 try (Response response = baseTarget.request().get()) {
58 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
59 Assert.assertEquals(SseEvent.RECONNECT_NOT_SET, (long) response.readEntity(long.class));
60 }
61 } finally {
62 client.close();
63 }
64 }
65
66 /**
67 * @tpTestDetails *** Check SseEvent.getReconnectDelay() returns correct delay,
68 * when OutboundSseEvent.reconnectDelay() is set.
69 * @tpInfo RESTEASY-1680
70 * @tpSince RESTEasy 3.5.0
71 */
72 @Test
73 public void testReconnectDelayIsSet() throws Exception {
74 Client client = ClientBuilder.newClient();
75 try {
76 WebTarget baseTarget = client.target(generateURL("/reconnect/reconnectDelaySet"));
77 try (Response response = baseTarget.request().get()) {
78 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
79 Assert.assertEquals(1000L, (long) response.readEntity(long.class));
80 }
81 } finally {
82 client.close();
83 }
84 }
85
86 /**
87 * @tpTestDetails SseEventSource receives HTTP 503 + "Retry-After" from the SSE endpoint. Check that SseEventSource
88 * retries after the specified period
89 * @tpInfo RESTEASY-1680
90 * @tpSince RESTEasy 3.5.0
91 */
92 @Test
93 public void testSseEndpointUnavailable() throws Exception {
94 final CountDownLatch latch = new CountDownLatch(1);
95 final AtomicInteger errors = new AtomicInteger(0);
96 final List<String> results = new ArrayList<String>();
97 Client client = ClientBuilder.newBuilder().build();
98 try {
99 WebTarget target = client.target(generateURL("/reconnect/unavailable"));
100 SseEventSource msgEventSource = SseEventSource.target(target).build();
101 try (SseEventSource eventSource = msgEventSource) {
102 eventSource.register(event -> {
103 results.add(event.readData(String.class));
104 latch.countDown();
105 }, ex -> {
106 errors.incrementAndGet();
107 Assert.assertTrue("ServiceUnavalile exception is expected", ex instanceof ServiceUnavailableException);
108 });
109 eventSource.open();
110
111 boolean waitResult = latch.await(30, TimeUnit.SECONDS);
112 Assert.assertEquals(1, errors.get());
113 Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
114 }
115 Assert.assertTrue("ServiceAvailable message is expected", results.get(0).equals("ServiceAvailable"));
116 } finally {
117 client.close();
118 }
119 }
120
121 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.io.IOException;
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.concurrent.ExecutorService;
6
7 import javax.servlet.ServletContext;
8 import javax.ws.rs.DELETE;
9 import javax.ws.rs.DefaultValue;
10 import javax.ws.rs.GET;
11 import javax.ws.rs.HeaderParam;
12 import javax.ws.rs.POST;
13 import javax.ws.rs.Path;
14 import javax.ws.rs.PathParam;
15 import javax.ws.rs.Produces;
16 import javax.ws.rs.ServerErrorException;
17 import javax.ws.rs.WebApplicationException;
18 import javax.ws.rs.core.Context;
19 import javax.ws.rs.core.HttpHeaders;
20 import javax.ws.rs.core.MediaType;
21 import javax.ws.rs.core.Response;
22 import javax.ws.rs.sse.OutboundSseEvent;
23 import javax.ws.rs.sse.Sse;
24 import javax.ws.rs.sse.SseBroadcaster;
25 import javax.ws.rs.sse.SseEventSink;
26 import javax.xml.bind.JAXBElement;
27 import javax.xml.namespace.QName;
28
29 import org.jboss.logging.Logger;
30 import org.jboss.resteasy.plugins.providers.sse.SseConstants;
31
32 @Path("/server-sent-events")
33 public class SseResource
34 {
35
36 private final Object outputLock = new Object();
37 private final Object sseBroadcasterLock = new Object();
38
39 @Context
40 private Sse sse;
41
42 @Context
43 private ServletContext servletContext;
44
45 private volatile SseEventSink eventSink;
46
47 private volatile SseBroadcaster sseBroadcaster;
48
49 private Object openLock = new Object();
50
51 private volatile boolean sending = true;
52
53 private List<OutboundSseEvent> eventsStore = new ArrayList<OutboundSseEvent>();
54
55 private final static Logger logger = Logger.getLogger(SseResource.class);
56
57 @GET
58 @Produces(MediaType.SERVER_SENT_EVENTS)
59 public void getMessageQueue(@HeaderParam(SseConstants.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastEventId,
60 @Context SseEventSink eventSink)
61 {
62 synchronized (outputLock)
63 {
64 if (this.eventSink != null)
65 {
66 throw new IllegalStateException("Server sink already served.");
67 }
68 }
69 this.eventSink = eventSink;
70 //replay missed events
71 if (lastEventId > -1)
72 {
73 synchronized (eventsStore)
74 {
75 if (lastEventId + 1 < eventsStore.size())
76 {
77 List<OutboundSseEvent> missedEvents = eventsStore.subList(lastEventId + 1, eventsStore.size());
78 for (OutboundSseEvent item : missedEvents)
79 {
80 this.eventSink.send(item);
81 }
82 }
83 }
84 }
85 }
86
87 @POST
88 public void addMessage(final String message) throws IOException
89 {
90 if (eventSink == null)
91 {
92 throw new IllegalStateException("No client connected.");
93 }
94 OutboundSseEvent event = null;
95 synchronized (eventsStore)
96 {
97 event = sse.newEventBuilder().id(Integer.toString(eventsStore.size())).data(message).build();
98 eventsStore.add(event);
99 }
100 eventSink.send(event);
101 }
102
103 @POST
104 @Path("/addMessageAndDisconnect")
105 public void addMessageAndDisconnect(final String message) throws IOException, InterruptedException
106 {
107 //clear events store first
108 eventsStore.clear();
109 for (int i = 0; i < 10; i++)
110 {
111 OutboundSseEvent event = null;
112 synchronized (eventsStore)
113 {
114 event = sse.newEventBuilder().id(Integer.toString(eventsStore.size())).data(i + "-" + message).build();
115 eventsStore.add(event);
116 }
117 //disconnect after 3 messages
118 if (i == 3)
119 {
120 close();
121 }
122 if (eventSink != null)
123 {
124 eventSink.send(event);
125 }
126 Thread.sleep(250);
127 }
128 }
129
130 @GET
131 @Path("/subscribe")
132 @Produces(MediaType.SERVER_SENT_EVENTS)
133 public void subscribe(@Context SseEventSink sink) throws IOException
134 {
135 if (sink == null)
136 {
137 throw new IllegalStateException("No client connected.");
138 }
139 synchronized (this.sseBroadcasterLock) {
140 //subscribe
141 if (sseBroadcaster == null)
142 {
143 sseBroadcaster = sse.newBroadcaster();
144 }
145 }
146 sseBroadcaster.register(sink);
147 }
148
149 @POST
150 @Path("/broadcast")
151 public void broadcast(String message)
152 {
153 if (this.sseBroadcaster == null)
154 {
155 throw new IllegalStateException("No Sse broadcaster created.");
156 }
157 ExecutorService service = (ExecutorService) servletContext
158 .getAttribute(ExecutorServletContextListener.TEST_EXECUTOR);
159 if ("repeat".equals(message))
160 {
161 service.execute(new Thread()
162 {
163 public void run()
164 {
165 for (int i = 0; i < 100; i++)
166 {
167
168 try
169 {
170 sseBroadcaster.broadcast(sse.newEvent(message));
171 Thread.sleep(100);
172 }
173 catch (final InterruptedException e)
174 {
175 logger.error(e.getMessage(), e);
176 break;
177 }
178 }
179 }
180 });
181
182 }
183 else
184 {
185 sseBroadcaster.broadcast(sse.newEvent(message));
186 }
187 }
188
189 @DELETE
190 public void close() throws IOException
191 {
192 synchronized (outputLock)
193 {
194 if (eventSink != null)
195 {
196 eventSink.close();
197 eventSink = null;
198 }
199 }
200 }
201
202 @GET
203 @Path("domains/{id}")
204 @Produces(MediaType.SERVER_SENT_EVENTS)
205 public void startDomain(@PathParam("id") final String id, @Context SseEventSink sink)
206 {
207 ExecutorService service = (ExecutorService) servletContext
208 .getAttribute(ExecutorServletContextListener.TEST_EXECUTOR);
209 service.execute(new Thread()
210 {
211 public void run()
212 {
213 try
214 {
215 sink.send(sse.newEventBuilder().name("domain-progress")
216 .data(String.class, "starting domain " + id + " ...").build());
217 Thread.sleep(200);
218 sink.send(sse.newEvent("domain-progress", "50%"));
219 Thread.sleep(200);
220 sink.send(sse.newEvent("domain-progress", "60%"));
221 Thread.sleep(200);
222 sink.send(sse.newEvent("domain-progress", "70%"));
223 Thread.sleep(200);
224 sink.send(sse.newEvent("domain-progress", "99%"));
225 Thread.sleep(200);
226 sink.send(sse.newEvent("domain-progress", "Done.")).thenAccept((Object obj) -> {
227 sink.close();
228 });
229 }
230 catch (final InterruptedException e)
231 {
232 logger.error(e.getMessage(), e);
233 }
234 }
235 });
236 }
237
238 @GET
239 @Path("/events")
240 @Produces(MediaType.SERVER_SENT_EVENTS)
241 public void eventStream(@Context SseEventSink sink) throws IOException
242 {
243 if (sink == null)
244 {
245 throw new IllegalStateException("No client connected.");
246 }
247 this.eventSink = sink;
248 ExecutorService service = (ExecutorService) servletContext
249 .getAttribute(ExecutorServletContextListener.TEST_EXECUTOR);
250 service.execute(new Thread()
251 {
252 public void run()
253 {
254 while (!eventSink.isClosed() && sending)
255 {
256 try
257 {
258 synchronized (openLock)
259 {
260 eventSink.send(sse.newEvent("msg"));
261 }
262 Thread.sleep(200);
263 }
264 catch (final InterruptedException e)
265 {
266 logger.error(e.getMessage(), e);
267 break;
268 }
269
270 }
271 }
272 });
273 }
274
275 @GET
276 @Path("/isopen")
277 public boolean isOpen()
278 {
279 synchronized (openLock)
280 {
281 return !eventSink.isClosed();
282 }
283
284 }
285
286 @GET
287 @Path("/stopevent")
288 public void stopEvent()
289 {
290 this.sending = false;
291
292 }
293
294 @GET
295 @Path("/error")
296 @Produces(MediaType.SERVER_SENT_EVENTS)
297 public void testErrorConsumer(@Context SseEventSink eventSink)
298 {
299 throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
300 }
301
302 @GET
303 @Path("/xmlevent")
304 @Produces(MediaType.SERVER_SENT_EVENTS)
305 public void sendXmlType(@Context SseEventSink sink)
306 {
307 try (SseEventSink eventSink = sink)
308 {
309 JAXBElement<String> element = new JAXBElement<String>(new QName("name"), String.class, "xmldata");
310 eventSink.send(sse.newEventBuilder().data(element).mediaType(MediaType.APPLICATION_XML_TYPE).build());
311 }
312 }
313 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import org.hamcrest.CoreMatchers;
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.logging.Logger;
7 import org.jboss.resteasy.category.Jaxrs21;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.test.providers.sse.resource.SseSmokeMessageBodyWriter;
11 import org.jboss.resteasy.test.providers.sse.resource.SseSmokeResource;
12 import org.jboss.resteasy.test.providers.sse.resource.SseSmokeUser;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.junit.experimental.categories.Category;
23 import org.junit.runner.RunWith;
24
25 import javax.ws.rs.client.Client;
26 import javax.ws.rs.client.ClientBuilder;
27 import javax.ws.rs.client.WebTarget;
28 import javax.ws.rs.sse.SseEventSource;
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.concurrent.CountDownLatch;
32 import java.util.concurrent.TimeUnit;
33
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 @Category(Jaxrs21.class)
37 public class SseSmokeTest {
38 private final static Logger logger = Logger.getLogger(SseSmokeTest.class);
39 static Client client;
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(SseSmokeTest.class.getSimpleName());
44 return TestUtil.finishContainerPrepare(war, null, SseSmokeMessageBodyWriter.class, SseSmokeUser.class,
45 SseSmokeResource.class);
46 }
47
48 @Before
49 public void init() {
50 client = ClientBuilder.newBuilder().build();
51 }
52
53 @After
54 public void after() throws Exception {
55 client.close();
56 }
57
58 private String generateURL(String path) {
59 return PortProviderUtil.generateURL(path, SseSmokeTest.class.getSimpleName());
60 }
61
62 /**
63 * @tpTestDetails REST resource with SSE endpoint. Event is sent to the client.
64 * @tpInfo RESTEASY-1680
65 * @tpSince RESTEasy 3.5.0
66 */
67 @Test
68 public void testSmoke() throws Exception {
69 final List<String> results = new ArrayList<String>();
70 WebTarget target = client.target(generateURL("/sse/events"));
71 SseEventSource msgEventSource = SseEventSource.target(target).build();
72
73 try (SseEventSource eventSource = msgEventSource) {
74 CountDownLatch countDownLatch = new CountDownLatch(1);
75 eventSource.register(event -> {
76 countDownLatch.countDown();
77 results.add(event.readData(String.class));
78 }, e -> {
79 throw new RuntimeException(e);
80 });
81 eventSource.open();
82 boolean result = countDownLatch.await(30, TimeUnit.SECONDS);
83 Assert.assertTrue("Waiting for event to be delivered has timed out.", result);
84 }
85 Assert.assertEquals("One message was expected.", 1, results.size());
86 Assert.assertThat("The message doesn't have expected content.","Zeytin;zeytin@resteasy.org",
87 CoreMatchers.is(CoreMatchers.equalTo(results.get(0))));
88 }
89 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.ArrayList;
3 import java.util.Arrays;
4 import java.util.List;
5 import java.util.SortedSet;
6 import java.util.TreeSet;
7 import java.util.concurrent.CountDownLatch;
8 import java.util.concurrent.TimeUnit;
9 import java.util.concurrent.atomic.AtomicInteger;
10 import java.util.function.Consumer;
11
12 import javax.ws.rs.InternalServerErrorException;
13 import javax.ws.rs.ServiceUnavailableException;
14 import javax.ws.rs.client.Client;
15 import javax.ws.rs.client.ClientBuilder;
16 import javax.ws.rs.client.Entity;
17 import javax.ws.rs.client.WebTarget;
18 import javax.ws.rs.core.MediaType;
19 import javax.ws.rs.core.Response;
20 import javax.ws.rs.sse.InboundSseEvent;
21 import javax.ws.rs.sse.SseEventSource;
22 import javax.xml.bind.JAXBElement;
23
24 import org.jboss.arquillian.container.test.api.Deployment;
25 import org.jboss.arquillian.container.test.api.RunAsClient;
26 import org.jboss.arquillian.junit.Arquillian;
27 import org.jboss.arquillian.junit.InSequence;
28 import org.jboss.logging.Logger;
29 import org.jboss.resteasy.category.Jaxrs21;
30 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
31 import org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl;
32 import org.jboss.resteasy.utils.PortProviderUtil;
33 import org.jboss.resteasy.utils.TestUtil;
34 import org.jboss.shrinkwrap.api.Archive;
35 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
36 import org.jboss.shrinkwrap.api.spec.WebArchive;
37 import org.junit.Assert;
38 import org.junit.Test;
39 import org.junit.experimental.categories.Category;
40 import org.junit.runner.RunWith;
41
42 @RunWith(Arquillian.class)
43 @RunAsClient
44 @Category(Jaxrs21.class)
45 public class SseTest
46 {
47
48 private final static Logger logger = Logger.getLogger(SseTest.class);
49
50 @Deployment
51 public static Archive<?> deploy()
52 {
53 WebArchive war = TestUtil.prepareArchive(SseTest.class.getSimpleName());
54 war.addClass(SseTest.class);
55 war.addAsWebInfResource("org/jboss/resteasy/test/providers/sse/web.xml", "web.xml");
56 war.addAsWebResource("org/jboss/resteasy/test/providers/sse/index.html", "index.html");
57 war.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
58 return TestUtil.finishContainerPrepare(war, null, SseApplication.class, GreenHouse.class, SseResource.class,
59 AnotherSseResource.class, EscapingSseResource.class, ExecutorServletContextListener.class);
60 }
61
62 private String generateURL(String path)
63 {
64 return PortProviderUtil.generateURL(path, SseTest.class.getSimpleName());
65 }
66
67 @Test
68 @InSequence(1)
69 public void testAddMessage() throws Exception
70 {
71 final CountDownLatch latch = new CountDownLatch(5);
72 final AtomicInteger errors = new AtomicInteger(0);
73 final List<String> results = new ArrayList<String>();
74 final List<String> sent = new ArrayList<String>();
75 Client client = ClientBuilder.newBuilder().build();
76 WebTarget target = client.target(generateURL("/service/server-sent-events"));
77 SseEventSource msgEventSource = SseEventSource.target(target).build();
78 try (SseEventSource eventSource = msgEventSource)
79 {
80 Assert.assertEquals(SseEventSourceImpl.class, eventSource.getClass());
81 eventSource.register(event -> {
82 results.add(event.readData(String.class));
83 latch.countDown();
84 }, ex -> {
85 errors.incrementAndGet();
86 logger.error(ex.getMessage(), ex);
87 throw new RuntimeException(ex);
88 });
89 eventSource.open();
90
91 Client messageClient = new ResteasyClientBuilder().connectionPoolSize(10).build();
92 WebTarget messageTarget = messageClient.target(generateURL("/service/server-sent-events"));
93 for (int counter = 0; counter < 5; counter++)
94 {
95 String msg = "message " + counter;
96 sent.add(msg);
97 messageTarget.request().post(Entity.text(msg));
98 }
99 boolean waitResult = latch.await(30, TimeUnit.SECONDS);
100 Assert.assertEquals(0, errors.get());
101 Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
102 messageTarget.request().delete();
103 messageClient.close();
104 }
105 Assert.assertFalse("SseEventSource is not closed", msgEventSource.isOpen());
106 Assert.assertTrue("5 messages are expected, but is : " + results.size(), results.size() == 5);
107 for (String s : sent)
108 {
109 Assert.assertTrue("Sent message \"" + s + "\" not found as result.", results.contains(s));
110 }
111 }
112
113 //Test for Last-Event-Id. This test uses the message items stores in testAddMessage()
114 @Test
115 @InSequence(2)
116 public void testLastEventId() throws Exception
117 {
118 final CountDownLatch missedEventLatch = new CountDownLatch(3);
119 final List<String> missedEvents = new ArrayList<String>();
120 WebTarget lastEventTarget = new ResteasyClientBuilder().connectionPoolSize(10).build()
121 .target(generateURL("/service/server-sent-events"));
122 SseEventSourceImpl lastEventSource = (SseEventSourceImpl) SseEventSource.target(lastEventTarget).build();
123 lastEventSource.register(event -> {
124 missedEvents.add(event.toString());
125 missedEventLatch.countDown();
126 }, ex -> {
127 throw new RuntimeException(ex);
128 });
129 lastEventSource.open("1");
130 Assert.assertTrue(
131 "Waiting for missed events to be delivered has timed our, received events :"
132 + Arrays.toString(missedEvents.toArray(new String[]
133 {})), missedEventLatch.await(30, TimeUnit.SECONDS));
134 Assert.assertTrue("3 messages are expected, but is : " + missedEvents.toArray(new String[]
135 {}), missedEvents.size() == 3);
136 lastEventTarget.request().delete();
137 lastEventSource.close();
138 }
139
140 @Test
141 @InSequence(3)
142 public void testSseEvent() throws Exception
143 {
144 final List<String> results = new ArrayList<String>();
145 final CountDownLatch latch = new CountDownLatch(6);
146 final AtomicInteger errors = new AtomicInteger(0);
147 Client client = new ResteasyClientBuilder().connectionPoolSize(10).build();
148 WebTarget target = client.target(generateURL("/service/server-sent-events")).path("domains").path("1");
149
150 SseEventSource eventSource = SseEventSource.target(target).build();
151 Assert.assertEquals(SseEventSourceImpl.class, eventSource.getClass());
152 eventSource.register(event -> {
153 results.add(event.readData());
154 latch.countDown();
155 }, ex -> {
156 errors.incrementAndGet();
157 logger.error(ex.getMessage(), ex);
158 throw new RuntimeException(ex);
159 });
160 eventSource.open();
161
162 boolean waitResult = latch.await(30, TimeUnit.SECONDS);
163 Assert.assertEquals(0, errors.get());
164 Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
165 Assert.assertTrue("6 SseInboundEvent expected", results.size() == 6);
166 Assert.assertTrue("Expect the last event is Done event, but it is :" + results.toArray(new String[]
167 {})[5], results.toArray(new String[]
168 {})[5].indexOf("Done") > -1);
169 eventSource.close();
170 client.close();
171 }
172
173 @Test
174 @InSequence(4)
175 public void testBroadcast() throws Exception
176 {
177 final CountDownLatch latch = new CountDownLatch(3);
178 Client client = new ResteasyClientBuilder().build();
179 WebTarget target = client.target(generateURL("/service/server-sent-events/subscribe"));
180 final String textMessage = "This is broadcast message";
181 Consumer<InboundSseEvent> checkConsumer = insse -> {
182 if (latch.getCount() > 0)
183 {
184 Assert.assertTrue("Unexpected sever sent event data", textMessage.equals(insse.readData()));
185 }
186 latch.countDown();
187 };
188 SseEventSource eventSource = SseEventSource.target(target).build();
189 Assert.assertEquals(SseEventSourceImpl.class, eventSource.getClass());
190 eventSource.register(checkConsumer);
191 eventSource.open();
192
193 Client client2 = new ResteasyClientBuilder().build();
194 WebTarget target2 = client2.target(generateURL("/service/sse/subscribe"));
195
196 SseEventSource eventSource2 = SseEventSource.target(target2).build();
197 eventSource2.register(checkConsumer);
198 eventSource2.open();
199 //Test for eventSource subscriber
200
201 client.target(generateURL("/service/server-sent-events/broadcast")).request()
202 .post(Entity.entity(textMessage, MediaType.SERVER_SENT_EVENTS));
203 client2.target(generateURL("/service/sse/broadcast")).request()
204 .post(Entity.entity(textMessage, MediaType.SERVER_SENT_EVENTS));
205 Assert.assertTrue("Waiting for broadcast event to be delivered has timed out.", latch.await(20, TimeUnit.SECONDS));
206
207 //one subscriber is closed and test if another subscriber works
208 CountDownLatch latch3 = new CountDownLatch(5);
209 CountDownLatch latch4 = new CountDownLatch(5);
210 eventSource.register(insse -> {
211 latch3.countDown();
212 });
213 eventSource2.register(insse -> {
214 latch4.countDown();
215 });
216 client2.target(generateURL("/service/server-sent-events/broadcast")).request()
217 .post(Entity.entity("repeat", MediaType.SERVER_SENT_EVENTS));
218 Assert.assertTrue("Waiting for repeatable broadcast events to be delivered has timed out.",
219 latch3.await(20, TimeUnit.SECONDS));
220 Assert.assertTrue("Waiting for repeatable broadcast events to be delivered has timed out.",
221 latch4.await(20, TimeUnit.SECONDS));
222
223 client.close();
224 CountDownLatch latch5 = new CountDownLatch(5);
225 CountDownLatch latch6 = new CountDownLatch(5);
226
227 eventSource.register(insse -> {
228 latch5.countDown();
229 });
230 eventSource2.register(insse -> {
231 latch6.countDown();
232 });
233
234 Assert.assertTrue("Eventsource should not receive event after close", latch5.getCount() == 5);
235 Assert.assertTrue("Waiting for eventsource2 receive broadcast events to be delivered has timed out.",
236 latch6.await(20, TimeUnit.SECONDS));
237
238 client2.target(generateURL("/service/server-sent-events/broadcast")).request()
239 .post(Entity.entity("close one subscriber", MediaType.SERVER_SENT_EVENTS));
240
241 Client closeClient = new ResteasyClientBuilder().build();
242 WebTarget closeTarget = closeClient.target(generateURL("/service/sse"));
243 Assert.assertTrue("Subscribed eventsink is not closed", closeTarget.request().delete().readEntity(Boolean.class));
244 eventSource2.close();
245 }
246
247 //This test is checking SseEventSource reconnect ability. When request post /addMessageAndDisconnect path, server will
248 //disconnect the connection, but events is continued to add to eventsStore. SseEventSource will automatically reconnect
249 //with LastEventId and receive the missed events
250 @Test
251 @InSequence(5)
252 public void testReconnect() throws Exception
253 {
254 final CountDownLatch latch = new CountDownLatch(10);
255 final CountDownLatch closeLatch = new CountDownLatch(1);
256 final List<String> results = new ArrayList<String>();
257 final AtomicInteger errors = new AtomicInteger(0);
258 Client client = new ResteasyClientBuilder().connectionPoolSize(10).build();
259 WebTarget target = client.target(generateURL("/service/server-sent-events"));
260 try (SseEventSource eventSource = SseEventSource.target(target).reconnectingEvery(1, TimeUnit.SECONDS).build())
261 {
262 Assert.assertEquals(SseEventSourceImpl.class, eventSource.getClass());
263 eventSource.register(event -> {
264 results.add(event.toString());
265 latch.countDown();
266 closeLatch.countDown();
267 }, ex -> {
268 errors.incrementAndGet();
269 logger.error(ex.getMessage(), ex);
270 throw new RuntimeException(ex);
271 });
272 eventSource.open();
273
274 Client messageClient = new ResteasyClientBuilder().build();
275 WebTarget messageTarget = messageClient
276 .target(generateURL("/service/server-sent-events/addMessageAndDisconnect"));
277 messageTarget.request().post(Entity.text("msg"));
278 messageClient.close();
279
280 boolean waitResult = latch.await(30, TimeUnit.SECONDS);
281 Assert.assertEquals(0, errors.get());
282 Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
283 Assert.assertTrue("10 events are expected, but is : " + results.size(), results.size() == 10);
284 target.request().delete();
285 }
286 }
287
288 @Test
289 @InSequence(6)
290 public void testEventSourceConsumer() throws Exception
291 {
292 final CountDownLatch latch = new CountDownLatch(1);
293 Client client = new ResteasyClientBuilder().connectionPoolSize(10).build();
294 WebTarget target = client.target(generateURL("/service/server-sent-events/error"));
295 List<Throwable> errorList = new ArrayList<Throwable>();
296 Thread t = new Thread(new Runnable()
297 {
298 @Override
299 public void run()
300 {
301 try (SseEventSource eventSource = SseEventSource.target(target).build())
302 {
303 eventSource.register(event -> {
304 latch.countDown();
305 }, ex -> {
306 if (ex instanceof InternalServerErrorException)
307 {
308 errorList.add(ex);
309 latch.countDown();
310 }
311 });
312 eventSource.open();
313 }
314 }
315 });
316 t.start();
317 if (latch.await(30, TimeUnit.SECONDS))
318 {
319 t.interrupt();
320 }
321 Assert.assertFalse("InternalServerErrorException isn't processed in error consumer", errorList.isEmpty());
322 }
323
324 @Test
325 @InSequence(7)
326 public void testMultipleDataFields() throws Exception
327 {
328 final CountDownLatch latch = new CountDownLatch(7);
329 final AtomicInteger errors = new AtomicInteger(0);
330 final SortedSet<String> results = new TreeSet<String>();
331 Client client = ClientBuilder.newBuilder().build();
332 WebTarget target = client.target(generateURL("/service/server-sent-events"));
333 SseEventSource msgEventSource = SseEventSource.target(target).build();
334 try (SseEventSource eventSource = msgEventSource)
335 {
336 Assert.assertEquals(SseEventSourceImpl.class, eventSource.getClass());
337 eventSource.register(event -> {
338 results.add(event.readData());
339 latch.countDown();
340 }, ex -> {
341 errors.incrementAndGet();
342 logger.error(ex.getMessage(), ex);
343 throw new RuntimeException(ex);
344 });
345 eventSource.open();
346
347 Client messageClient = new ResteasyClientBuilder().connectionPoolSize(10).build();
348 WebTarget messageTarget = messageClient.target(generateURL("/service/server-sent-events"));
349 messageTarget.request().post(Entity.text("data0a"));
350 messageTarget.request().post(Entity.text("data1a\ndata1b\n\rdata1c"));
351 messageTarget.request().post(Entity.text("data2a\r\ndata2b"));
352 messageTarget.request().post(Entity.text("data3a\n\rdata3b"));
353 messageTarget.request().post(Entity.text("data4a\r\ndata4b"));
354 messageTarget.request().post(Entity.text("data5a\r\r\r\ndata5b"));
355 messageTarget.request().post(Entity.text("data6a\n\n\r\r\ndata6b"));
356 boolean waitResult = latch.await(30, TimeUnit.SECONDS);
357 Assert.assertEquals(0, errors.get());
358 Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
359 messageTarget.request().delete();
360 messageClient.close();
361 }
362 Assert.assertFalse("SseEventSource is not closed", msgEventSource.isOpen());
363 Assert.assertTrue("5 messages are expected, but is : " + results.size(), results.size() == 7);
364 String[] lines = results.toArray(new String[]
365 {})[1].split("\n");
366 Assert.assertTrue("3 data fields are expected, but is : " + lines.length, lines.length == 3);
367 Assert.assertEquals("expect second data field value is : " + lines[1], "data1b", lines[1]);
368
369 }
370
371 @Test
372 @InSequence(8)
373 public void testEscapedMessage() throws Exception
374 {
375 final CountDownLatch latch = new CountDownLatch(3);
376 final AtomicInteger errors = new AtomicInteger(0);
377 final List<String> results = new ArrayList<String>();
378 final List<String> sent = new ArrayList<String>();
379 sent.add("foo1\nbar");
380 sent.add("foo2\nbar");
381 sent.add("foo3\nbar");
382 Client client = ClientBuilder.newBuilder().build();
383 WebTarget target = client.target(generateURL("/service/sse-escaping"));
384 SseEventSource msgEventSource = SseEventSource.target(target).build();
385 try (SseEventSource eventSource = msgEventSource)
386 {
387 Assert.assertEquals(SseEventSourceImpl.class, eventSource.getClass());
388 eventSource.register(event -> {
389 results.add(event.readData(String.class));
390 latch.countDown();
391 }, ex -> {
392 errors.incrementAndGet();
393 logger.error(ex.getMessage(), ex);
394 throw new RuntimeException(ex);
395 });
396 eventSource.open();
397
398 boolean waitResult = latch.await(30, TimeUnit.SECONDS);
399 Assert.assertEquals(0, errors.get());
400 Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
401 }
402 Assert.assertFalse("SseEventSource is not closed", msgEventSource.isOpen());
403 Assert.assertTrue("3 messages are expected, but is : " + results.size(), results.size() == 3);
404 for (String s : sent)
405 {
406 Assert.assertTrue("Sent message \"" + s + "\" not found as result.", results.contains(s));
407 }
408 }
409
410 @Test
411 @InSequence(10)
412 public void testXmlEvent() throws Exception
413 {
414 final CountDownLatch latch = new CountDownLatch(1);
415 final AtomicInteger errors = new AtomicInteger(0);
416 final List<InboundSseEvent> results = new ArrayList<InboundSseEvent>();
417 Client client = ClientBuilder.newBuilder().build();
418 WebTarget target = client.target(generateURL("/service/server-sent-events/xmlevent"));
419 SseEventSource msgEventSource = SseEventSource.target(target).build();
420 try (SseEventSource eventSource = msgEventSource)
421 {
422 Assert.assertEquals(SseEventSourceImpl.class, eventSource.getClass());
423 eventSource.register(event -> {
424 results.add(event);
425 latch.countDown();
426 }, ex -> {
427 errors.incrementAndGet();
428 ex.printStackTrace();
429 throw new RuntimeException(ex);
430 });
431 eventSource.open();
432
433 boolean waitResult = latch.await(30, TimeUnit.SECONDS);
434 Assert.assertEquals(0, errors.get());
435 Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
436 }
437 JAXBElement<String> jaxbElement = results.get(0).readData(new javax.ws.rs.core.GenericType<JAXBElement<String>>()
438 {
439 }, MediaType.APPLICATION_XML_TYPE);
440 Assert.assertEquals("xmldata is expceted", jaxbElement.getValue(), "xmldata");
441 }
442
443 @Test
444 @InSequence(11)
445 public void testGetSseEvent() throws Exception
446 {
447 Client client = ClientBuilder.newClient();
448 WebTarget target = client.target(generateURL("/service/server-sent-events/events"));
449 Response response = target.request().get();
450 Assert.assertEquals("response OK is expected", response.getStatus(), 200);
451 Assert.assertEquals("text/event-stream is expected", response.getMediaType(), MediaType.SERVER_SENT_EVENTS_TYPE);
452 client.close();
453 }
454
455 // @Test
456 // //This will open a browser and test with html sse client
457 // public void testHtmlSse() throws Exception
458 // {
459 //
460 // Runtime runtime = Runtime.getRuntime();
461 // try
462 // {
463 // runtime.exec("xdg-open " + generateURL(""));
464 // }
465 // catch (IOException e)
466 // {
467 //
468 // }
469 // Thread.sleep(30 * 1000);
470 // }
471 }
0 package org.jboss.resteasy.test.providers.sse.resource;
1
2 import org.hibernate.validator.constraints.br.CPF;
3 import org.junit.Assert;
4
5 import javax.ejb.Singleton;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.WebApplicationException;
10 import javax.ws.rs.container.ContainerRequestContext;
11 import javax.ws.rs.core.Context;
12 import javax.ws.rs.core.HttpHeaders;
13 import javax.ws.rs.core.MediaType;
14 import javax.ws.rs.core.Response;
15 import javax.ws.rs.sse.OutboundSseEvent;
16 import javax.ws.rs.sse.Sse;
17 import javax.ws.rs.sse.SseEventSink;
18 import java.util.concurrent.TimeUnit;
19
20 @Singleton
21 @Path("/reconnect")
22 public class SseReconnectResource {
23
24 private volatile boolean isServiceAvailable = false;
25
26 private volatile long startTime = 0L;
27 private volatile long endTime = 0L;
28
29 @GET
30 @Path("/defaultReconnectDelay")
31 @Produces(MediaType.TEXT_PLAIN)
32 public Response reconnectDelayNotSet(@Context Sse sse, @Context SseEventSink sseEventSink) {
33 OutboundSseEvent event = sse.newEventBuilder().id("1").data("test").build();
34 return Response.ok(event.getReconnectDelay()).build();
35 }
36
37 @GET
38 @Path("/reconnectDelaySet")
39 @Produces(MediaType.TEXT_PLAIN)
40 public Response reconnectDelaySet(@Context Sse sse, @Context SseEventSink sseEventSink) {
41 OutboundSseEvent event = sse.newEventBuilder().id("1").data("test").reconnectDelay(1000L).build();
42 return Response.ok(event.getReconnectDelay()).build();
43 }
44
45 @GET
46 @Path("/unavailable")
47 @Produces(MediaType.SERVER_SENT_EVENTS)
48 public void sendMessage(@Context SseEventSink sink, @Context Sse sse)
49 {
50 if (!isServiceAvailable)
51 {
52 isServiceAvailable = true;
53 startTime = System.currentTimeMillis();
54 throw new WebApplicationException(Response.status(503).header(HttpHeaders.RETRY_AFTER, String.valueOf(2))
55 .build());
56 }
57 else
58 {
59 endTime = System.currentTimeMillis() - startTime;
60 long elapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(endTime);
61 System.out.println("ELAPSED:" + elapsedSeconds);
62 Assert.assertTrue(elapsedSeconds >= 2);
63 try (SseEventSink s = sink)
64 {
65 s.send(sse.newEvent("ServiceAvailable"));
66 isServiceAvailable = false;
67 }
68 }
69 }
70 }
0 package org.jboss.resteasy.test.providers.sse.resource;
1
2 import org.jboss.resteasy.api.validation.ConstraintType;
3
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.Provider;
10 import java.io.BufferedWriter;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.io.OutputStreamWriter;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16
17 @Provider
18 @Produces("text/plain")
19 public class SseSmokeMessageBodyWriter implements MessageBodyWriter<SseSmokeUser> {
20
21 public long getSize(SseSmokeUser arg0, Class<?> arg1, ConstraintType.Type arg2, Annotation[] arg3, MediaType arg4) {
22 return getStringRepresentation(arg0).length();
23 }
24
25 public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
26 return true;
27 }
28
29 public void writeTo(SseSmokeUser arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4,
30 MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException {
31 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(arg6));
32 bw.write(getStringRepresentation(arg0));
33 bw.flush();
34 }
35
36 private String getStringRepresentation(SseSmokeUser user) {
37 return user.getUsername() + ";" + user.getEmail();
38 }
39 }
0 package org.jboss.resteasy.test.providers.sse.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Context;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.sse.Sse;
8 import javax.ws.rs.sse.SseEventSink;
9
10 @Path("/sse")
11 public class SseSmokeResource {
12
13 @GET
14 @Path("/events")
15 @Produces(MediaType.SERVER_SENT_EVENTS)
16 public void sentEvents(@Context SseEventSink sseEventSink, @Context Sse sse) {
17
18 try (SseEventSink sink = sseEventSink) {
19 sseEventSink.send(sse.newEventBuilder()
20 .name("customObj")
21 .data(new SseSmokeUser("Zeytin", "zeytin@resteasy.org")).build());
22 }
23 }
24 }
0 package org.jboss.resteasy.test.providers.sse.resource;
1
2 public class SseSmokeUser {
3 private String username;
4 private String email;
5
6 public SseSmokeUser() {
7 }
8
9 public SseSmokeUser(final String username, final String email) {
10 this.username = username;
11 this.email = email;
12 }
13
14 public String getUsername() {
15 return username;
16 }
17
18 public void setUsername(String username) {
19 this.username = username;
20 }
21
22 public String getEmail() {
23 return email;
24 }
25
26 public void setEmail(String email) {
27 this.email = email;
28 }
29 }
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.category.ExpectedFailing;
65 import org.jboss.resteasy.test.providers.yaml.resource.YamlPojoBindingNestedObject;
76 import org.jboss.resteasy.test.providers.yaml.resource.YamlPojoBindingObject;
87 import org.jboss.resteasy.test.providers.yaml.resource.YamlResource;
1312 import org.jboss.shrinkwrap.api.spec.WebArchive;
1413 import org.junit.Assert;
1514 import org.junit.Test;
16 import org.junit.experimental.categories.Category;
1715 import org.junit.runner.RunWith;
1816 import org.yaml.snakeyaml.Yaml;
1917
11
22 import org.jboss.arquillian.container.test.api.RunAsClient;
33 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.category.ExpectedFailing;
54 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
65 import org.junit.Assert;
76 import org.jboss.arquillian.container.test.api.Deployment;
1817 import org.junit.After;
1918 import org.junit.Before;
2019 import org.junit.Test;
21 import org.junit.experimental.categories.Category;
2220 import org.junit.runner.RunWith;
2321 import org.yaml.snakeyaml.Yaml;
2422
1818 import org.junit.Before;
1919 import org.junit.Test;
2020 import org.junit.runner.RunWith;
21 import org.junit.experimental.categories.Category;
22 import org.jboss.resteasy.category.NotForForwardCompatibility;
2123
2224 /**
2325 * @tpSubChapter Resources
2426 * @tpChapter Integration tests
2527 * @tpTestCaseDetails Add charset "UTF-8" to response mediatype if context parameter "resteasy.add.charset" is true
26 * @tpSince RESTEasy 3.1.1.Final
28 * @tpSince RESTEasy 3.0.21.Final
2729 */
2830 @RunWith(Arquillian.class)
2931 @RunAsClient
7072 }
7173
7274 @Test
75 @Category(NotForForwardCompatibility.class)
7376 public void testCharset() throws Exception {
74 doTest("_true", "/true", "/nocharset", "UTF-8"); // "resteasy.add.charset" set to true, text media type, charset not set
75 doTest("_true", "/true", "/charset", "UTF-16"); // "resteasy.add.charset" set to true, text media type, charset already set
76 doTest("_true", "/true", "/nomediatype", null); // "resteasy.add.charset" set to true, no mediatype set in response
77 doTest("_true", "/true", "/xml_nocharset", "UTF-8"); // "resteasy.add.charset" set to true, application/xml media type, charset not set
78 doTest("_true", "/true", "/xml_charset", "UTF-16"); // "resteasy.add.charset" set to true, application/xml media type, charset already set
79 doTest("_true", "/true", "/external", "UTF-8"); // "resteasy.add.charset" set to true, application/xml-... media type, charset not set
80 doTest("_true", "/true", "/json", null); // "resteasy.add.charset" set to true, application/json media type, charset not set
77 doTest("_true", "/true", "/nocharset", "UTF-8"); // "resteasy.add.charset" set to true, text media type, charset not set
78 doTest("_true", "/true", "/charset", "UTF-16"); // "resteasy.add.charset" set to true, text media type, charset already set
79 doTest("_true", "/true", "/nomediatype", null); // "resteasy.add.charset" set to true, no mediatype set in response
80 doTest("_true", "/true", "/xml_nocharset", "UTF-8"); // "resteasy.add.charset" set to true, application/xml media type, charset not set
81 doTest("_true", "/true", "/xml_charset", "UTF-16"); // "resteasy.add.charset" set to true, application/xml media type, charset already set
82 doTest("_true", "/true", "/external", "UTF-8"); // "resteasy.add.charset" set to true, application/xml-... media type, charset not set
83 doTest("_true", "/true", "/json", null); // "resteasy.add.charset" set to true, application/json media type, charset not set
8184
82 doTest("_false", "/false", "/nocharset", null); // "resteasy.add.charset" set to false, text media type, charset not set
83 doTest("_false", "/false", "/charset", "UTF-16"); // "resteasy.add.charset" set to false, text media type, charset already set
84 doTest("_false", "/false", "/nomediatype", null); // "resteasy.add.charset" set to false, no media type set in response
85 doTest("_false", "/false", "/xml_nocharset", null); // "resteasy.add.charset" set to false, application/xml media type, charset not set
86 doTest("_false", "/false", "/xml_charset", "UTF-16"); // "resteasy.add.charset" set to false, application/xml media type, charset already set
87 doTest("_false", "/false", "/external", null); // "resteasy.add.charset" set to false, application/xml-... media type, charset not set
88 doTest("_false", "/false", "/json", null); // "resteasy.add.charset" set to false, application/json media type, charset not set
85 doTest("_false", "/false", "/nocharset", null); // "resteasy.add.charset" set to false, text media type, charset not set
86 doTest("_false", "/false", "/charset", "UTF-16"); // "resteasy.add.charset" set to false, text media type, charset already set
87 doTest("_false", "/false", "/nomediatype", null); // "resteasy.add.charset" set to false, no media type set in response
88 doTest("_false", "/false", "/xml_nocharset", null); // "resteasy.add.charset" set to false, application/xml media type, charset not set
89 doTest("_false", "/false", "/xml_charset", "UTF-16"); // "resteasy.add.charset" set to false, application/xml media type, charset already set
90 doTest("_false", "/false", "/external", null); // "resteasy.add.charset" set to false, application/xml-... media type, charset not set
91 doTest("_false", "/false", "/json", null); // "resteasy.add.charset" set to false, application/json media type, charset not set
8992
90 doTest("_default", "/default", "/nocharset", "UTF-8"); // "resteasy.add.charset" not set, text media type, charset not set
91 doTest("_default", "/default", "/charset", "UTF-16"); // "resteasy.add.charset" not set, text media type, charset already set
92 doTest("_default", "/default", "/nomediatype", null); // "resteasy.add.charset" not set, no mediatype set in response
93 doTest("_default", "/default", "/xml_nocharset", "UTF-8"); // "resteasy.add.charset" not set, application/xml media type, charset not set
94 doTest("_default", "/default", "/xml_charset", "UTF-16"); // "resteasy.add.charset" not set, application/xml media type, charset already set
95 doTest("_default", "/default", "/external", "UTF-8"); // "resteasy.add.charset" not set, application/xml-... media type, charset not set
96 doTest("_default", "/default", "/json", null); // "resteasy.add.charset" not set, application/json media type, charset not set
93 doTest("_default", "/default", "/nocharset", "UTF-8"); // "resteasy.add.charset" not set, text media type, charset not set
94 doTest("_default", "/default", "/charset", "UTF-16"); // "resteasy.add.charset" not set, text media type, charset already set
95 doTest("_default", "/default", "/nomediatype", null); // "resteasy.add.charset" not set, no mediatype set in response
96 doTest("_default", "/default", "/xml_nocharset", "UTF-8"); // "resteasy.add.charset" not set, application/xml media type, charset not set
97 doTest("_default", "/default", "/xml_charset", "UTF-16"); // "resteasy.add.charset" not set, application/xml media type, charset already set
98 doTest("_default", "/default", "/external", "UTF-8"); // "resteasy.add.charset" not set, application/xml-... media type, charset not set
99 doTest("_default", "/default", "/json", null); // "resteasy.add.charset" not set, application/json media type, charset not set
97100 }
98101
99102 void doTest(String suffix, String mapping, String path, String expectedMediaType) throws Exception {
109109
110110 /**
111111 * @tpTestDetails Test that MessageBodyWriters can be consulted for media type
112 * @tpSince RESTEasy 3.1.3.Final
112 * @tpSince RESTEasy 3.0.23.Final
113113 */
114114 @Test
115115 @OperateOnDeployment("multiple")
137137 * @tpTestDetails Test use case described in RESTEASY-1227. If multiple Accept headers are send by the client the chosen
138138 * response Content-type will be the one which we are able to write (MessageBodyWriter exists for it), not the one
139139 * we are not able to write.
140 * @tpSince RESTEasy 3.1.3.Final
140 * @tpSince RESTEasy 3.0.23.Final
141141 */
142142 @Test
143143 @OperateOnDeployment("single")
+0
-125
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/MultipleAcceptHeaderTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.client.ClientBuilder;
6
7 import org.jboss.arquillian.container.test.api.Deployment;
8 import org.jboss.arquillian.container.test.api.RunAsClient;
9 import org.jboss.arquillian.junit.Arquillian;
10 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 @RunWith(Arquillian.class)
21 @RunAsClient
22 public class MultipleAcceptHeaderTest
23 {
24
25 protected static String APPLICATION_JSON = "Content-Type: application/json";
26
27 protected static String APPLICATION_XML = "Content-Type: application/xml";
28
29 private TestInterfaceClient service;
30
31 @Deployment
32 public static Archive<?> deploy() throws Exception
33 {
34 WebArchive war = TestUtil.prepareArchive(MultipleAcceptHeaderTest.class.getSimpleName());
35 return TestUtil.finishContainerPrepare(war, null, TestResourceServer.class);
36 }
37
38 private String generateBaseUrl()
39 {
40 return PortProviderUtil.generateBaseUrl(MultipleAcceptHeaderTest.class.getSimpleName());
41 }
42
43 @Path("/test")
44 static public class TestResourceServer
45 {
46 @GET
47 @Path("accept")
48 @Produces("application/json")
49 public String acceptJson()
50 {
51 return APPLICATION_JSON;
52 }
53
54 @GET
55 @Path("accept")
56 @Produces(
57 {"application/xml", "text/plain"})
58 public String acceptXml()
59 {
60 return APPLICATION_XML;
61 }
62 }
63
64 @Path("test")
65 interface TestInterfaceClient
66 {
67 @GET
68 @Path("accept")
69 @Produces("application/json")
70 public String getJson();
71
72 @GET
73 @Path("accept")
74 @Produces("application/xml")
75 public String getXml();
76
77 @GET
78 @Path("accept")
79 @Produces(
80 {"application/wrong1", "application/wrong2", "application/xml"})
81 public String getXmlMultiple();
82
83 @GET
84 @Path("accept")
85 @Produces(
86 {"application/wrong1", "text/plain"})
87 public String getXmlPlainMultiple();
88 }
89
90 @Before
91 public void setUp() throws Exception
92 {
93 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target(generateBaseUrl());
94 service = target.proxy(TestInterfaceClient.class);
95 }
96
97 @Test
98 public void testSingleAcceptHeader() throws Exception
99 {
100 String result = service.getJson();
101 Assert.assertEquals(APPLICATION_JSON, result);
102 }
103
104 @Test
105 public void testSingleAcceptHeader2() throws Exception
106 {
107 String result = service.getXml();
108 Assert.assertEquals(APPLICATION_XML, result);
109 }
110
111 @Test
112 public void testMultipleAcceptHeader() throws Exception
113 {
114 String result = service.getXmlMultiple();
115 Assert.assertEquals(APPLICATION_XML, result);
116 }
117
118 @Test
119 public void testMultipleAcceptHeaderSecondHeader() throws Exception
120 {
121 String result = service.getXmlPlainMultiple();
122 Assert.assertEquals(APPLICATION_XML, result);
123 }
124 }
2727 /**
2828 * @tpSubChapter Resources
2929 * @tpChapter Integration tests
30 * @tpTestCaseDetails Regression tests for RESTEASY-1398
31 * @tpSince RESTEasy 3.0.20
30 * @tpTestCaseDetails Multiple regression tests for logged warnings for the endpoints
31 * @tpSince RESTEasy 3.0.18.Final
3232 */
3333 @RunWith(Arquillian.class)
3434 @RunAsClient
6060 client.target(generateURL("/teardown")).request().get();
6161 client.close();
6262 }
63
63
64 /**
65 * @tpTestDetails RESTEASY-1398
66 * @tpSince RESTEasy 3.0.18.Final
67 */
6468 @Test
6569 public void testUnique() throws Exception {
6670 Response response = client.target(generateURL("/unique/")).request().accept(MediaType.TEXT_PLAIN).get();
7680 Assert.assertEquals("Incorrectly logged " + LogHandler.MESSAGE_CODE, new Long(0), response.readEntity(long.class));
7781 }
7882
83 /**
84 * @tpTestDetails RESTEASY-1398
85 * @tpSince RESTEasy 3.0.18.Final
86 */
7987 @Test
8088 public void testDifferentVerbs() throws Exception {
8189 Response response = client.target(generateURL("/verbs")).request().accept(MediaType.TEXT_PLAIN).get();
8896 Assert.assertEquals("Incorrectly logged " + LogHandler.MESSAGE_CODE, new Long(0), response.readEntity(long.class));
8997 }
9098
99 /**
100 * @tpTestDetails RESTEASY-1454
101 * @tpSince RESTEasy 3.0.20.Final
102 */
91103 @Test
92104 @Category({NotForForwardCompatibility.class})
93105 public void testDuplicate() throws Exception {
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
55 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
6 import org.jboss.resteasy.test.resource.basic.resource.ApplicationScopeObject;
67 import org.jboss.resteasy.test.resource.basic.resource.MultiInterfaceResLocatorResource;
78 import org.jboss.resteasy.test.resource.basic.resource.MultiInterfaceResLocatorSubresource;
9 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResClassSub;
810 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResConcreteSubImpl;
911 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResDoubleInterface;
1012 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResGenericInterface;
1416 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResRootImpl;
1517 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResSub;
1618 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResSubImpl;
19 import org.jboss.resteasy.test.resource.basic.resource.RequestScopedObject;
1720 import org.jboss.resteasy.util.HttpResponseCodes;
1821 import org.jboss.resteasy.util.Types;
1922 import org.jboss.resteasy.utils.PortProviderUtil;
2023 import org.jboss.resteasy.utils.TestUtil;
2124 import org.jboss.shrinkwrap.api.Archive;
25 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
2226 import org.jboss.shrinkwrap.api.spec.WebArchive;
2327 import org.junit.After;
2428 import org.junit.Assert;
5155 war.addClass(ParameterSubResGenericInterface.class);
5256 war.addClass(ParameterSubResInternalInterface.class);
5357 war.addClass(ParameterSubResRoot.class);
58 war.addClass(ParameterSubResClassSub.class);
59 war.addClass(ApplicationScopeObject.class);
60 war.addClass(RequestScopedObject.class);
5461 war.addClass(ParameterSubResSub.class);
5562 war.addClass(ParameterSubResSubImpl.class);
63 war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
5664 return TestUtil.finishContainerPrepare(war, null, ParameterSubResRootImpl.class, ParameterSubResGenericSub.class);
5765 }
5866
9098 Assert.assertEquals("Wrong content of response", "Boo! - fred", response.readEntity(String.class));
9199 }
92100
101
102 @Test
103 public void testReturnSubResourceAsClass() throws Exception {
104 Response response = client.target(generateURL("/path/subclass")).request().get();
105 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
106 Assert.assertEquals("Wrong response", "resourceCounter:1,appscope:1,requestScope:1", response.readEntity(String.class));
107 response = client.target(generateURL("/path/subclass")).request().get();
108 Assert.assertEquals("Wrong response", "resourceCounter:2,appscope:2,requestScope:1", response.readEntity(String.class));
109 }
110
93111 /**
94112 * @tpTestDetails Check root resource.
95113 * @tpSince RESTEasy 3.0.16
143143 Assert.assertEquals("got", response.readEntity(String.class));
144144 Assert.assertNotNull(response.getHeaderString("Content-Type"));
145145 Assert.assertNotNull(response.getHeaderString("Content-Type"));
146 Assert.assertEquals(MediaType.TEXT_PLAIN_TYPE.withCharset("UTF-8").toString(), response.getHeaderString("Content-Type"));
146 Assert.assertEquals(MediaType.TEXT_PLAIN+";charset=UTF-8", response.getHeaderString("Content-Type"));
147147 }
148148
149149 {
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
57 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
68 import org.jboss.resteasy.spi.ResteasyProviderFactory;
79 import org.jboss.resteasy.test.resource.basic.resource.ScanProxy;
5557 }
5658
5759 /**
60 * @tpTestDetails Test with old client
61 * @tpSince RESTEasy 3.0.16
62 */
63 @Test
64 public void testOldClient() throws Exception {
65 RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
66 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/test/doit", ScanTest.class.getSimpleName()));
67 ClientResponse response = request.get();
68 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
69 Assert.assertEquals("Wrong content of response", "hello world", response.getEntity(String.class));
70 }
71
72 /**
5873 * @tpTestDetails Test with new client
5974 * @tpSince RESTEasy 3.0.16
6075 */
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import java.util.concurrent.atomic.AtomicInteger;
3
4 import javax.enterprise.context.ApplicationScoped;
5
6 @ApplicationScoped
7 public class ApplicationScopeObject
8 {
9 AtomicInteger counter = new AtomicInteger();
10
11 public int getCount()
12 {
13 return counter.incrementAndGet();
14 }
15 }
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import java.util.concurrent.atomic.AtomicInteger;
3
4 import javax.enterprise.context.ApplicationScoped;
5 import javax.inject.Inject;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.HttpHeaders;
10 import javax.ws.rs.core.UriInfo;
11
12 import org.junit.Assert;
13 @ApplicationScoped
14 public class ParameterSubResClassSub
15 {
16 AtomicInteger resourceCounter = new AtomicInteger();
17 @Inject
18 ApplicationScopeObject appScope;
19
20 @Inject
21 RequestScopedObject requestScope;
22
23 @Context UriInfo uriInfo;
24
25 @GET
26 @Produces("text/plain")
27 public String get(@Context HttpHeaders headers)
28 {
29 Assert.assertEquals("Wrong path value from injected UriInfo", "/path/subclass", uriInfo.getPath());
30 Assert.assertNotNull("Connection header from injected HttpHeaders is null", headers.getHeaderString("Connection"));
31 return "resourceCounter:" + resourceCounter.incrementAndGet() + ",appscope:" + appScope.getCount() + ",requestScope:" + requestScope.getCount();
32 }
33 }
55 public interface ParameterSubResRoot {
66 @Path("sub/{path}")
77 ParameterSubResSub getSub(@PathParam("path") String path);
8 @Path("subclass")
9 Class<ParameterSubResClassSub> getSubClass();
810 }
99 return new ParameterSubResSubImpl<Integer>(path) {
1010 };
1111 }
12 @Override
13 public Class<ParameterSubResClassSub> getSubClass()
14 {
15 return ParameterSubResClassSub.class;
16 }
1217
1318 }
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import java.util.concurrent.atomic.AtomicInteger;
3
4 import javax.enterprise.context.RequestScoped;
5
6 @RequestScoped
7 public class RequestScopedObject
8 {
9
10 AtomicInteger count = new AtomicInteger();
11 public int getCount() {
12 return count.incrementAndGet();
13 }
14 }
2929 import javax.ws.rs.client.Invocation;
3030 import javax.ws.rs.core.Response;
3131 import java.lang.reflect.ReflectPermission;
32 import java.net.SocketPermission;
3233 import java.util.Date;
3334 import java.util.PropertyPermission;
35 import java.util.logging.LoggingPermission;
3436
3537 /**
3638 * @tpSubChapter Parameters
5860 war.addClass(PortProviderUtil.class);
5961 war.addClass(HeaderDelegateTest.class);
6062 // Arquillian in the deployment
61 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
63 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
64 new LoggingPermission("control", ""),
65 new PropertyPermission("arquillian.*", "read"),
66 new PropertyPermission("ipv6", "read"),
67 new PropertyPermission("node", "read"),
68 new PropertyPermission("org.jboss.resteasy.port", "read"),
69 new ReflectPermission("suppressAccessChecks"),
6270 new RuntimePermission("accessDeclaredMembers"),
63 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
71 new RuntimePermission("getenv.RESTEASY_PORT"),
72 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
73 ), "permissions.xml");
6474 return TestUtil.finishContainerPrepare(war, null, HeaderDelegateResource.class);
6575 }
6676
+0
-86
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/MatrixPathParamTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.MatrixParam;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.client.ClientBuilder;
6
7 import org.jboss.arquillian.container.test.api.Deployment;
8 import org.jboss.arquillian.container.test.api.RunAsClient;
9 import org.jboss.arquillian.junit.Arquillian;
10 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 @RunWith(Arquillian.class)
20 @RunAsClient
21 public class MatrixPathParamTest
22 {
23
24 @Deployment
25 public static Archive<?> deploy() throws Exception {
26 WebArchive war = TestUtil.prepareArchive(MatrixPathParamTest.class.getSimpleName());
27 return TestUtil.finishContainerPrepare(war, null, TestResourceServer.class, TestSubResourceServer.class);
28 }
29
30 private String generateBaseUrl() {
31 return PortProviderUtil.generateBaseUrl(MatrixPathParamTest.class.getSimpleName());
32 }
33
34 @Path("/")
35 static public class TestResourceServer
36 {
37 @Path("matrix1")
38 public TestSubResourceServer getM1(@MatrixParam("m1") String m1)
39 {
40 return new TestSubResourceServer(m1);
41 }
42 }
43
44 static public class TestSubResourceServer
45 {
46 protected String m1;
47
48 TestSubResourceServer(String m1)
49 {
50 this.m1 = m1;
51 }
52
53 @GET
54 @Path("matrix2")
55 public String getM2(@MatrixParam("m2") String m2)
56 {
57 return m1 + m2;
58 }
59 }
60
61 @Path("/")
62 public interface TestInterfaceClient
63 {
64 @Path("matrix1")
65 public TestSubInterfaceClient getM1(@MatrixParam("m1") String m1);
66 }
67
68 public interface TestSubInterfaceClient
69 {
70 @GET
71 @Path("matrix2")
72 public String getM2(@MatrixParam("m2") String m2);
73 }
74
75 @Test
76 public void testSingleAcceptHeader() throws Exception
77 {
78 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target(generateBaseUrl());
79 TestInterfaceClient proxy = target.proxy(TestInterfaceClient.class);
80
81 String result = proxy.getM1("a").getM2("b");
82 Assert.assertEquals("ab", result);
83 }
84
85 }
0 package org.jboss.resteasy.test.resource.param;
1
2 import java.util.ArrayList;
3 import java.util.Arrays;
4 import java.util.HashSet;
5 import java.util.List;
6 import java.util.TreeSet;
7
8 import org.jboss.arquillian.container.test.api.Deployment;
9 import org.jboss.arquillian.container.test.api.RunAsClient;
10 import org.jboss.arquillian.junit.Arquillian;
11 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
12 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
13 import org.jboss.resteasy.test.resource.param.resource.CookieParamWrapper;
14 import org.jboss.resteasy.test.resource.param.resource.CookieParamWrapperArrayConverter;
15 import org.jboss.resteasy.test.resource.param.resource.DateParamConverter;
16 import org.jboss.resteasy.test.resource.param.resource.MultiValuedCookieParam;
17 import org.jboss.resteasy.test.resource.param.resource.MultiValuedCookieParamConverter;
18 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParam;
19 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamConverter;
20 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamConverterProvider;
21 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamResource;
22 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamResourceClient;
23 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamResourceClient.CookieParamResourceClient;
24 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamResourceClient.FormParamResourceClient;
25 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamResourceClient.HeaderParamResourceClient;
26 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamResourceClient.MatrixParamResourceClient;
27 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamResourceClient.PathParamResourceClient;
28 import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamResourceClient.QueryParamResourceClient;
29 import org.jboss.resteasy.test.resource.param.resource.MultiValuedPathParam;
30 import org.jboss.resteasy.test.resource.param.resource.MultiValuedPathParamConverter;
31 import org.jboss.resteasy.test.resource.param.resource.ParamWrapper;
32 import org.jboss.resteasy.test.resource.param.resource.ParamWrapperArrayConverter;
33 import org.jboss.resteasy.test.resource.param.resource.PathParamWrapper;
34 import org.jboss.resteasy.test.resource.param.resource.PathParamWrapperArrayConverter;
35 import org.jboss.resteasy.utils.PortProviderUtil;
36 import org.jboss.resteasy.utils.TestUtil;
37 import org.jboss.shrinkwrap.api.Archive;
38 import org.jboss.shrinkwrap.api.spec.WebArchive;
39 import org.junit.Assert;
40 import org.junit.Test;
41 import org.junit.runner.RunWith;
42
43 /**
44 * @tpSubChapter Parameters
45 * @tpChapter Integration tests
46 * @tpTestCaseDetails Test for ParamConverter
47 * @tpSince RESTEasy 3.5.
48 */
49 @RunWith(Arquillian.class)
50 @RunAsClient
51 public class MultiValuedParamTest {
52
53 @Deployment
54 public static Archive<?> deploy() {
55 WebArchive war = TestUtil.prepareArchive(MultiValuedParamTest.class.getSimpleName());
56 war.addClass(MultiValuedParam.class);
57 war.addClass(ParamWrapper.class);
58 war.addClass(MultiValuedCookieParam.class);
59 war.addClass(CookieParamWrapper.class);
60 war.addClass(MultiValuedPathParam.class);
61 war.addClass(PathParamWrapper.class);
62 war.addClass(DateParamConverter.class);
63 war.addClass(MultiValuedParamConverter.class);
64 war.addClass(ParamWrapperArrayConverter.class);
65 war.addClass(MultiValuedCookieParamConverter.class);
66 war.addClass(CookieParamWrapperArrayConverter.class);
67 war.addClass(MultiValuedPathParamConverter.class);
68 war.addClass(PathParamWrapperArrayConverter.class);
69 war.addClass(MultiValuedParamResourceClient.class);
70 return TestUtil.finishContainerPrepare(war, null, MultiValuedParamConverterProvider.class,
71 MultiValuedParamResource.class, MultiValuedParamResource.QueryParamResource.class, MultiValuedParamResource.HeaderParamResource.class,
72 MultiValuedParamResource.MatrixParamResource.class, MultiValuedParamResource.CookieParamResource.class, MultiValuedParamResource.FormParamResource.class,
73 MultiValuedParamResource.PathParamResource.class);
74 }
75
76 private String generateBaseUrl() {
77 return PortProviderUtil.generateBaseUrl(MultiValuedParamTest.class.getSimpleName());
78 }
79
80 /**
81 * @tpTestDetails Set specific values
82 * @tpSince RESTEasy 3.5
83 */
84 @Test
85 public void testQueryParam() throws Exception {
86 ResteasyClient client = new ResteasyClientBuilder().build();
87 try {
88 QueryParamResourceClient queryParamResourceClient = client.target(generateBaseUrl()).proxy(MultiValuedParamResourceClient.class).queryParam();
89
90 String date1 = "20161217";
91 String date2 = "20161218";
92 String date3 = "20161219";
93
94 Assert.assertEquals(date1 + "," + date2 + "," + date3, queryParamResourceClient.customConversion_multiValuedParam(date1 + "," + date2 + "," + date3));
95 Assert.assertEquals(date1 + "," + date2 + "," + date3, queryParamResourceClient.customConversion_multiValuedParam_array(date1 + "," + date2 + "," + date3));
96
97 List<String> dates=Arrays.asList(date1, date2, date3);
98
99 String expectedResponse= date1 + "," + date2 + "," + date3;
100 Assert.assertEquals(expectedResponse, queryParamResourceClient.defaultConversion_list(dates));
101 Assert.assertEquals(expectedResponse, queryParamResourceClient.defaultConversion_arrayList(new ArrayList<>(dates)));
102
103 Assert.assertEquals(expectedResponse, queryParamResourceClient.defaultConversion_set(new HashSet<>(dates)));
104 Assert.assertEquals(expectedResponse, queryParamResourceClient.defaultConversion_hashSet(new HashSet<>(dates)));
105
106 Assert.assertEquals(expectedResponse, queryParamResourceClient.defaultConversion_sortedSet(new TreeSet<>(dates)));
107 Assert.assertEquals(expectedResponse, queryParamResourceClient.defaultConversion_treeSet(new TreeSet<>(dates)));
108
109 Assert.assertEquals(expectedResponse, queryParamResourceClient.defaultConversion_array(dates.toArray(new String[dates.size()])));
110 } finally {
111 client.close();
112 }
113 }
114
115
116 /**
117 * @tpTestDetails Set specific values
118 * @tpSince RESTEasy 3.5
119 */
120 @Test
121 public void testHeaderParam() throws Exception {
122 ResteasyClient client = new ResteasyClientBuilder().build();
123 try {
124 HeaderParamResourceClient headerParamResourceClient = client.target(generateBaseUrl()).proxy(MultiValuedParamResourceClient.class).headerParam();
125
126 String date1 = "20161217";
127 String date2 = "20161218";
128 String date3 = "20161219";
129
130 Assert.assertEquals(date1 + "," + date2 + "," + date3, headerParamResourceClient.customConversion_multiValuedParam(date1 + "," + date2 + "," + date3));
131 Assert.assertEquals(date1 + "," + date2 + "," + date3, headerParamResourceClient.customConversion_multiValuedParam_array(date1 + "," + date2 + "," + date3));
132
133 List<String> dates=Arrays.asList(date1, date2, date3);
134
135 String expectedResponse= date1 + "," + date2 + "," + date3;
136 Assert.assertEquals(expectedResponse, headerParamResourceClient.defaultConversion_list(dates));
137 Assert.assertEquals(expectedResponse, headerParamResourceClient.defaultConversion_arrayList(new ArrayList<>(dates)));
138
139 Assert.assertEquals(expectedResponse, headerParamResourceClient.defaultConversion_set(new HashSet<>(dates)));
140 Assert.assertEquals(expectedResponse, headerParamResourceClient.defaultConversion_hashSet(new HashSet<>(dates)));
141
142 Assert.assertEquals(expectedResponse, headerParamResourceClient.defaultConversion_sortedSet(new TreeSet<>(dates)));
143 Assert.assertEquals(expectedResponse, headerParamResourceClient.defaultConversion_treeSet(new TreeSet<>(dates)));
144
145 Assert.assertEquals(expectedResponse, headerParamResourceClient.defaultConversion_array(dates.toArray(new String[dates.size()])));
146 } finally {
147 client.close();
148 }
149 }
150
151 /**
152 * @tpTestDetails Set specific values
153 * @tpSince RESTEasy 3.5
154 */
155 @Test
156 public void testMatrixParam() throws Exception {
157 ResteasyClient client = new ResteasyClientBuilder().build();
158 try {
159 MatrixParamResourceClient matrixParamResourceClient = client.target(generateBaseUrl()).proxy(MultiValuedParamResourceClient.class).matrixParam();
160
161 String date1 = "20161217";
162 String date2 = "20161218";
163 String date3 = "20161219";
164
165 Assert.assertEquals(date1 + "," + date2 + "," + date3, matrixParamResourceClient.customConversion_multiValuedParam(date1 + "," + date2 + "," + date3));
166 Assert.assertEquals(date1 + "," + date2 + "," + date3, matrixParamResourceClient.customConversion_multiValuedParam_array(date1 + "," + date2 + "," + date3));
167
168 List<String> dates=Arrays.asList(date1, date2, date3);
169
170 String expectedResponse= date1 + "," + date2 + "," + date3;
171 Assert.assertEquals(expectedResponse, matrixParamResourceClient.defaultConversion_list(dates));
172 Assert.assertEquals(expectedResponse, matrixParamResourceClient.defaultConversion_arrayList(new ArrayList<>(dates)));
173
174 Assert.assertEquals(expectedResponse, matrixParamResourceClient.defaultConversion_set(new HashSet<>(dates)));
175 Assert.assertEquals(expectedResponse,matrixParamResourceClient.defaultConversion_hashSet(new HashSet<>(dates)));
176
177 Assert.assertEquals(expectedResponse, matrixParamResourceClient.defaultConversion_sortedSet(new TreeSet<>(dates)));
178 Assert.assertEquals(expectedResponse, matrixParamResourceClient.defaultConversion_treeSet(new TreeSet<>(dates)));
179
180 Assert.assertEquals(expectedResponse, matrixParamResourceClient.defaultConversion_array(dates.toArray(new String[dates.size()])));
181 } finally {
182 client.close();
183 }
184 }
185
186 /**
187 * @tpTestDetails Set specific values
188 * @tpSince RESTEasy 3.5
189 */
190 @Test
191 public void testCookieParam() throws Exception {
192 ResteasyClient client = new ResteasyClientBuilder().build();
193 try {
194 CookieParamResourceClient cookieParamResourceClient = client.target(generateBaseUrl()).proxy(MultiValuedParamResourceClient.class).cookieParam();
195
196 String date1 = "20161217";
197 String date2 = "20161218";
198 String date3 = "20161219";
199
200 Assert.assertEquals(date1 + "," + date2 + "," + date3, cookieParamResourceClient.customConversion_multiValuedCookieParam(date1 + "-" + date2 + "-" + date3));
201 Assert.assertEquals(date1 + "," + date2 + "," + date3, cookieParamResourceClient.customConversion_multiValuedCookieParam_array(date1 + "-" + date2 + "-" + date3));
202
203 Assert.assertEquals(date1, cookieParamResourceClient.defaultConversion_list(date1));
204 Assert.assertEquals(date1, cookieParamResourceClient.defaultConversion_arrayList(date1));
205
206 Assert.assertEquals(date1, cookieParamResourceClient.defaultConversion_set(date1));
207 Assert.assertEquals(date1, cookieParamResourceClient.defaultConversion_hashSet(date1));
208
209 Assert.assertEquals(date1, cookieParamResourceClient.defaultConversion_sortedSet(date1));
210 Assert.assertEquals(date1, cookieParamResourceClient.defaultConversion_treeSet(date1));
211
212 Assert.assertEquals(date1, cookieParamResourceClient.defaultConversion_array(date1));
213 } finally {
214 client.close();
215 }
216 }
217
218 /**
219 * @tpTestDetails Set specific values
220 * @tpSince RESTEasy 3.5
221 */
222 @Test
223 public void testFormParam() throws Exception {
224 ResteasyClient client = new ResteasyClientBuilder().build();
225 try {
226 FormParamResourceClient formParamResourceClient = client.target(generateBaseUrl()).proxy(MultiValuedParamResourceClient.class).formParam();
227
228 String date1 = "20161217";
229 String date2 = "20161218";
230 String date3 = "20161219";
231
232 Assert.assertEquals(date1 + "," + date2 + "," + date3, formParamResourceClient.customConversion_multiValuedParam(date1 + "," + date2 + "," + date3));
233 Assert.assertEquals(date1 + "," + date2 + "," + date3, formParamResourceClient.customConversion_multiValuedParam_array(date1 + "," + date2 + "," + date3));
234
235 List<String> dates=Arrays.asList(date1, date2, date3);
236
237 String expectedResponse= date1 + "," + date2 + "," + date3;
238 Assert.assertEquals(expectedResponse, formParamResourceClient.defaultConversion_list(dates));
239 Assert.assertEquals(expectedResponse, formParamResourceClient.defaultConversion_arrayList(new ArrayList<>(dates)));
240
241 Assert.assertEquals(expectedResponse, formParamResourceClient.defaultConversion_set(new HashSet<>(dates)));
242 Assert.assertEquals(expectedResponse,formParamResourceClient.defaultConversion_hashSet(new HashSet<>(dates)));
243
244 Assert.assertEquals(expectedResponse, formParamResourceClient.defaultConversion_sortedSet(new TreeSet<>(dates)));
245 Assert.assertEquals(expectedResponse, formParamResourceClient.defaultConversion_treeSet(new TreeSet<>(dates)));
246
247 Assert.assertEquals(expectedResponse, formParamResourceClient.defaultConversion_array(dates.toArray(new String[dates.size()])));
248 } finally {
249 client.close();
250 }
251 }
252
253 /**
254 * @tpTestDetails Set specific values
255 * @tpSince RESTEasy 3.5
256 */
257 @Test
258 public void testPathParam() throws Exception {
259 ResteasyClient client = new ResteasyClientBuilder().build();
260 try {
261 PathParamResourceClient pathParamResourceClient = client.target(generateBaseUrl()).proxy(MultiValuedParamResourceClient.class).pathParam();
262
263 String path1 = "20161217";
264 String path2 = "20161218";
265 String path3 = "20161219";
266
267 Assert.assertEquals(path1 + "," + path2 + "," + path3, pathParamResourceClient.customConversion_multiValuedPathParam(path1, path2, path3));
268 Assert.assertEquals(path1 + "," + path2 + "," + path3, pathParamResourceClient.customConversion_multiValuedPathParam_array(path1, path2, path3));
269
270 Assert.assertEquals(path1, pathParamResourceClient.defaultConversion_list(path1));
271 Assert.assertEquals(path1, pathParamResourceClient.defaultConversion_arrayList(path1));
272
273 Assert.assertEquals(path1, pathParamResourceClient.defaultConversion_set(path1));
274 Assert.assertEquals(path1, pathParamResourceClient.defaultConversion_hashSet(path1));
275
276 Assert.assertEquals(path1, pathParamResourceClient.defaultConversion_sortedSet(path1));
277 Assert.assertEquals(path1, pathParamResourceClient.defaultConversion_treeSet(path1));
278
279 Assert.assertEquals(path1, pathParamResourceClient.defaultConversion_array(path1));
280 } finally {
281 client.close();
282 }
283 }
284
285 }
2222 * @tpSubChapter Parameters
2323 * @tpChapter Integration tests
2424 * @tpTestCaseDetails Test for @PathParam capturing multiple PathSegments (RESTEASY-1653)
25 * @tpSince RESTEasy 3.1.3.Final
25 * @tpSince RESTEasy 3.0.23.Final
2626 */
2727 @RunWith(Arquillian.class)
2828 @RunAsClient
5252
5353 /**
5454 * @tpTestDetails Array of PathSegments captured by wildcard
55 * @tpSince RESTEasy 3.1.3.Final
55 * @tpSince RESTEasy 3.0.23.Final
5656 */
5757 @Test
5858 public void testWildcardArray() throws Exception
6666
6767 /**
6868 * @tpTestDetails List of PathSegments captured by wildcard
69 * @tpSince RESTEasy 3.1.3.Final
69 * @tpSince RESTEasy 3.0.23.Final
7070 */
7171 @Test
7272 public void testWildcardList() throws Exception
8080
8181 /**
8282 * @tpTestDetails ArrayList of PathSegments captured by wildcard
83 * @tpSince RESTEasy 3.1.3.Final
83 * @tpSince RESTEasy 3.0.23.Final
8484 */
8585 @Test
8686 public void testWildcardArrayList() throws Exception
9494
9595 /**
9696 * @tpTestDetails Array of PathSegments captured by two separate segments with the same name
97 * @tpSince RESTEasy 3.1.3.Final
97 * @tpSince RESTEasy 3.0.23.Final
9898 */
9999 @Test
100100 public void testTwoSegmentsArray() throws Exception
108108
109109 /**
110110 * @tpTestDetails List of PathSegments captured by two separate segments with the same name
111 * @tpSince RESTEasy 3.1.3.Final
111 * @tpSince RESTEasy 3.0.23.Final
112112 */
113113 @Test
114114 public void testTwoSegmentsList() throws Exception
122122
123123 /**
124124 * @tpTestDetails ArrayList of PathSegments captured by two separate segments with the same name
125 * @tpSince RESTEasy 3.1.3.Final
125 * @tpSince RESTEasy 3.0.23.Final
126126 */
127127 @Test
128128 public void testTwoSegmentsArrayList() throws Exception
00 package org.jboss.resteasy.test.resource.param;
1
2 import javax.ws.rs.client.ClientBuilder;
31
42 import org.jboss.arquillian.container.test.api.Deployment;
53 import org.jboss.arquillian.container.test.api.RunAsClient;
64 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
5 import org.jboss.resteasy.client.ProxyFactory;
86 import org.jboss.resteasy.test.resource.param.resource.ParamInterfaceResource;
97 import org.jboss.resteasy.test.resource.param.resource.ParamResource;
108 import org.jboss.resteasy.utils.PortProviderUtil;
4341 */
4442 @Test
4543 public void testNullMatrixParam() throws Exception {
46 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target(generateBaseUrl());
47 ParamInterfaceResource proxy = target.proxy(ParamInterfaceResource.class);
44 ParamInterfaceResource proxy = ProxyFactory.create(ParamInterfaceResource.class, generateBaseUrl());
4845 String rtn = proxy.getMatrix(null);
4946 Assert.assertEquals("null", rtn);
5047 }
5653 */
5754 @Test
5855 public void testNullCookieParam() throws Exception {
59 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target(generateBaseUrl());
60 ParamInterfaceResource proxy = target.proxy(ParamInterfaceResource.class);
56 ParamInterfaceResource proxy = ProxyFactory.create(ParamInterfaceResource.class, generateBaseUrl());
6157 String rtn = proxy.getCookie(null);
6258 Assert.assertEquals("null", rtn);
6359 }
6965 */
7066 @Test
7167 public void testNullHeaderParam() throws Exception {
72 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target(generateBaseUrl());
73 ParamInterfaceResource proxy = target.proxy(ParamInterfaceResource.class);
68 ParamInterfaceResource proxy = ProxyFactory.create(ParamInterfaceResource.class, generateBaseUrl());
7469 String rtn = proxy.getHeader(null);
7570 Assert.assertEquals("null", rtn);
7671 }
77 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
88 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterCompany;
99 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterCompanyConverter;
10 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterCompanyConverterProvider;
1110 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterMyClient;
1211 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterObjectConverter;
1312 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterPerson;
1413 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterPersonConverter;
15 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterPersonConverterProvider;
1614 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterResource;
1715 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterSuperPersonConverter;
1816 import org.jboss.resteasy.utils.PortProviderUtil;
4139 war.addClass(SuperStringConverterPerson.class);
4240 war.addClass(SuperStringConverterObjectConverter.class);
4341 war.addClass(SuperStringConverterSuperPersonConverter.class);
44 war.addClass(SuperStringConverterPersonConverterProvider.class);
4542 war.addClass(SuperStringConverterMyClient.class);
4643 war.addClass(SuperStringConverterCompany.class);
47 war.addClass(SuperStringConverterCompanyConverterProvider.class);
4844 return TestUtil.finishContainerPrepare(war, null, SuperStringConverterPersonConverter.class,
49 SuperStringConverterCompanyConverter.class, SuperStringConverterCompanyConverterProvider.class,
45 SuperStringConverterCompanyConverter.class,
5046 SuperStringConverterResource.class);
5147 }
5248
6157 @Test
6258 public void testPerson() throws Exception {
6359 ResteasyClient client = new ResteasyClientBuilder().build();
64 client.register(SuperStringConverterPersonConverterProvider.class);
65 client.register(SuperStringConverterCompanyConverterProvider.class);
60 client.register(SuperStringConverterPersonConverter.class);
61 client.register(SuperStringConverterCompanyConverter.class);
6662
6763 SuperStringConverterMyClient proxy = ProxyBuilder.builder(SuperStringConverterMyClient.class, client.target(generateBaseUrl())).build();
6864 SuperStringConverterPerson person = new SuperStringConverterPerson("name");
7773 @Test
7874 public void testCompany() throws Exception {
7975 ResteasyClient client = new ResteasyClientBuilder().build();
80 client.register(SuperStringConverterPersonConverterProvider.class);
81 client.register(SuperStringConverterCompanyConverterProvider.class);
76 client.register(SuperStringConverterPersonConverter.class);
77 client.register(SuperStringConverterCompanyConverter.class);
8278 SuperStringConverterMyClient proxy = ProxyBuilder.builder(SuperStringConverterMyClient.class, client.target(generateBaseUrl())).build();
8379 SuperStringConverterCompany company = new SuperStringConverterCompany("name");
8480 proxy.putCompany(company);
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 /***
3 *
4 * @author Nicolas NESMON
5 *
6 * @param <E>
7 */
8 public class CookieParamWrapper<E> {
9
10 private final E element;
11
12 public CookieParamWrapper(E element) {
13 this.element = element;
14 }
15
16 public E getElement() {
17 return element;
18 }
19
20 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.lang.reflect.Array;
3
4 import javax.ws.rs.ext.ParamConverter;
5
6 /**
7 *
8 * @author Nicolas NESMON
9 *
10 */
11
12 public class CookieParamWrapperArrayConverter implements ParamConverter<CookieParamWrapper<Object>[]> {
13
14 private final ParamConverter<Object> paramConverter;
15
16 public CookieParamWrapperArrayConverter(ParamConverter<Object> paramConverter) {
17 this.paramConverter = paramConverter;
18 }
19
20 @Override
21 public CookieParamWrapper<Object>[] fromString(String param) {
22 if (param == null || param.trim().isEmpty()) {
23 return null;
24 }
25 String[] params = param.split("-");
26 @SuppressWarnings("unchecked")
27 CookieParamWrapper<Object>[] array = (CookieParamWrapper<Object>[]) Array.newInstance(CookieParamWrapper.class,
28 params.length);
29 for (int i = 0; i < params.length; i++) {
30 array[i] = new CookieParamWrapper<>(this.paramConverter.fromString(params[i]));
31 }
32 return array;
33 }
34
35 @Override
36 public String toString(CookieParamWrapper<Object>[] array) {
37 if (array == null || array.length == 0) {
38 return null;
39 }
40 StringBuilder stringBuilder = new StringBuilder();
41 int size = array.length;
42 for (int i = 0; i < array.length; i++) {
43 stringBuilder.append(this.paramConverter.toString(array[i].getElement()));
44 if (i != size) {
45 stringBuilder.append('-');
46 }
47 }
48 return stringBuilder.toString();
49 }
50
51 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.text.ParseException;
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5
6 import javax.ws.rs.BadRequestException;
7 import javax.ws.rs.ext.ParamConverter;
8
9 public class DateParamConverter implements ParamConverter<Date> {
10
11 public static final String DATE_PATTERN = "yyyyMMdd";
12
13 @Override
14 public Date fromString(String param) {
15 try {
16 return new SimpleDateFormat(DATE_PATTERN).parse(param.trim());
17 } catch (ParseException e) {
18 throw new BadRequestException(e);
19 }
20 }
21
22 @Override
23 public String toString(Date date) {
24 return new SimpleDateFormat(DATE_PATTERN).format(date);
25 }
26
27 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.util.LinkedList;
3
4 public class MultiValuedCookieParam<E> extends LinkedList<E> {
5
6 private static final long serialVersionUID = 1L;
7 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.ext.ParamConverter;
3
4 public class MultiValuedCookieParamConverter implements ParamConverter<MultiValuedCookieParam<?>> {
5
6 private final ParamConverter<?> paramConverter;
7
8 public MultiValuedCookieParamConverter(ParamConverter<?> paramConverter) {
9 this.paramConverter = paramConverter;
10 }
11
12 @Override
13 public MultiValuedCookieParam<?> fromString(String param) {
14 if (param == null || param.trim().isEmpty()) {
15 return null;
16 }
17 return parse(param.split("-"), this.paramConverter);
18 }
19
20 @Override
21 public String toString(MultiValuedCookieParam<?> multiValuedCookieParam) {
22 if (multiValuedCookieParam == null || multiValuedCookieParam.isEmpty()) {
23 return null;
24 }
25 return format(multiValuedCookieParam, this.paramConverter);
26 }
27
28 private static <T> MultiValuedCookieParam<T> parse(String[] params, ParamConverter<T> paramConverter) {
29 MultiValuedCookieParam<T> multiValuedCookieParam = new MultiValuedCookieParam<>();
30 for (String param : params) {
31 multiValuedCookieParam.add(paramConverter.fromString(param));
32 }
33 return multiValuedCookieParam;
34 }
35
36 @SuppressWarnings("unchecked")
37 private static <T> String format(MultiValuedCookieParam<?> multiValuedCookieParam,
38 ParamConverter<T> paramConverter) {
39 StringBuilder stringBuilder = new StringBuilder();
40 int size = multiValuedCookieParam.size();
41 for (int i = 0; i < size; i++) {
42 stringBuilder.append(paramConverter.toString((T) multiValuedCookieParam.get(i)));
43 if (i != size - 1) {
44 stringBuilder.append('-');
45 }
46 }
47 return stringBuilder.toString();
48 }
49
50 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.util.LinkedList;
3
4 public class MultiValuedParam<E> extends LinkedList<E> {
5
6 private static final long serialVersionUID = 1L;
7 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.ext.ParamConverter;
3
4 public class MultiValuedParamConverter implements ParamConverter<MultiValuedParam<?>> {
5
6 private final ParamConverter<?> paramConverter;
7
8 public MultiValuedParamConverter(ParamConverter<?> paramConverter) {
9 this.paramConverter = paramConverter;
10 }
11
12 @Override
13 public MultiValuedParam<?> fromString(String param) {
14 if (param == null || param.trim().isEmpty()) {
15 return null;
16 }
17 return parse(param.split(","), this.paramConverter);
18 }
19
20 @Override
21 public String toString(MultiValuedParam<?> multiValuedParam) {
22 if (multiValuedParam == null || multiValuedParam.isEmpty()) {
23 return null;
24 }
25 return format(multiValuedParam, this.paramConverter);
26 }
27
28 private static <T> MultiValuedParam<T> parse(String[] params, ParamConverter<T> paramConverter) {
29 MultiValuedParam<T> multiValuedParam = new MultiValuedParam<>();
30 for (String param : params) {
31 multiValuedParam.add(paramConverter.fromString(param));
32 }
33 return multiValuedParam;
34 }
35
36 @SuppressWarnings("unchecked")
37 private static <T> String format(MultiValuedParam<?> multiValuedParam, ParamConverter<T> paramConverter) {
38 StringBuilder stringBuilder = new StringBuilder();
39 int size = multiValuedParam.size();
40 for (int i = 0; i < size; i++) {
41 stringBuilder.append(paramConverter.toString((T) multiValuedParam.get(i)));
42 if (i != size - 1) {
43 stringBuilder.append(',');
44 }
45 }
46 return stringBuilder.toString();
47 }
48
49 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.GenericArrayType;
4 import java.lang.reflect.ParameterizedType;
5 import java.lang.reflect.Type;
6 import java.util.Date;
7
8 import javax.ws.rs.ext.ParamConverter;
9 import javax.ws.rs.ext.ParamConverterProvider;
10
11 public class MultiValuedParamConverterProvider implements ParamConverterProvider {
12
13 @SuppressWarnings("unchecked")
14 @Override
15 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
16 if (MultiValuedParam.class.isAssignableFrom(rawType)) {
17 ParamConverter<T> paramConverter = (ParamConverter<T>) getConverter(getType(genericType));
18 return (ParamConverter<T>) (paramConverter != null ? new MultiValuedParamConverter(paramConverter) : null);
19 }else if (MultiValuedCookieParam.class.isAssignableFrom(rawType)) {
20 ParamConverter<T> paramConverter = (ParamConverter<T>) getConverter(getType(genericType));
21 return (ParamConverter<T>) (paramConverter != null ? new MultiValuedCookieParamConverter(paramConverter)
22 : null);
23 }else if (MultiValuedPathParam.class.isAssignableFrom(rawType)) {
24 ParamConverter<T> paramConverter = (ParamConverter<T>) getConverter(getType(genericType));
25 return (ParamConverter<T>) (paramConverter != null ? new MultiValuedPathParamConverter(paramConverter)
26 : null);
27 }else if (rawType.isArray()){
28 Class<?> componentType = rawType.getComponentType();
29 if(genericType instanceof GenericArrayType){
30 Type genericComponentType=((GenericArrayType) genericType).getGenericComponentType();
31 if (ParamWrapper.class.isAssignableFrom(componentType)) {
32 ParamConverter<Object> paramConverter = (ParamConverter<Object>) getConverter(getType(genericComponentType));
33 return (ParamConverter<T>) (paramConverter != null ? new ParamWrapperArrayConverter(paramConverter) : null);
34 }else if (CookieParamWrapper.class.isAssignableFrom(componentType)) {
35 ParamConverter<Object> paramConverter = (ParamConverter<Object>) getConverter(getType(genericComponentType));
36 return (ParamConverter<T>) (paramConverter != null ? new CookieParamWrapperArrayConverter(paramConverter): null);
37 }else if (PathParamWrapper.class.isAssignableFrom(componentType)) {
38 ParamConverter<Object> paramConverter = (ParamConverter<Object>) getConverter(getType(genericComponentType));
39 return (ParamConverter<T>) (paramConverter != null ? new PathParamWrapperArrayConverter(paramConverter): null);
40 }
41 }
42 }
43 return (ParamConverter<T>) getConverter(rawType);
44 }
45
46 private static Class<?> getType(Type genericType) {
47 ParameterizedType parameterizedType = (ParameterizedType) genericType;
48 Type type = parameterizedType.getActualTypeArguments()[0];
49 return (type instanceof Class) ? (Class<?>) type : null;
50 }
51
52
53 private static ParamConverter<?> getConverter(Class<?> rawType) {
54 if (Date.class.isAssignableFrom(rawType)) {
55 return new DateParamConverter();
56 }
57 return null;
58 }
59
60 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.text.SimpleDateFormat;
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Collection;
6 import java.util.Date;
7 import java.util.HashSet;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Set;
11 import java.util.SortedSet;
12 import java.util.TreeSet;
13
14 import javax.ws.rs.Consumes;
15 import javax.ws.rs.CookieParam;
16 import javax.ws.rs.FormParam;
17 import javax.ws.rs.GET;
18 import javax.ws.rs.HeaderParam;
19 import javax.ws.rs.MatrixParam;
20 import javax.ws.rs.POST;
21 import javax.ws.rs.Path;
22 import javax.ws.rs.PathParam;
23 import javax.ws.rs.QueryParam;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.Response;
26
27 public class MultiValuedParamResource {
28
29 @Path("queryParam")
30 public static class QueryParamResource {
31
32 // http://xxx/queryParam/customConversion_multiValuedParam?date=20161217,20161218,20161219
33 @GET
34 @Path("customConversion_multiValuedParam")
35 public Response customConversion_multiValuedParam(@QueryParam("date") MultiValuedParam<Date> dates) {
36 return Response.ok(formatDates(dates)).build();
37 }
38
39 // http://xxx/queryParam/customConversion_multiValuedParam_array?date=20161217,20161218,20161219
40 @GET
41 @Path("customConversion_multiValuedParam_array")
42 public Response customConversion_multiValuedParam_array(@QueryParam("date") ParamWrapper<Date>[] dates) {
43 Collection<Date> dateCollection=new ArrayList<>();
44 for (ParamWrapper<Date> paramWrapper : dates) {
45 dateCollection.add(paramWrapper.getElement());
46 }
47 return Response.ok(formatDates(dateCollection)).build();
48 }
49
50 // http://xxx/queryParam/defaultConversion_list?date=20161217&date=20161218&date=20161219
51 @GET
52 @Path("defaultConversion_list")
53 public Response defaultConversion_list(@QueryParam("date") List<Date> dates) {
54 return Response.ok(formatDates(dates)).build();
55 }
56
57 // http://xxx/queryParam/defaultConversion_arrayList?date=20161217&date=20161218&date=20161219
58 @GET
59 @Path("defaultConversion_arrayList")
60 public Response defaultConversion_arrayList(@QueryParam("date") ArrayList<Date> dates) {
61 return Response.ok(formatDates(dates)).build();
62 }
63
64 // http://xxx/queryParam/defaultConversion_set?date=20161217&date=20161218&date=20161219
65 @GET
66 @Path("defaultConversion_set")
67 public Response defaultConversion_set(@QueryParam("date") Set<Date> dates) {
68 return Response.ok(formatDates(dates)).build();
69 }
70
71 // http://xxx/queryParam/defaultConversion_hashSet?date=20161217&date=20161218&date=20161219
72 @GET
73 @Path("defaultConversion_hashSet")
74 public Response defaultConversion_hashSet(@QueryParam("date") HashSet<Date> dates) {
75 return Response.ok(formatDates(dates)).build();
76 }
77
78 // http://xxx/queryParam/defaultConversion_sortedSet?date=20161217&date=20161218&date=20161219
79 @GET
80 @Path("defaultConversion_sortedSet")
81 public Response defaultConversion_sortedSet(@QueryParam("date") SortedSet<Date> dates) {
82 return Response.ok(formatDates(dates)).build();
83 }
84
85 // http://xxx/queryParam/defaultConversion_treeSet?date=20161217&date=20161218&date=20161219
86 @GET
87 @Path("defaultConversion_treeSet")
88 public Response defaultConversion_treeSet(@QueryParam("date") TreeSet<Date> dates) {
89 return Response.ok(formatDates(dates)).build();
90 }
91
92 // http://xxx/queryParam/defaultConversion_array?date=20161217&date=20161218&date=20161219
93 @GET
94 @Path("defaultConversion_array")
95 public Response defaultConversion_array(@QueryParam("date") Date[] dates) {
96 return Response.ok(formatDates(Arrays.asList(dates))).build();
97 }
98
99 }
100
101 @Path("headerParam")
102 public static class HeaderParamResource {
103
104 // date:20161217,20161218,20161219
105 @GET
106 @Path("customConversion_multiValuedParam")
107 public Response customConversion_multiValuedParam(@HeaderParam("date") MultiValuedParam<Date> dates) {
108 return Response.ok(formatDates(dates)).build();
109 }
110
111 // date:20161217,20161218,20161219
112 @GET
113 @Path("customConversion_multiValuedParam_array")
114 public Response customConversion_multiValuedParam_array(@HeaderParam("date") ParamWrapper<Date>[] dates) {
115 Collection<Date> dateCollection=new ArrayList<>();
116 for (ParamWrapper<Date> paramWrapper : dates) {
117 dateCollection.add(paramWrapper.getElement());
118 }
119 return Response.ok(formatDates(dateCollection)).build();
120 }
121
122 // date:20161217,20161218,20161219
123 @GET
124 @Path("defaultConversion_list")
125 public Response defaultConversion_list(@HeaderParam("date") List<Date> dates) {
126 return Response.ok(formatDates(dates)).build();
127 }
128
129 // date:20161217,20161218,20161219
130 @GET
131 @Path("defaultConversion_arrayList")
132 public Response defaultConversion_arrayList(@HeaderParam("date") ArrayList<Date> dates) {
133 return Response.ok(formatDates(dates)).build();
134 }
135
136 // date:20161217,20161218,20161219
137 @GET
138 @Path("defaultConversion_set")
139 public Response defaultConversion_set(@HeaderParam("date") Set<Date> dates) {
140 return Response.ok(formatDates(dates)).build();
141 }
142
143 // date:20161217,20161218,20161219
144 @GET
145 @Path("defaultConversion_hashSet")
146 public Response defaultConversion_hashSet(@HeaderParam("date") HashSet<Date> dates) {
147 return Response.ok(formatDates(dates)).build();
148 }
149
150 // date:20161217,20161218,20161219
151 @GET
152 @Path("defaultConversion_sortedSet")
153 public Response defaultConversion_sortedSet(@HeaderParam("date") SortedSet<Date> dates) {
154 return Response.ok(formatDates(dates)).build();
155 }
156
157 // date:20161217,20161218,20161219
158 @GET
159 @Path("defaultConversion_treeSet")
160 public Response defaultConversion_treeSet(@HeaderParam("date") TreeSet<Date> dates) {
161 return Response.ok(formatDates(dates)).build();
162 }
163
164 // date:20161217,20161218,20161219
165 @GET
166 @Path("defaultConversion_array")
167 public Response defaultConversion_array(@HeaderParam("date") Date[] dates) {
168 return Response.ok(formatDates(Arrays.asList(dates))).build();
169 }
170
171 }
172
173 @Path("matrixParam")
174 public static class MatrixParamResource {
175
176 // http://xxx/matrixParam/customConversion_multiValuedParam;date=20161217,20161218,20161219
177 @GET
178 @Path("customConversion_multiValuedParam")
179 public Response customConversion_multiValuedParam(@MatrixParam("date") MultiValuedParam<Date> dates) {
180 return Response.ok(formatDates(dates)).build();
181 }
182
183 // http://xxx/matrixParam/customConversion_multiValuedParam_array;date=20161217,20161218,20161219
184 @GET
185 @Path("customConversion_multiValuedParam_array")
186 public Response customConversion_multiValuedParam_array(@MatrixParam("date") ParamWrapper<Date>[] dates) {
187 Collection<Date> dateCollection=new ArrayList<>();
188 for (ParamWrapper<Date> paramWrapper : dates) {
189 dateCollection.add(paramWrapper.getElement());
190 }
191 return Response.ok(formatDates(dateCollection)).build();
192 }
193
194 // http://xxx/matrixParam/defaultConversion_list;date=20161217;date=20161218;date=20161219
195 @GET
196 @Path("defaultConversion_list")
197 public Response defaultConversion_list(@MatrixParam("date") List<Date> dates) {
198 return Response.ok(formatDates(dates)).build();
199 }
200
201 // http://xxx/matrixParam/defaultConversion_arrayList;date=20161217;date=20161218;date=20161219
202 @GET
203 @Path("defaultConversion_arrayList")
204 public Response defaultConversion_arrayList(@MatrixParam("date") ArrayList<Date> dates) {
205 return Response.ok(formatDates(dates)).build();
206 }
207
208 // http://xxx/matrixParam/defaultConversion_set;date=20161217;date=20161218;date=20161219
209 @GET
210 @Path("defaultConversion_set")
211 public Response defaultConversion_set(@MatrixParam("date") Set<Date> dates) {
212 return Response.ok(formatDates(dates)).build();
213 }
214
215 // http://xxx/matrixParam/defaultConversion_hashSet;date=20161217;date=20161218;date=20161219
216 @GET
217 @Path("defaultConversion_hashSet")
218 public Response defaultConversion_hashSet(@MatrixParam("date") HashSet<Date> dates) {
219 return Response.ok(formatDates(dates)).build();
220 }
221
222 // http://xxx/matrixParam/defaultConversion_sortedSet;date=20161217;date=20161218;date=20161219
223 @GET
224 @Path("defaultConversion_sortedSet")
225 public Response defaultConversion_sortedSet(@MatrixParam("date") SortedSet<Date> dates) {
226 return Response.ok(formatDates(dates)).build();
227 }
228
229 // http://xxx/matrixParam/defaultConversion_treeSet;date=20161217;date=20161218;date=20161219
230 @GET
231 @Path("defaultConversion_treeSet")
232 public Response defaultConversion_treeSet(@MatrixParam("date") TreeSet<Date> dates) {
233 return Response.ok(formatDates(dates)).build();
234 }
235
236 // http://xxx/matrixParam/defaultConversion_array;date=20161217;date=20161218;date=20161219
237 @GET
238 @Path("defaultConversion_array")
239 public Response defaultConversion_array(@MatrixParam("date") Date[] dates) {
240 return Response.ok(formatDates(Arrays.asList(dates))).build();
241 }
242
243 }
244
245 @Path("cookieParam")
246 public static class CookieParamResource {
247
248 // cookie:date=20161217-20161218-20161219
249 @GET
250 @Path("customConversion_multiValuedCookieParam")
251 public Response customConversion_multiValuedCookieParam(@CookieParam("date") MultiValuedCookieParam<Date> dates) {
252 return Response.ok(formatDates(dates)).build();
253 }
254
255 // cookie:date=20161217-20161218-20161219
256 @GET
257 @Path("customConversion_multiValuedCookieParam_array")
258 public Response customConversion_multiValuedCookieParam_array(@CookieParam("date") CookieParamWrapper<Date>[] dates) {
259 Collection<Date> dateCollection=new ArrayList<>();
260 for (CookieParamWrapper<Date> paramWrapper : dates) {
261 dateCollection.add(paramWrapper.getElement());
262 }
263 return Response.ok(formatDates(dateCollection)).build();
264 }
265
266 // cookie:date=20161217
267 @GET
268 @Path("defaultConversion_list")
269 public Response defaultConversion_list(@CookieParam("date") List<Date> dates) {
270 return Response.ok(formatDates(dates)).build();
271 }
272
273 // cookie:date=20161217
274 @GET
275 @Path("defaultConversion_arrayList")
276 public Response defaultConversion_arrayList(@CookieParam("date") ArrayList<Date> dates) {
277 return Response.ok(formatDates(dates)).build();
278 }
279
280 // cookie:date=20161217
281 @GET
282 @Path("defaultConversion_set")
283 public Response defaultConversion_set(@CookieParam("date") Set<Date> dates) {
284 return Response.ok(formatDates(dates)).build();
285 }
286
287 // cookie:date=20161217
288 @GET
289 @Path("defaultConversion_hashSet")
290 public Response defaultConversion_hashSet(@CookieParam("date") HashSet<Date> dates) {
291 return Response.ok(formatDates(dates)).build();
292 }
293
294 // cookie:date=20161217
295 @GET
296 @Path("defaultConversion_sortedSet")
297 public Response defaultConversion_sortedSet(@CookieParam("date") SortedSet<Date> dates) {
298 return Response.ok(formatDates(dates)).build();
299 }
300
301 // cookie:date=20161217
302 @GET
303 @Path("defaultConversion_treeSet")
304 public Response defaultConversion_treeSet(@CookieParam("date") TreeSet<Date> dates) {
305 return Response.ok(formatDates(dates)).build();
306 }
307
308 // cookie:date=20161217
309 @GET
310 @Path("defaultConversion_array")
311 public Response defaultConversion_array(@CookieParam("date") Date[] dates) {
312 return Response.ok(formatDates(Arrays.asList(dates))).build();
313 }
314
315 }
316
317 @Path("formParam")
318 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
319 public static class FormParamResource {
320
321 // date=20161217,20161218,20161219
322 @POST
323 @Path("customConversion_multiValuedParam")
324 public Response customConversion_multiValuedParam(@FormParam("date") MultiValuedParam<Date> dates) {
325 return Response.ok(formatDates(dates)).build();
326 }
327
328 // date=20161217,20161218,20161219
329 @POST
330 @Path("customConversion_multiValuedParam_array")
331 public Response customConversion_multiValuedParam_array(@FormParam("date") ParamWrapper<Date>[] dates) {
332 Collection<Date> dateCollection=new ArrayList<>();
333 for (ParamWrapper<Date> paramWrapper : dates) {
334 dateCollection.add(paramWrapper.getElement());
335 }
336 return Response.ok(formatDates(dateCollection)).build();
337 }
338
339 // date=20161217&date=20161218&date=20161219
340 @POST
341 @Path("defaultConversion_list")
342 public Response defaultConversion_list(@FormParam("date") List<Date> dates) {
343 return Response.ok(formatDates(dates)).build();
344 }
345
346 // date=20161217&date=20161218&date=20161219
347 @POST
348 @Path("defaultConversion_arrayList")
349 public Response defaultConversion_arrayList(@FormParam("date") ArrayList<Date> dates) {
350 return Response.ok(formatDates(dates)).build();
351 }
352
353 // date=20161217&date=20161218&date=20161219
354 @POST
355 @Path("defaultConversion_set")
356 public Response defaultConversion_set(@FormParam("date") Set<Date> dates) {
357 return Response.ok(formatDates(dates)).build();
358 }
359
360 // date=20161217&date=20161218&date=20161219
361 @POST
362 @Path("defaultConversion_hashSet")
363 public Response defaultConversion_hashSet(@FormParam("date") HashSet<Date> dates) {
364 return Response.ok(formatDates(dates)).build();
365 }
366
367 // date=20161217&date=20161218&date=20161219
368 @POST
369 @Path("defaultConversion_sortedSet")
370 public Response defaultConversion_sortedSet(@FormParam("date") SortedSet<Date> dates) {
371 return Response.ok(formatDates(dates)).build();
372 }
373
374 // date=20161217&date=20161218&date=20161219
375 @POST
376 @Path("defaultConversion_treeSet")
377 public Response defaultConversion_treeSet(@FormParam("date") TreeSet<Date> dates) {
378 return Response.ok(formatDates(dates)).build();
379 }
380
381 // date=20161217&date=20161218&date=20161219
382 @POST
383 @Path("defaultConversion_array")
384 public Response defaultConversion_array(@FormParam("date") Date[] dates) {
385 return Response.ok(formatDates(Arrays.asList(dates))).build();
386 }
387
388 }
389
390 @Path("pathParam")
391 public static class PathParamResource {
392
393 // http://xxx/pathParam/customConversion_multiValuedPathParam/20161217/20161218/20161219
394 @GET
395 @Path("customConversion_multiValuedPathParam/{path: .+}")
396 public Response customConversion_multiValuedPathParam(@PathParam("path") MultiValuedPathParam<Date> paths) {
397 return Response.ok(formatDates(paths)).build();
398 }
399
400 // http://xxx/pathParam/customConversion_multiValuedPathParam_array/20161217/20161218/20161219
401 @GET
402 @Path("customConversion_multiValuedPathParam_array/{path: .+}")
403 public Response customConversion_multiValuedPathParam_array(@PathParam("path") PathParamWrapper<Date>[] paths) {
404 Collection<Date> pathCollection=new ArrayList<>();
405 for (PathParamWrapper<Date> paramWrapper : paths) {
406 pathCollection.add(paramWrapper.getElement());
407 }
408 return Response.ok(formatDates(pathCollection)).build();
409 }
410
411 // http://xxx/pathParam/defaultConversion_list/20161217
412 @GET
413 @Path("defaultConversion_list/{path: .+}")
414 public Response defaultConversion_list(@PathParam("path") List<Date> paths) {
415 return Response.ok(formatDates(paths)).build();
416 }
417
418 // http://xxx/pathParam/defaultConversion_arrayList/20161217
419 @GET
420 @Path("defaultConversion_arrayList/{path: .+}")
421 public Response defaultConversion_arrayList(@PathParam("path") ArrayList<Date> paths) {
422 return Response.ok(formatDates(paths)).build();
423 }
424
425 // http://xxx/pathParam/defaultConversion_set/20161217
426 @GET
427 @Path("defaultConversion_set/{path: .+}")
428 public Response defaultConversion_set(@PathParam("path") Set<Date> paths) {
429 return Response.ok(formatDates(paths)).build();
430 }
431
432 // http://xxx/pathParam/defaultConversion_hashSet/20161217
433 @GET
434 @Path("defaultConversion_hashSet/{path: .+}")
435 public Response defaultConversion_hashSet(@PathParam("path") HashSet<Date> paths) {
436 return Response.ok(formatDates(paths)).build();
437 }
438
439 // http://xxx/pathParam/defaultConversion_sortedSet/20161217
440 @GET
441 @Path("defaultConversion_sortedSet/{path: .+}")
442 public Response defaultConversion_sortedSet(@PathParam("path") SortedSet<Date> paths) {
443 return Response.ok(formatDates(paths)).build();
444 }
445
446 // http://xxx/pathParam/defaultConversion_treeSet/20161217
447 @GET
448 @Path("defaultConversion_treeSet/{path: .+}")
449 public Response defaultConversion_treeSet(@PathParam("path") TreeSet<Date> paths) {
450 return Response.ok(formatDates(paths)).build();
451 }
452
453 // http://xxx/pathParam/defaultConversion_array/20161217
454 @GET
455 @Path("defaultConversion_array/{path: .+}")
456 public Response defaultConversion_array(@PathParam("path") Date[] paths) {
457 return Response.ok(formatDates(Arrays.asList(paths))).build();
458 }
459
460 }
461
462 private static String formatDates(Collection<Date> dates) {
463 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
464 StringBuilder stringBuilder = new StringBuilder();
465 int datesCount = dates.size();
466 int i = 0;
467 for (Date date : new TreeSet<>(dates)) {
468 stringBuilder.append(simpleDateFormat.format(date));
469 ++i;
470 if (i < datesCount) {
471 stringBuilder.append(",");
472 }
473 }
474 return stringBuilder.toString();
475 }
476
477 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.util.ArrayList;
3 import java.util.HashSet;
4 import java.util.List;
5 import java.util.Set;
6 import java.util.SortedSet;
7 import java.util.TreeSet;
8
9 import javax.ws.rs.Consumes;
10 import javax.ws.rs.CookieParam;
11 import javax.ws.rs.FormParam;
12 import javax.ws.rs.GET;
13 import javax.ws.rs.HeaderParam;
14 import javax.ws.rs.MatrixParam;
15 import javax.ws.rs.POST;
16 import javax.ws.rs.Path;
17 import javax.ws.rs.PathParam;
18 import javax.ws.rs.QueryParam;
19 import javax.ws.rs.core.MediaType;
20
21 @Path("/")
22 public interface MultiValuedParamResourceClient {
23
24 @Path("queryParam")
25 QueryParamResourceClient queryParam();
26
27 @Path("headerParam")
28 HeaderParamResourceClient headerParam();
29
30 @Path("matrixParam")
31 MatrixParamResourceClient matrixParam();
32
33 @Path("cookieParam")
34 CookieParamResourceClient cookieParam();
35
36 @Path("formParam")
37 FormParamResourceClient formParam();
38
39 @Path("pathParam")
40 PathParamResourceClient pathParam();
41
42 @Path("/")
43 public interface QueryParamResourceClient {
44
45 @GET
46 @Path("customConversion_multiValuedParam")
47 String customConversion_multiValuedParam(@QueryParam("date") String dates);
48
49 @GET
50 @Path("customConversion_multiValuedParam_array")
51 String customConversion_multiValuedParam_array(@QueryParam("date") String dates);
52
53 @GET
54 @Path("defaultConversion_list")
55 String defaultConversion_list(@QueryParam("date") List<String> dates);
56
57 @GET
58 @Path("defaultConversion_arrayList")
59 String defaultConversion_arrayList(@QueryParam("date") ArrayList<String> dates);
60
61 @GET
62 @Path("defaultConversion_set")
63 String defaultConversion_set(@QueryParam("date") Set<String> dates);
64
65 @GET
66 @Path("defaultConversion_hashSet")
67 String defaultConversion_hashSet(@QueryParam("date") HashSet<String> dates);
68
69 @GET
70 @Path("defaultConversion_sortedSet")
71 String defaultConversion_sortedSet(@QueryParam("date") SortedSet<String> dates);
72
73 @GET
74 @Path("defaultConversion_treeSet")
75 String defaultConversion_treeSet(@QueryParam("date") TreeSet<String> dates);
76
77 @GET
78 @Path("defaultConversion_array")
79 String defaultConversion_array(@QueryParam("date") String[] dates);
80
81 }
82
83 @Path("/")
84 public interface HeaderParamResourceClient {
85
86 @GET
87 @Path("customConversion_multiValuedParam")
88 String customConversion_multiValuedParam(@HeaderParam("date") String dates);
89
90 @GET
91 @Path("customConversion_multiValuedParam_array")
92 String customConversion_multiValuedParam_array(@HeaderParam("date") String dates);
93
94 @GET
95 @Path("defaultConversion_list")
96 String defaultConversion_list(@HeaderParam("date") List<String> dates);
97
98 @GET
99 @Path("defaultConversion_arrayList")
100 String defaultConversion_arrayList(@HeaderParam("date") ArrayList<String> dates);
101
102 @GET
103 @Path("defaultConversion_set")
104 String defaultConversion_set(@HeaderParam("date") Set<String> dates);
105
106 @GET
107 @Path("defaultConversion_hashSet")
108 String defaultConversion_hashSet(@HeaderParam("date") HashSet<String> dates);
109
110 @GET
111 @Path("defaultConversion_sortedSet")
112 String defaultConversion_sortedSet(@HeaderParam("date") SortedSet<String> dates);
113
114 @GET
115 @Path("defaultConversion_treeSet")
116 String defaultConversion_treeSet(@HeaderParam("date") TreeSet<String> dates);
117
118 @GET
119 @Path("defaultConversion_array")
120 String defaultConversion_array(@HeaderParam("date") String[] dates);
121
122 }
123
124 @Path("/")
125 public interface MatrixParamResourceClient {
126
127 @GET
128 @Path("customConversion_multiValuedParam")
129 String customConversion_multiValuedParam(@MatrixParam("date") String dates);
130
131 @GET
132 @Path("customConversion_multiValuedParam_array")
133 String customConversion_multiValuedParam_array(@MatrixParam("date") String dates);
134
135 @GET
136 @Path("defaultConversion_list")
137 String defaultConversion_list(@MatrixParam("date") List<String> dates);
138
139 @GET
140 @Path("defaultConversion_arrayList")
141 String defaultConversion_arrayList(@MatrixParam("date") ArrayList<String> dates);
142
143 @GET
144 @Path("defaultConversion_set")
145 String defaultConversion_set(@MatrixParam("date") Set<String> dates);
146
147 @GET
148 @Path("defaultConversion_hashSet")
149 String defaultConversion_hashSet(@MatrixParam("date") HashSet<String> dates);
150
151 @GET
152 @Path("defaultConversion_sortedSet")
153 String defaultConversion_sortedSet(@MatrixParam("date") SortedSet<String> dates);
154
155 @GET
156 @Path("defaultConversion_treeSet")
157 String defaultConversion_treeSet(@MatrixParam("date") TreeSet<String> dates);
158
159 @GET
160 @Path("defaultConversion_array")
161 String defaultConversion_array(@MatrixParam("date") String[] dates);
162
163 }
164
165 @Path("/")
166 public interface CookieParamResourceClient {
167
168 @GET
169 @Path("customConversion_multiValuedCookieParam")
170 String customConversion_multiValuedCookieParam(@CookieParam("date") String dates);
171
172 @GET
173 @Path("customConversion_multiValuedCookieParam_array")
174 String customConversion_multiValuedCookieParam_array(@CookieParam("date") String dates);
175
176 @GET
177 @Path("defaultConversion_list")
178 String defaultConversion_list(@CookieParam("date") String dates);
179
180 @GET
181 @Path("defaultConversion_arrayList")
182 String defaultConversion_arrayList(@CookieParam("date") String dates);
183
184 @GET
185 @Path("defaultConversion_set")
186 String defaultConversion_set(@CookieParam("date") String dates);
187
188 @GET
189 @Path("defaultConversion_hashSet")
190 String defaultConversion_hashSet(@CookieParam("date") String dates);
191
192 @GET
193 @Path("defaultConversion_sortedSet")
194 String defaultConversion_sortedSet(@CookieParam("date") String dates);
195
196 @GET
197 @Path("defaultConversion_treeSet")
198 String defaultConversion_treeSet(@CookieParam("date") String dates);
199
200 @GET
201 @Path("defaultConversion_array")
202 String defaultConversion_array(@CookieParam("date") String dates);
203
204 }
205
206 @Path("/")
207 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
208 public interface FormParamResourceClient {
209
210 @POST
211 @Path("customConversion_multiValuedParam")
212 String customConversion_multiValuedParam(@FormParam("date") String dates);
213
214 @POST
215 @Path("customConversion_multiValuedParam_array")
216 String customConversion_multiValuedParam_array(@FormParam("date") String dates);
217
218 @POST
219 @Path("defaultConversion_list")
220 String defaultConversion_list(@FormParam("date") List<String> dates);
221
222 @POST
223 @Path("defaultConversion_arrayList")
224 String defaultConversion_arrayList(@FormParam("date") ArrayList<String> dates);
225
226 @POST
227 @Path("defaultConversion_set")
228 String defaultConversion_set(@FormParam("date") Set<String> dates);
229
230 @POST
231 @Path("defaultConversion_hashSet")
232 String defaultConversion_hashSet(@FormParam("date") HashSet<String> dates);
233
234 @POST
235 @Path("defaultConversion_sortedSet")
236 String defaultConversion_sortedSet(@FormParam("date") SortedSet<String> dates);
237
238 @POST
239 @Path("defaultConversion_treeSet")
240 String defaultConversion_treeSet(@FormParam("date") TreeSet<String> dates);
241
242 @POST
243 @Path("defaultConversion_array")
244 String defaultConversion_array(@FormParam("date") String[] dates);
245
246 }
247
248 @Path("/")
249 public interface PathParamResourceClient {
250
251 @GET
252 @Path("customConversion_multiValuedPathParam/{path1}/{path2}/{path3}")
253 String customConversion_multiValuedPathParam(@PathParam("path1") String path1, @PathParam("path2") String path2, @PathParam("path3") String path3);
254
255 @GET
256 @Path("customConversion_multiValuedPathParam_array/{path1}/{path2}/{path3}")
257 String customConversion_multiValuedPathParam_array(@PathParam("path1") String path1, @PathParam("path2") String path2, @PathParam("path3") String path3);
258
259 @GET
260 @Path("defaultConversion_list/{path}")
261 String defaultConversion_list(@PathParam("path") String path);
262
263 @GET
264 @Path("defaultConversion_arrayList/{path}")
265 String defaultConversion_arrayList(@PathParam("path") String path);
266
267 @GET
268 @Path("defaultConversion_set/{path}")
269 String defaultConversion_set(@PathParam("path") String path);
270
271 @GET
272 @Path("defaultConversion_hashSet/{path}")
273 String defaultConversion_hashSet(@PathParam("path") String path);
274
275 @GET
276 @Path("defaultConversion_sortedSet/{path}")
277 String defaultConversion_sortedSet(@PathParam("path") String path);
278
279 @GET
280 @Path("defaultConversion_treeSet/{path}")
281 String defaultConversion_treeSet(@PathParam("path") String path);
282
283 @GET
284 @Path("defaultConversion_array/{path}")
285 String defaultConversion_array(@PathParam("path") String path);
286
287 }
288
289 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.util.LinkedList;
3
4 public class MultiValuedPathParam<E> extends LinkedList<E> {
5
6 private static final long serialVersionUID = 1L;
7 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.ext.ParamConverter;
3
4 public class MultiValuedPathParamConverter implements ParamConverter<MultiValuedPathParam<?>> {
5
6 private final ParamConverter<?> paramConverter;
7
8 public MultiValuedPathParamConverter(ParamConverter<?> paramConverter) {
9 this.paramConverter = paramConverter;
10 }
11
12 @Override
13 public MultiValuedPathParam<?> fromString(String param) {
14 if (param == null || param.trim().isEmpty()) {
15 return null;
16 }
17 return parse(param.split("/"), this.paramConverter);
18 }
19
20 @Override
21 public String toString(MultiValuedPathParam<?> multiValuedPathParam) {
22 if (multiValuedPathParam == null || multiValuedPathParam.isEmpty()) {
23 return null;
24 }
25 return format(multiValuedPathParam, this.paramConverter);
26 }
27
28 private static <T> MultiValuedPathParam<T> parse(String[] params, ParamConverter<T> paramConverter) {
29 MultiValuedPathParam<T> multiValuedPathParam = new MultiValuedPathParam<>();
30 for (String param : params) {
31 multiValuedPathParam.add(paramConverter.fromString(param));
32 }
33 return multiValuedPathParam;
34 }
35
36 @SuppressWarnings("unchecked")
37 private static <T> String format(MultiValuedPathParam<?> multiValuedPathParam,
38 ParamConverter<T> paramConverter) {
39 StringBuilder stringBuilder = new StringBuilder();
40 int size = multiValuedPathParam.size();
41 for (int i = 0; i < size; i++) {
42 stringBuilder.append(paramConverter.toString((T) multiValuedPathParam.get(i)));
43 if (i != size - 1) {
44 stringBuilder.append('/');
45 }
46 }
47 return stringBuilder.toString();
48 }
49
50 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 /***
3 *
4 * @author Nicolas NESMON
5 *
6 * @param <E>
7 */
8 public class ParamWrapper<E> {
9
10 private final E element;
11
12 public ParamWrapper(E element) {
13 this.element = element;
14 }
15
16 public E getElement() {
17 return element;
18 }
19
20 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.lang.reflect.Array;
3
4 import javax.ws.rs.ext.ParamConverter;
5
6 /**
7 *
8 * @author Nicolas NESMON
9 *
10 */
11
12 public class ParamWrapperArrayConverter implements ParamConverter<ParamWrapper<Object>[]> {
13
14 private final ParamConverter<Object> paramConverter;
15
16 public ParamWrapperArrayConverter(ParamConverter<Object> paramConverter) {
17 this.paramConverter = paramConverter;
18 }
19
20 @Override
21 public ParamWrapper<Object>[] fromString(String param) {
22 if (param == null || param.trim().isEmpty()) {
23 return null;
24 }
25 String[] params = param.split(",");
26 @SuppressWarnings("unchecked")
27 ParamWrapper<Object>[] array = (ParamWrapper<Object>[]) Array.newInstance(ParamWrapper.class, params.length);
28 for (int i = 0; i < params.length; i++) {
29 array[i] = new ParamWrapper<>(this.paramConverter.fromString(params[i]));
30 }
31 return array;
32 }
33
34 @Override
35 public String toString(ParamWrapper<Object>[] array) {
36 if (array == null || array.length == 0) {
37 return null;
38 }
39 StringBuilder stringBuilder = new StringBuilder();
40 int size = array.length;
41 for (int i = 0; i < array.length; i++) {
42 stringBuilder.append(this.paramConverter.toString(array[i].getElement()));
43 if (i != size) {
44 stringBuilder.append(',');
45 }
46 }
47 return stringBuilder.toString();
48 }
49
50 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 /***
3 *
4 * @author Nicolas NESMON
5 *
6 * @param <E>
7 */
8 public class PathParamWrapper<E> {
9
10 private final E element;
11
12 public PathParamWrapper(E element) {
13 this.element = element;
14 }
15
16 public E getElement() {
17 return element;
18 }
19
20 }
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.lang.reflect.Array;
3
4 import javax.ws.rs.ext.ParamConverter;
5
6 /**
7 *
8 * @author Nicolas NESMON
9 *
10 */
11
12 public class PathParamWrapperArrayConverter implements ParamConverter<PathParamWrapper<Object>[]> {
13
14 private final ParamConverter<Object> paramConverter;
15
16 public PathParamWrapperArrayConverter(ParamConverter<Object> paramConverter) {
17 this.paramConverter = paramConverter;
18 }
19
20 @Override
21 public PathParamWrapper<Object>[] fromString(String param) {
22 if (param == null || param.trim().isEmpty()) {
23 return null;
24 }
25 String[] params = param.split("/");
26 @SuppressWarnings("unchecked")
27 PathParamWrapper<Object>[] array = (PathParamWrapper<Object>[]) Array.newInstance(PathParamWrapper.class,
28 params.length);
29 for (int i = 0; i < params.length; i++) {
30 array[i] = new PathParamWrapper<>(this.paramConverter.fromString(params[i]));
31 }
32 return array;
33 }
34
35 @Override
36 public String toString(PathParamWrapper<Object>[] array) {
37 if (array == null || array.length == 0) {
38 return null;
39 }
40 StringBuilder stringBuilder = new StringBuilder();
41 int size = array.length;
42 for (int i = 0; i < array.length; i++) {
43 stringBuilder.append(this.paramConverter.toString(array[i].getElement()));
44 if (i != size) {
45 stringBuilder.append('/');
46 }
47 }
48 return stringBuilder.toString();
49 }
50
51 }
00 package org.jboss.resteasy.test.resource.param.resource;
11
2 import javax.ws.rs.ext.ParamConverter;
2 import org.jboss.resteasy.spi.StringConverter;
33
44 import javax.ws.rs.ext.Provider;
55
66 @Provider
7 public class SuperStringConverterCompanyConverter extends SuperStringConverterObjectConverter<SuperStringConverterCompany> implements ParamConverter<SuperStringConverterCompany> {
7 public class SuperStringConverterCompanyConverter extends SuperStringConverterObjectConverter<SuperStringConverterCompany> implements StringConverter<SuperStringConverterCompany> {
88 public SuperStringConverterCompany fromString(String value) {
99 return new SuperStringConverterCompany(value);
1010 }
+0
-21
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterCompanyConverterProvider.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4
5 import javax.ws.rs.ext.ParamConverter;
6 import javax.ws.rs.ext.ParamConverterProvider;
7 import javax.ws.rs.ext.Provider;
8
9 @Provider
10 public class SuperStringConverterCompanyConverterProvider implements ParamConverterProvider {
11
12 @SuppressWarnings("unchecked")
13 @Override
14 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations)
15 {
16 if (!SuperStringConverterCompanyConverter.class.equals(rawType)) return null;
17 return (ParamConverter<T>)new SuperStringConverterCompanyConverter();
18 }
19
20 }
00 package org.jboss.resteasy.test.resource.param.resource;
11
2 import javax.ws.rs.ext.ParamConverter;
2 import org.jboss.resteasy.spi.StringConverter;
33
4 public abstract class SuperStringConverterObjectConverter<T> implements ParamConverter<T> {
4 public abstract class SuperStringConverterObjectConverter<T> implements StringConverter<T> {
55 public String toString(T value) {
66 return value.toString();
77 }
00 package org.jboss.resteasy.test.resource.param.resource;
11
2 import javax.ws.rs.ext.ParamConverter;
2 import org.jboss.resteasy.spi.StringConverter;
33
44 import javax.ws.rs.ext.Provider;
55
66 @Provider
7 public class SuperStringConverterPersonConverter extends SuperStringConverterSuperPersonConverter implements ParamConverter<SuperStringConverterPerson> {
7 public class SuperStringConverterPersonConverter extends SuperStringConverterSuperPersonConverter implements StringConverter<SuperStringConverterPerson> {
88 }
+0
-19
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterPersonConverterProvider.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4
5 import javax.ws.rs.ext.ParamConverter;
6 import javax.ws.rs.ext.ParamConverterProvider;
7
8 public class SuperStringConverterPersonConverterProvider implements ParamConverterProvider
9 {
10 @SuppressWarnings("unchecked")
11 @Override
12 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations)
13 {
14 if (!SuperStringConverterPerson.class.equals(rawType)) return null;
15 return (ParamConverter<T>) new SuperStringConverterPersonConverter();
16 }
17
18 }
00 package org.jboss.resteasy.test.resource.param.resource;
11
2 import javax.ws.rs.ext.ParamConverter;
2 import org.jboss.resteasy.spi.StringConverter;
33
4 public abstract class SuperStringConverterSuperPersonConverter implements ParamConverter<SuperStringConverterPerson> {
4 public abstract class SuperStringConverterSuperPersonConverter implements StringConverter<SuperStringConverterPerson> {
55 public SuperStringConverterPerson fromString(String value) {
66 return new SuperStringConverterPerson(value);
77 }
0 package org.jboss.resteasy.test.resource.patch;
1
2 public class Student
3 {
4 private Long id;
5
6 private String firstName;
7
8 private String lastName;
9
10 private String school;
11
12 private String gender;
13
14 public Long getId()
15 {
16 return id;
17 }
18
19 public Student setId(Long id)
20 {
21 this.id = id;
22 return this;
23 }
24
25 public String getFirstName()
26 {
27 return firstName;
28 }
29
30 public Student setFirstName(String firstName)
31 {
32 this.firstName = firstName;
33 return this;
34 }
35
36 public String getLastName()
37 {
38 return lastName;
39 }
40
41 public Student setLastName(String lastName)
42 {
43 this.lastName = lastName;
44 return this;
45 }
46
47 public String getSchool()
48 {
49 return school;
50 }
51
52 public Student setSchool(String school)
53 {
54 this.school = school;
55 return this;
56 }
57
58 public String getGender()
59 {
60 return gender;
61 }
62
63 public Student setGender(String gender)
64 {
65 this.gender = gender;
66 return this;
67 }
68 }
69
0 package org.jboss.resteasy.test.resource.patch;
1
2 import javax.json.Json;
3 import javax.ws.rs.HttpMethod;
4 import javax.ws.rs.client.Client;
5 import javax.ws.rs.client.ClientBuilder;
6 import javax.ws.rs.client.Entity;
7 import javax.ws.rs.client.WebTarget;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Response;
10
11 import org.jboss.arquillian.container.test.api.Deployment;
12 import org.jboss.arquillian.container.test.api.RunAsClient;
13 import org.jboss.arquillian.junit.Arquillian;
14 import org.jboss.resteasy.category.Jaxrs21;
15 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
16 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
17 import org.jboss.resteasy.utils.PortProviderUtil;
18 import org.jboss.resteasy.utils.TestUtil;
19 import org.jboss.shrinkwrap.api.Archive;
20 import org.jboss.shrinkwrap.api.spec.WebArchive;
21 import org.junit.AfterClass;
22 import org.junit.Assert;
23 import org.junit.BeforeClass;
24 import org.junit.Test;
25 import org.junit.experimental.categories.Category;
26 import org.junit.runner.RunWith;
27
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 @Category(Jaxrs21.class)
31 public class StudentPatchTest
32 {
33
34 static Client client;
35
36 @BeforeClass
37 public static void setup()
38 {
39 client = ClientBuilder.newClient();
40 }
41
42 @AfterClass
43 public static void close()
44 {
45 client.close();
46 client = null;
47 }
48
49 @Deployment
50 public static Archive<?> deploy()
51 {
52 WebArchive war = TestUtil.prepareArchive(StudentPatchTest.class.getSimpleName());
53 return TestUtil.finishContainerPrepare(war, null, StudentResource.class, Student.class);
54 }
55
56 private String generateURL(String path)
57 {
58 return PortProviderUtil.generateURL(path, StudentPatchTest.class.getSimpleName());
59 }
60
61 @Test
62 //@Ignore
63 public void testPatchStudent() throws Exception
64 {
65 ResteasyClient client = new ResteasyClientBuilder().connectionPoolSize(10).build();
66
67 WebTarget base = client.target(generateURL("/students"));
68 //add a student, first name is Taylor and school is school1, other fields is null.
69 Student newStudent = new Student().setId(1L).setFirstName("Taylor").setSchool("school1");
70 Response response = base.request().post(Entity.<Student> entity(newStudent, MediaType.APPLICATION_JSON_TYPE));
71 Student s = response.readEntity(Student.class);
72 Assert.assertNotNull("Add student failed", s);
73 Assert.assertEquals("Taylor", s.getFirstName());
74 Assert.assertNull("Last name is not null", s.getLastName());
75 Assert.assertEquals("school1", s.getSchool());
76 Assert.assertNull("Gender is not null", s.getGender());
77
78 //patch a student, after patch we can get a male student named John Taylor and school is null.
79 WebTarget patchTarget = client.target(generateURL("/students/1"));
80 javax.json.JsonArray patchRequest = Json.createArrayBuilder()
81 .add(Json.createObjectBuilder().add("op", "copy").add("from", "/firstName").add("path", "/lastName").build())
82 .add(Json.createObjectBuilder().add("op", "replace").add("path", "/firstName").add("value", "John").build())
83 .add(Json.createObjectBuilder().add("op", "remove").add("path", "/school").build())
84 .add(Json.createObjectBuilder().add("op", "add").add("path", "/gender").add("value", "male").build())
85 .build();
86 patchTarget.request().build(HttpMethod.PATCH, Entity.entity(patchRequest, MediaType.APPLICATION_JSON_PATCH_JSON)).invoke();
87
88 //verify the patch update result
89 WebTarget getTarget = client.target(generateURL("/students/1"));
90 Response getResponse = getTarget.request().get();
91 Student patchedStudent = getResponse.readEntity(Student.class);
92 Assert.assertEquals("Expected lastname is changed to Taylor", "Taylor", patchedStudent.getLastName());
93 Assert.assertEquals("Expected firstname is replaced from Taylor to John", "John", patchedStudent.getFirstName());
94 Assert.assertEquals("Expected school is null", null, patchedStudent.getSchool());
95 Assert.assertEquals("Add gender", "male", patchedStudent.getGender());
96 }
97 }
0 package org.jboss.resteasy.test.resource.patch;
1
2 import java.util.Map;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.GET;
6 import javax.ws.rs.NotFoundException;
7 import javax.ws.rs.PATCH;
8 import javax.ws.rs.POST;
9 import javax.ws.rs.PUT;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.PathParam;
12 import javax.ws.rs.Produces;
13 import javax.ws.rs.core.MediaType;
14
15 @Path("/students")
16 public class StudentResource
17 {
18 private static Map<Long, Student> studentsMap = new java.util.concurrent.ConcurrentHashMap<Long, Student>();
19
20 public StudentResource()
21 {
22
23 }
24
25 @GET
26 @Path("/{id}")
27 @Produces(MediaType.APPLICATION_JSON)
28 public Student getStudent(@PathParam("id") long id)
29 {
30 Student student = studentsMap.get(id);
31 if (student == null)
32 {
33 throw new NotFoundException();
34 }
35 return student;
36 }
37
38 @POST
39 @Consumes(MediaType.APPLICATION_JSON)
40 @Produces(MediaType.APPLICATION_JSON)
41 public Student addStudent(Student student)
42 {
43 studentsMap.put(student.getId(), student);
44 return student;
45 }
46
47 @PUT
48 @Path("/{id}")
49 @Consumes(MediaType.APPLICATION_JSON)
50 @Produces(MediaType.APPLICATION_JSON)
51 public Student updateStudent(@PathParam("id") long id, Student student)
52 {
53 if (studentsMap.get(id) == null)
54 {
55 throw new NotFoundException();
56 }
57 studentsMap.put(id, student);
58 return student;
59 }
60
61 @PATCH
62 @Path("/{id}")
63 @Consumes(MediaType.APPLICATION_JSON_PATCH_JSON)
64 @Produces(MediaType.APPLICATION_JSON)
65 public Student patchStudent(@PathParam("id") long id, Student student)
66 {
67 if (studentsMap.get(id) == null)
68 {
69 throw new NotFoundException();
70 }
71 studentsMap.put(id, student);
72 return student;
73 }
74
75 }
0 package org.jboss.resteasy.test.resource.path;
1
2 import static org.junit.Assert.assertEquals;
3
4 import javax.ws.rs.client.Client;
5 import javax.ws.rs.client.ClientBuilder;
6 import javax.ws.rs.core.Response;
7
8 import org.jboss.arquillian.container.test.api.Deployment;
9 import org.jboss.arquillian.container.test.api.RunAsClient;
10 import org.jboss.arquillian.junit.Arquillian;
11 import org.jboss.resteasy.test.resource.path.resource.PathParamMissingDefaultValueBeanParamEntity;
12 import org.jboss.resteasy.test.resource.path.resource.PathParamMissingDefaultValueResource;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 /**
21 * @tpSubChapter Resource
22 * @tpChapter Integration tests
23 * @tpSince RESTEasy 3.5
24 * @tpTestCaseDetails Check for slash in URL
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class PathParamMissingDefaultValueTest {
29
30 @Deployment
31 public static Archive<?> deploy() {
32 WebArchive war = TestUtil.prepareArchive(PathParamMissingDefaultValueTest.class.getSimpleName());
33 war.addClass(PathParamMissingDefaultValueBeanParamEntity.class);
34 return TestUtil.finishContainerPrepare(war, null, PathParamMissingDefaultValueResource.class);
35 }
36
37 private String generateURL(String path) {
38 return PortProviderUtil.generateURL(path, PathParamMissingDefaultValueTest.class.getSimpleName());
39 }
40
41 /**
42 * @tpTestDetails Missing @PathParam in BeanParam with no @DefaultValue should get java default value.
43 * @tpSince RESTEasy 3.5
44 */
45 @Test
46 public void testTrailingSlash() throws Exception {
47 Client client = ClientBuilder.newClient();
48 Response response = client.target(generateURL("/resource/test/")).request().get();
49 assertEquals(200, response.getStatus());
50 assertEquals("Wrong response", "nullnullnullnullnullnull", response.readEntity(String.class));
51 client.close();
52 }
53 }
0 package org.jboss.resteasy.test.resource.path.resource;
1
2 import javax.ws.rs.CookieParam;
3 import javax.ws.rs.FormParam;
4 import javax.ws.rs.HeaderParam;
5 import javax.ws.rs.MatrixParam;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.QueryParam;
8
9 public class PathParamMissingDefaultValueBeanParamEntity {
10
11 @CookieParam("bpeCookie")
12 public String bpeCookie;
13
14 @FormParam("bpeForm")
15 public String bpeForm;
16
17 @HeaderParam("bpeHeader")
18 public String bpeHeader;
19
20 @MatrixParam("bpeMatrix")
21 public String bpeMatrix;
22
23 @PathParam("bpePath")
24 public String bpePath;
25
26 @QueryParam("bpeQuery")
27 public String bpeQuery;
28
29 public String toString() {
30 return bpeCookie + bpeForm + bpeHeader + bpeMatrix + bpePath + bpeQuery;
31 }
32 }
0 package org.jboss.resteasy.test.resource.path.resource;
1
2 import javax.ws.rs.BeanParam;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.Path;
5
6 @Path("resource")
7 public class PathParamMissingDefaultValueResource {
8
9 @BeanParam
10 PathParamMissingDefaultValueBeanParamEntity beanParam;
11
12 @GET
13 @Path("test")
14 public String defaultParams() {
15 return beanParam.toString();
16 }
17 }
0 package org.jboss.resteasy.test.response;
1
2 import java.util.ArrayList;
3 import java.util.List;
4 import java.util.concurrent.CompletableFuture;
5 import java.util.concurrent.TimeUnit;
6
7 import javax.ws.rs.client.Client;
8 import javax.ws.rs.client.ClientBuilder;
9 import javax.ws.rs.client.WebTarget;
10 import javax.ws.rs.sse.SseEventSource;
11
12
13 import org.jboss.arquillian.container.test.api.Deployment;
14 import org.jboss.arquillian.junit.Arquillian;
15 import org.jboss.logging.Logger;
16 import org.jboss.resteasy.category.Jaxrs21;
17 import org.jboss.resteasy.test.response.resource.AsyncResponseCallback;
18 import org.jboss.resteasy.test.response.resource.AsyncResponseException;
19 import org.jboss.resteasy.test.response.resource.AsyncResponseExceptionMapper;
20 import org.jboss.resteasy.test.response.resource.PublisherResponseResource;
21 import org.jboss.resteasy.utils.PortProviderUtil;
22 import org.jboss.resteasy.utils.TestUtil;
23 import org.jboss.shrinkwrap.api.Archive;
24 import org.jboss.shrinkwrap.api.asset.StringAsset;
25 import org.jboss.shrinkwrap.api.spec.WebArchive;
26 import org.junit.Assert;
27 import org.junit.Test;
28 import org.junit.experimental.categories.Category;
29 import org.junit.runner.RunWith;
30
31 /**
32 * @tpSubChapter Publisher response type
33 * @tpChapter Integration tests
34 * @tpSince RESTEasy 3.5
35 */
36 @RunWith(Arquillian.class)
37 @Category(Jaxrs21.class)
38 public class AnotherPublisherResponseTest {
39 private final static Logger logger = Logger.getLogger(AnotherPublisherResponseTest.class);
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(AnotherPublisherResponseTest.class.getSimpleName());
44 war.addClass(AnotherPublisherResponseTest.class);
45 war.addClass(Jaxrs21.class);
46 war.addAsLibrary(TestUtil.resolveDependency("io.reactivex.rxjava2:rxjava:2.1.3"));
47 war.setManifest(new StringAsset("Manifest-Version: 1.0\n"
48 + "Dependencies: org.reactivestreams\n"));
49 return TestUtil.finishContainerPrepare(war, null, PublisherResponseResource.class,
50 AsyncResponseCallback.class, AsyncResponseExceptionMapper.class, AsyncResponseException.class, PortProviderUtil.class);
51 }
52
53 private String generateURL(String path) {
54 return PortProviderUtil.generateURL(path, AnotherPublisherResponseTest.class.getSimpleName());
55 }
56
57 /**
58 * @tpTestDetails Resource method returns Publisher<String>.
59 * @tpSince RESTEasy 3.5
60 */
61 @Test
62 public void testSse() throws Exception
63 {
64 for (int i=0; i < 40; i++) {
65 internalTestSse(i);
66 }
67 }
68 public void internalTestSse(int i) throws Exception
69 {
70 Client client = ClientBuilder.newClient();
71 WebTarget target = client.target(generateURL("/sse"));
72 List<String> collector = new ArrayList<>();
73 List<Throwable> errors = new ArrayList<>();
74 CompletableFuture<Void> future = new CompletableFuture<Void>();
75 try (SseEventSource source = SseEventSource.target(target).build())
76 {
77 source.register(evt -> {
78 String data = evt.readData(String.class);
79 collector.add(data);
80 if (collector.size() >= 2)
81 {
82 future.complete(null);
83 }
84 }, t -> {
85 logger.error(t.getMessage(), t);
86 errors.add(t);
87 }, () -> {
88 // bah, never called
89 future.complete(null);
90 });
91 source.open();
92 future.get(5000, TimeUnit.SECONDS);
93 Assert.assertEquals(2, collector.size());
94 Assert.assertEquals(0, errors.size());
95 Assert.assertTrue(collector.contains("one"));
96 Assert.assertTrue(collector.contains("two"));
97 }
98 client.close();
99 }
100 }
0 package org.jboss.resteasy.test.response;
1
2 import java.util.Map;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.QueryParam;
8 import javax.ws.rs.client.Client;
9 import javax.ws.rs.client.ClientBuilder;
10 import javax.ws.rs.client.Invocation;
11 import javax.ws.rs.core.Cookie;
12 import javax.ws.rs.core.HttpHeaders;
13 import javax.ws.rs.core.MediaType;
14 import javax.ws.rs.core.NewCookie;
15 import javax.ws.rs.core.Response;
16
17 import org.jboss.arquillian.container.test.api.Deployment;
18 import org.jboss.arquillian.container.test.api.RunAsClient;
19 import org.jboss.arquillian.junit.Arquillian;
20 import org.jboss.resteasy.utils.PortProviderUtil;
21 import org.jboss.resteasy.utils.TestUtil;
22 import org.jboss.shrinkwrap.api.Archive;
23 import org.jboss.shrinkwrap.api.spec.WebArchive;
24 import org.junit.AfterClass;
25 import org.junit.Assert;
26 import org.junit.BeforeClass;
27 import org.junit.Test;
28 import org.junit.runner.RunWith;
29
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class CommitNewCookiesHeaderTest {
33
34 @Path("echo")
35 public static class EchoResource {
36
37 @Produces(MediaType.TEXT_PLAIN)
38 @GET
39 public Response echo(@QueryParam("msg") String msg) {
40 // send cookie as a simple string
41 return Response.ok(msg).header(HttpHeaders.SET_COOKIE, "Cookie 1=Cookie 1 value;Version=1;Path=/")
42 .cookie(new NewCookie("Cookie 2", "Cookie 2 value"),
43 new NewCookie("Cookie 3", "Cookie 3 value"))
44 .build();
45 }
46
47 @Path("two")
48 @Produces(MediaType.TEXT_PLAIN)
49 @GET
50 public Response echoTwo(@QueryParam("msg") String msg) {
51 // Any class that provides a toString can be provided as a cookie
52 return Response.ok().header(HttpHeaders.SET_COOKIE,
53 new Object() {
54 @Override
55 public String toString() {
56 return "Cookie 1=Cookie 1 value;Version=1;Path=/";
57 }
58 })
59 .cookie(new NewCookie("Cookie 2", "Cookie 2 value"))
60 .build();
61 }
62
63 @Path("three")
64 @Produces(MediaType.TEXT_PLAIN)
65 @GET
66 public Response echoThree(@QueryParam("msg") String msg) {
67 // Cookie should really only be used with request but it is an object with a toString impl
68 return Response.ok(msg).header(HttpHeaders.SET_COOKIE, new Cookie("Cookie 1", "Cookie 1 value"))
69 .cookie(new NewCookie("Cookie 2", "Cookie 2 value"))
70 .build();
71 }
72
73 }
74
75 private static Client client;
76 private static final String DEP = "CommitCookiesHeaderTest";
77
78 @Deployment
79 public static Archive<?> deploy() {
80 WebArchive war = TestUtil.prepareArchive(DEP);
81 war.addClass(EchoResource.class);
82 return TestUtil.finishContainerPrepare(war, null, EchoResource.class);
83 }
84
85 @BeforeClass
86 public static void setup() {
87 client = ClientBuilder.newClient();
88 }
89
90 @AfterClass
91 public static void cleanup() {
92 client.close();
93 }
94
95 private String generateURL() {
96 return PortProviderUtil.generateBaseUrl(DEP);
97 }
98
99 @Test
100 public void testAcceptApplicationStar() throws Exception {
101 Invocation.Builder request = client.target(generateURL()).path("echo").queryParam("msg", "Hello world")
102 .request(MediaType.TEXT_PLAIN_TYPE);
103 try (Response response = request.get()) {
104 Map<String, NewCookie> cookies = response.getCookies();
105 Assert.assertEquals(3, cookies.size());
106 Assert.assertEquals("Cookie 1 value", cookies.get("Cookie 1").getValue());
107 Assert.assertEquals("Cookie 2 value", cookies.get("Cookie 2").getValue());
108 Assert.assertEquals("Cookie 3 value", cookies.get("Cookie 3").getValue());
109 }
110 }
111
112 @Test
113 public void testSecondCase() throws Exception {
114 Invocation.Builder request = client.target(generateURL()).path("echo/two").queryParam("msg", "Hello world")
115 .request(MediaType.TEXT_PLAIN_TYPE);
116 try (Response response = request.get()) {
117 Map<String, NewCookie> cookies = response.getCookies();
118 Assert.assertEquals(2, cookies.size());
119 Assert.assertEquals("Cookie 1 value", cookies.get("Cookie 1").getValue());
120 Assert.assertEquals("Cookie 2 value", cookies.get("Cookie 2").getValue());
121 }
122 }
123
124 @Test
125 public void testThreeCase() throws Exception {
126 Invocation.Builder request = client.target(generateURL()).path("echo/three").queryParam("msg", "Hello world")
127 .request(MediaType.TEXT_PLAIN_TYPE);
128 try (Response response = request.get()) {
129 Map<String, NewCookie> cookies = response.getCookies();
130 Assert.assertEquals(2, cookies.size());
131 Assert.assertEquals("Cookie 1 value", cookies.get("Cookie 1").getValue());
132 Assert.assertEquals("Cookie 2 value", cookies.get("Cookie 2").getValue());
133 }
134 }
135 }
0 package org.jboss.resteasy.test.response;
1
2 import java.net.InetAddress;
3
4 import javax.ws.rs.client.Invocation;
5 import javax.ws.rs.core.Response;
6
7 import org.jboss.arquillian.container.test.api.Deployment;
8 import org.jboss.arquillian.container.test.api.RunAsClient;
9 import org.jboss.arquillian.junit.Arquillian;
10 import org.jboss.resteasy.category.ExpectedFailing;
11 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
12 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
13 import org.jboss.resteasy.test.response.resource.AsyncResponseCallback;
14 import org.jboss.resteasy.test.response.resource.CompletionStageProxy;
15 import org.jboss.resteasy.test.response.resource.CompletionStageResponseMessageBodyWriter;
16 import org.jboss.resteasy.test.response.resource.CompletionStageResponseResource;
17 import org.jboss.resteasy.test.response.resource.CompletionStageResponseTestClass;
18 import org.jboss.resteasy.utils.PortProviderUtil;
19 import org.jboss.resteasy.utils.TestUtil;
20 import org.jboss.shrinkwrap.api.Archive;
21 import org.jboss.shrinkwrap.api.asset.StringAsset;
22 import org.jboss.shrinkwrap.api.spec.WebArchive;
23 import org.junit.AfterClass;
24 import org.junit.Assert;
25 import org.junit.BeforeClass;
26 import org.junit.Test;
27 import org.junit.experimental.categories.Category;
28 import org.junit.runner.RunWith;
29
30 import java.util.concurrent.Future;
31
32 /**
33 * @tpSubChapter CompletionStage response type
34 * @tpChapter Integration tests
35 * @tpSince RESTEasy 3.5
36 */
37 @RunWith(Arquillian.class)
38 @RunAsClient
39 public class CompletionStageResponseTest {
40
41 static boolean serverIsLocal;
42 static ResteasyClient client;
43
44 @Deployment
45 public static Archive<?> deploy() {
46 WebArchive war = TestUtil.prepareArchive(CompletionStageResponseTest.class.getSimpleName());
47 war.addClass(CompletionStageResponseTestClass.class);
48 war.addClass(CompletionStageProxy.class);
49 war.addAsLibrary(TestUtil.resolveDependency("io.reactivex.rxjava2:rxjava:2.1.3"));
50 war.setManifest(new StringAsset("Manifest-Version: 1.0\n"
51 + "Dependencies: org.reactivestreams\n"));
52 return TestUtil.finishContainerPrepare(war, null, CompletionStageResponseMessageBodyWriter.class,
53 CompletionStageResponseResource.class, SingleProvider.class,
54 AsyncResponseCallback.class);
55 }
56
57 private static String generateURL(String path) {
58 return PortProviderUtil.generateURL(path, CompletionStageResponseTest.class.getSimpleName());
59 }
60
61 @BeforeClass
62 public static void setup() throws Exception {
63 client = new ResteasyClientBuilder().build();
64
65 // Undertow's default behavior is to send an HTML error page only if the client and
66 // server are communicating on a loopback connection. Otherwise, it returns "".
67 Invocation.Builder request = client.target(generateURL("/host")).request();
68 Response response = request.get();
69 String host = response.readEntity(String.class);
70 InetAddress addr = InetAddress.getByName(host);
71 serverIsLocal = addr.isLoopbackAddress();
72 }
73
74 @AfterClass
75 public static void close() {
76 client.close();
77 client = null;
78 }
79
80
81 /**
82 * @tpTestDetails Resource method returns CompletionStage<String>.
83 * @tpSince RESTEasy 3.5
84 */
85 @Test
86 public void testText() throws Exception
87 {
88 Invocation.Builder request = client.target(generateURL("/text")).request();
89 Response response = request.get();
90 String entity = response.readEntity(String.class);
91 Assert.assertEquals(200, response.getStatus());
92 Assert.assertEquals(CompletionStageResponseResource.HELLO, entity);
93
94 // make sure the completion callback was called with no error
95 request = client.target(generateURL("/callback-called-no-error")).request();
96 response = request.get();
97 Assert.assertEquals(200, response.getStatus());
98 response.close();
99 }
100
101 /**
102 * @tpTestDetails Resource method returns CompletionStage<Response>.
103 * Response has MediaType "text/plain" overriding @Produces("text/xxx").
104 * @tpSince RESTEasy 3.5
105 */
106 @Test
107 public void testResponse() throws Exception
108 {
109 ResteasyClient client = new ResteasyClientBuilder().build();
110 Invocation.Builder request = client.target(generateURL("/response")).request();
111 Response response = request.get();
112 String entity = response.readEntity(String.class);
113 Assert.assertEquals(200, response.getStatus());
114 Assert.assertEquals("text/plain;charset=UTF-8", response.getHeaderString("Content-Type"));
115 Assert.assertEquals(CompletionStageResponseResource.HELLO, entity);
116 }
117
118 /**
119 * @tpTestDetails Resource method returns CompletionStage<CompletionStageResponseTestClass>,
120 * where CompletionStageResponseTestClass is handled by CompletionStageResponseMessageBodyWriter,
121 * which has annotation @Produces("abc/xyz").
122 * @tpSince RESTEasy 3.5
123 */
124 @Test
125 public void testTestClass() throws Exception
126 {
127 Invocation.Builder request = client.target(generateURL("/testclass")).request();
128 Response response = request.get();
129 String entity = response.readEntity(String.class);
130 Assert.assertEquals(200, response.getStatus());
131 Assert.assertEquals("abc/xyz", response.getHeaderString("Content-Type"));
132 Assert.assertEquals("pdq", entity);
133 }
134
135 /**
136 * @tpTestDetails Resource method returns CompletionStage<Response>, where the Response
137 * emtity is a CompletionStageResponseTestClass, and where
138 * CompletionStageResponseTestClass is handled by CompletionStageResponseMessageBodyWriter,
139 * which has annotation @Produces("abc/xyz").
140 * @tpSince RESTEasy 3.5
141 */
142 @Test
143 public void testResponseTestClass() throws Exception
144 {
145 Invocation.Builder request = client.target(generateURL("/responsetestclass")).request();
146 Response response = request.get();
147 String entity = response.readEntity(String.class);
148 Assert.assertEquals(200, response.getStatus());
149 Assert.assertEquals("abc/xyz", response.getHeaderString("Content-Type"));
150 Assert.assertEquals("pdq", entity);
151 }
152
153 /**
154 * @tpTestDetails Resource method return type is CompletionStage<String>, and it passes
155 * null to CompleteableFuture.complete().
156 * @tpSince RESTEasy 3.5
157 */
158 @Test
159 public void testNull() throws Exception
160 {
161 Invocation.Builder request = client.target(generateURL("/null")).request();
162 Response response = request.get();
163 String entity = response.readEntity(String.class);
164 Assert.assertEquals(204, response.getStatus());
165 Assert.assertEquals(null, entity);
166 }
167
168 /**
169 * @tpTestDetails Resource method passes a WebApplicationException to
170 * to CompleteableFuture.completeExceptionally().
171 * @tpSince RESTEasy 3.5
172 */
173 @Test
174 public void testExceptionDelay() throws Exception
175 {
176 Invocation.Builder request = client.target(generateURL("/exception/delay")).request();
177 Response response = request.get();
178 String entity = response.readEntity(String.class);
179 Assert.assertEquals(444, response.getStatus());
180 Assert.assertEquals(CompletionStageResponseResource.EXCEPTION, entity);
181
182 // make sure the completion callback was called with with an error
183 request = client.target(generateURL("/callback-called-with-error")).request();
184 response = request.get();
185 Assert.assertEquals(200, response.getStatus());
186 response.close();
187 }
188
189 /**
190 * @tpTestDetails Resource method return type is CompletionStage<String>, but it
191 * throws a RuntimeException without creating a CompletionStage.
192 * @tpSince RESTEasy 3.5
193 */
194 @Test
195 public void testExceptionImmediateRuntime() throws Exception
196 {
197 Invocation.Builder request = client.target(generateURL("/exception/immediate/runtime")).request();
198 Response response = request.get();
199 String entity = response.readEntity(String.class);
200 Assert.assertEquals(500, response.getStatus());
201 if (serverIsLocal) {
202 Assert.assertTrue(entity.contains(CompletionStageResponseResource.EXCEPTION));
203 }
204 // make sure the completion callback was called with with an error
205 request = client.target(generateURL("/callback-called-with-error")).request();
206 response = request.get();
207 Assert.assertEquals(200, response.getStatus());
208 response.close();
209 }
210
211 /**
212 * @tpTestDetails Resource method return type is CompletionStage<String>, but it
213 * throws an Exception without creating a CompletionStage.
214 * @tpSince RESTEasy 3.5
215 */
216 @Test
217 public void testExceptionImmediateNotRuntime() throws Exception
218 {
219 Invocation.Builder request = client.target(generateURL("/exception/immediate/notruntime")).request();
220 Response response = request.get();
221 String entity = response.readEntity(String.class);
222 Assert.assertEquals(500, response.getStatus());
223 if (serverIsLocal) {
224 Assert.assertTrue(entity.contains(CompletionStageResponseResource.EXCEPTION));
225 }
226 response.close();
227
228 // make sure the completion callback was called with with an error
229 request = client.target(generateURL("/callback-called-with-error")).request();
230 response = request.get();
231 Assert.assertEquals(200, response.getStatus());
232 response.close();
233 }
234
235 /**
236 * @tpTestDetails Resource method returns CompletionStage<String>.
237 * @tpSince RESTEasy 3.5
238 */
239 @Test
240 public void testTextSingle() throws Exception
241 {
242 Invocation.Builder request = client.target(generateURL("/textSingle")).request();
243 Response response = request.get();
244 String entity = response.readEntity(String.class);
245 Assert.assertEquals(200, response.getStatus());
246 Assert.assertEquals(CompletionStageResponseResource.HELLO, entity);
247 }
248
249 /**
250 * @tpTestDetails Resource method returns CompletionStage<String>, data are computed after end-point method ends
251 * @tpSince RESTEasy 3.5
252 */
253 @Test
254 public void getDataWithDelayTest() throws Exception
255 {
256 Invocation.Builder request = client.target(generateURL("/sleep")).request();
257 Future<Response> future = request.async().get();
258 Assert.assertFalse(future.isDone());
259 Response response = future.get();
260 String entity = response.readEntity(String.class);
261 Assert.assertEquals(200, response.getStatus());
262 Assert.assertEquals(CompletionStageResponseResource.HELLO, entity);
263 }
264
265
266 /**
267 * @tpTestDetails Resource method returns CompletionStage<String>, client try to use proxy
268 * Regression check for https://issues.jboss.org/browse/RESTEASY-1798
269 * - RESTEasy proxy client can't use RxClient and CompletionStage
270 * @tpSince RESTEasy 3.5
271 */
272 @Test
273 @Category({ExpectedFailing.class})
274 public void proxyTest() throws Exception
275 {
276 CompletionStageProxy proxy = client.target(generateURL("/")).proxy(CompletionStageProxy.class);
277 Future<String> future = proxy.sleep().toCompletableFuture();
278 Assert.assertFalse(future.isDone());
279 Assert.assertEquals(CompletionStageResponseResource.HELLO, future.get());
280 }
281
282
283 }
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
56 import org.jboss.resteasy.test.response.resource.HttpRequestParameterInjectorClassicParam;
67 import org.jboss.resteasy.test.response.resource.HttpRequestParameterInjectorParamFactoryImpl;
78 import org.jboss.resteasy.test.response.resource.HttpRequestParameterInjectorResource;
6465 client.close();
6566 }
6667
68 /**
69 * @tpTestDetails Old Client usage.
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test
73 public void testCustomInjectorFactoryOldClient() throws Exception {
74 String url = generateURL("/foo");
75
76 String getResult = new ClientRequest(url).queryParameter("param", "getValue").accept(
77 "text/plain").get(String.class).getEntity();
78 Assert.assertEquals("getValue, getValue, ", getResult);
79
80 String postResult = new ClientRequest(generateURL("/foo")).formParameter("param", "postValue").accept(
81 "text/plain").post(String.class).getEntity();
82 Assert.assertEquals("postValue, , postValue", postResult);
83 }
84
6785 }
0 package org.jboss.resteasy.test.response;
1
2 import java.util.ArrayList;
3 import java.util.List;
4 import java.util.concurrent.CompletableFuture;
5 import java.util.concurrent.Future;
6 import java.util.concurrent.TimeUnit;
7 import java.util.concurrent.TimeoutException;
8
9 import javax.ws.rs.client.Client;
10 import javax.ws.rs.client.ClientBuilder;
11 import javax.ws.rs.client.Invocation;
12 import javax.ws.rs.client.WebTarget;
13 import javax.ws.rs.core.Response;
14 import javax.ws.rs.sse.SseEventSource;
15
16 import org.jboss.arquillian.container.test.api.Deployment;
17 import org.jboss.arquillian.container.test.api.RunAsClient;
18 import org.jboss.arquillian.junit.Arquillian;
19 import org.jboss.logging.Logger;
20 import org.jboss.resteasy.category.Jaxrs21;
21 import org.jboss.resteasy.test.response.resource.AsyncResponseCallback;
22 import org.jboss.resteasy.test.response.resource.AsyncResponseException;
23 import org.jboss.resteasy.test.response.resource.AsyncResponseExceptionMapper;
24 import org.jboss.resteasy.test.response.resource.PublisherResponseResource;
25 import org.jboss.resteasy.utils.PortProviderUtil;
26 import org.jboss.resteasy.utils.TestUtil;
27 import org.jboss.shrinkwrap.api.Archive;
28 import org.jboss.shrinkwrap.api.asset.StringAsset;
29 import org.jboss.shrinkwrap.api.spec.WebArchive;
30 import org.junit.After;
31 import org.junit.Assert;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.junit.experimental.categories.Category;
35 import org.junit.runner.RunWith;
36
37 /**
38 * @tpSubChapter Publisher response type
39 * @tpChapter Integration tests
40 * @tpSince RESTEasy 3.5
41 */
42 @RunWith(Arquillian.class)
43 @RunAsClient
44 @Category(Jaxrs21.class)
45 public class PublisherResponseTest {
46
47 Client client;
48
49 private final static Logger logger = Logger.getLogger(PublisherResponseTest.class);
50
51 @Deployment
52 public static Archive<?> deploy() {
53 WebArchive war = TestUtil.prepareArchive(PublisherResponseTest.class.getSimpleName());
54 war.addAsLibrary(TestUtil.resolveDependency("io.reactivex.rxjava2:rxjava:2.1.3"));
55 war.setManifest(new StringAsset("Manifest-Version: 1.0\n"
56 + "Dependencies: org.reactivestreams\n"));
57 return TestUtil.finishContainerPrepare(war, null, PublisherResponseResource.class,
58 AsyncResponseCallback.class, AsyncResponseExceptionMapper.class, AsyncResponseException.class);
59 }
60
61 private String generateURL(String path) {
62 return PortProviderUtil.generateURL(path, PublisherResponseTest.class.getSimpleName());
63 }
64
65 @Before
66 public void setup() {
67 client = ClientBuilder.newClient();
68 }
69
70 @After
71 public void close() {
72 client.close();
73 client = null;
74 }
75
76 /**
77 * @tpTestDetails Resource method returns Publisher<String>.
78 * @tpSince RESTEasy 3.5
79 */
80 @Test
81 public void testText() throws Exception
82 {
83 Invocation.Builder request = client.target(generateURL("/text")).request();
84 Response response = request.get();
85 String entity = response.readEntity(String.class);
86 Assert.assertEquals(200, response.getStatus());
87 Assert.assertEquals("[\"one\",\"two\"]", entity);
88
89 // make sure the completion callback was called with no error
90 request = client.target(generateURL("/callback-called-no-error")).request();
91 response = request.get();
92 Assert.assertEquals(200, response.getStatus());
93 response.close();
94 }
95
96 /**
97 * @tpTestDetails Resource method returns Publisher<String>, throws exception immediately.
98 * @tpSince RESTEasy 3.5
99 */
100 @Test
101 public void testTextErrorImmediate() throws Exception
102 {
103 Invocation.Builder request = client.target(generateURL("/text-error-immediate")).request();
104 Response response = request.get();
105 String entity = response.readEntity(String.class);
106 Assert.assertEquals(200, response.getStatus());
107 Assert.assertEquals("Got it", entity);
108
109 // make sure the completion callback was called with with an error
110 request = client.target(generateURL("/callback-called-with-error")).request();
111 response = request.get();
112 Assert.assertEquals(200, response.getStatus());
113 response.close();
114 }
115
116 /**
117 * @tpTestDetails Resource method returns Publisher<String>, throws exception in stream.
118 * @tpSince RESTEasy 3.5
119 */
120 @Test
121 public void testTextErrorDeferred() throws Exception
122 {
123 Invocation.Builder request = client.target(generateURL("/text-error-deferred")).request();
124 Response response = request.get();
125 String entity = response.readEntity(String.class);
126 Assert.assertEquals(200, response.getStatus());
127 Assert.assertEquals("Got it", entity);
128
129 // make sure the completion callback was called with with an error
130 request = client.target(generateURL("/callback-called-with-error")).request();
131 response = request.get();
132 Assert.assertEquals(200, response.getStatus());
133 response.close();
134 }
135
136 /**
137 * @tpTestDetails Resource method returns Publisher<String>.
138 * @tpSince RESTEasy 3.5
139 */
140 @Test
141 public void testChunked() throws Exception
142 {
143 Invocation.Builder request = client.target(generateURL("/chunked")).request();
144 Response response = request.get();
145 String entity = response.readEntity(String.class);
146 Assert.assertEquals(200, response.getStatus());
147 Assert.assertEquals("onetwo", entity);
148 }
149
150 /**
151 * @tpTestDetails Resource method returns Publisher<String>.
152 * @tpSince RESTEasy 3.5
153 */
154 @Test
155 public void testSse() throws Exception
156 {
157 WebTarget target = client.target(generateURL("/sse"));
158 List<String> collector = new ArrayList<>();
159 List<Throwable> errors = new ArrayList<>();
160 CompletableFuture<Void> future = new CompletableFuture<Void>();
161 SseEventSource source = SseEventSource.target(target).build();
162 source.register(evt -> {
163 String data = evt.readData(String.class);
164 collector.add(data);
165 if(collector.size() >= 2) {
166 future.complete(null);
167 }
168 },
169 t -> {
170 logger.error(t.getMessage(), t);
171 errors.add(t);
172 },
173 () -> {
174 // bah, never called
175 future.complete(null);
176 });
177 source.open();
178 future.get();
179 source.close();
180 Assert.assertEquals(2, collector.size());
181 Assert.assertEquals(0, errors.size());
182 Assert.assertEquals("one", collector.get(0));
183 Assert.assertEquals("two", collector.get(1));
184 }
185
186 /**
187 * @tpTestDetails Resource method unsubscribes on close for infinite streams.
188 * @tpSince RESTEasy 3.5
189 */
190 @Test
191 public void testInfiniteStreamsSse() throws Exception
192 {
193 WebTarget target = client.target(generateURL("/sse-infinite"));
194 List<String> collector = new ArrayList<>();
195 List<Throwable> errors = new ArrayList<>();
196 CompletableFuture<Void> future = new CompletableFuture<Void>();
197 SseEventSource source = SseEventSource.target(target).build();
198 source.register(evt -> {
199 String data = evt.readData(String.class);
200 collector.add(data);
201 if(collector.size() >= 2) {
202 future.complete(null);
203 }
204 },
205 t -> {
206 t.printStackTrace();
207 errors.add(t);
208 },
209 () -> {
210 // bah, never called
211 future.complete(null);
212 });
213 source.open();
214 future.get();
215 source.close();
216 Assert.assertEquals(2, collector.size());
217 Assert.assertEquals(0, errors.size());
218 Assert.assertEquals("one", collector.get(0));
219 Assert.assertEquals("one", collector.get(1));
220
221 close();
222 setup();
223 Thread.sleep(5000);
224 Invocation.Builder request = client.target(generateURL("/infinite-done")).request();
225 Response response = request.get();
226 String entity = response.readEntity(String.class);
227 Assert.assertEquals(200, response.getStatus());
228 Assert.assertEquals("true", entity);
229 }
230
231 /**
232 * @tpTestDetails Resource method unsubscribes on close for infinite streams.
233 * @tpSince RESTEasy 3.5
234 */
235 @Test
236 public void testInfiniteStreamsChunked() throws Exception
237 {
238 Invocation.Builder request = client.target(generateURL("/chunked-infinite")).request();
239 Future<Response> futureResponse = request.async().get();
240 try
241 {
242 futureResponse.get(2, TimeUnit.SECONDS);
243 }
244 catch(TimeoutException x)
245 {
246 }
247 close();
248 setup();
249 Thread.sleep(5000);
250 request = client.target(generateURL("/infinite-done")).request();
251 Response response = request.get();
252 String entity = response.readEntity(String.class);
253 Assert.assertEquals(200, response.getStatus());
254 Assert.assertEquals("true", entity);
255 }
256 }
5959 if (obj instanceof ArrayList) {
6060 List<Object> objs = (List<Object>)obj;
6161 if (objs.size() != 2) {
62 System.err.println(objs);
6263 Assert.fail("2 array objects expected " + objs.size() + " were returned");
6364 }
6465
7878
7979 @Test
8080 public void testStream() throws Exception {
81 Builder builder = client.target(generateURL("/test/document/abc/content")).request();
82
8183 try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
82 Builder builder = client.target(generateURL("/test/document/abc/content")).request();
83 // ByteArrayOutputStream baos = new ByteArrayOutputStream();
84 //builder.get().readEntity explicitly on the same line below and not saved in any temp variable
85 //to let the JVM try finalizing the ClientResponse object
86 InputStream ins = builder.get().readEntity(InputStream.class);
87 //suggest jvm to do gc and wait the gc notification
88 final CountDownLatch coutDown = new CountDownLatch(1);
8984
90 List<GarbageCollectorMXBean> gcbeans = ManagementFactory.getGarbageCollectorMXBeans();
91 NotificationListener listener = new NotificationListener() {
92 public void handleNotification(Notification notification, Object handback) {
93 coutDown.countDown();
85 if (! TestUtil.isIbmJdk()) {
86 //builder.get().readEntity explicitly on the same line below and not saved in any temp variable
87 //to let the JVM try finalizing the ClientResponse object
88 InputStream ins = builder.get().readEntity(InputStream.class);
89 //suggest jvm to do gc and wait the gc notification
90 final CountDownLatch coutDown = new CountDownLatch(1);
91
92 List<GarbageCollectorMXBean> gcbeans = ManagementFactory.getGarbageCollectorMXBeans();
93 NotificationListener listener = new NotificationListener() {
94 public void handleNotification(Notification notification, Object handback) {
95 coutDown.countDown();
96 }
97 };
98 try {
99 for (GarbageCollectorMXBean gcbean : gcbeans) {
100 NotificationEmitter emitter = (NotificationEmitter) gcbean;
101 emitter.addNotificationListener(listener, null, null);
102 }
103 System.gc();
104 coutDown.await(10, TimeUnit.SECONDS);
105
106 IOUtils.copy(ins, baos);
107 Assert.assertEquals(10000000, baos.size());
108 } finally {
109 //remove the listener
110 for (GarbageCollectorMXBean gcbean : gcbeans) {
111 ((NotificationEmitter) gcbean).removeNotificationListener(listener);
112 }
94113 }
95 };
96 try {
97 for (GarbageCollectorMXBean gcbean : gcbeans) {
98 NotificationEmitter emitter = (NotificationEmitter) gcbean;
99 emitter.addNotificationListener(listener, null, null);
100 }
101 System.gc();
102 coutDown.await(10, TimeUnit.SECONDS);
103
104 IOUtils.copy(ins, baos);
105 Assert.assertEquals(100000000, baos.size());
106 } finally {
107 //remove the listener
108 for (GarbageCollectorMXBean gcbean : gcbeans) {
109 ((NotificationEmitter) gcbean).removeNotificationListener(listener);
110 }
114 } else { // workaround for Ibm jdk - doesn't allow to use NotificationEmitter with GarbageCollectorMXBean
115 //builder.get().readEntity explicitly on the same line below and not saved in any temp variable
116 //to let the JVM try finalizing the ClientResponse object
117 IOUtils.copy(builder.get().readEntity(InputStream.class), baos);
118 Assert.assertEquals(10000000, baos.size());
111119 }
112120 }
113
114121 }
115 }
122 }
0 package org.jboss.resteasy.test.response;
1
2 import java.util.concurrent.CompletableFuture;
3 import java.util.concurrent.CompletionStage;
4
5 import javax.ws.rs.ext.Provider;
6
7 import org.jboss.resteasy.spi.AsyncResponseProvider;
8
9 import io.reactivex.Single;
10 import io.reactivex.disposables.Disposable;
11
12 @Provider
13 public class SingleProvider implements AsyncResponseProvider<Single<?>>
14 {
15
16 private static class SingleAdaptor<T> extends CompletableFuture<T>
17 {
18 private Disposable subscription;
19
20 public SingleAdaptor(Single<T> observable)
21 {
22 this.subscription = observable.subscribe(this::complete, this::completeExceptionally);
23 }
24
25 @Override
26 public boolean cancel(boolean mayInterruptIfRunning)
27 {
28 subscription.dispose();
29 return super.cancel(mayInterruptIfRunning);
30 }
31 }
32
33 @Override
34 public CompletionStage toCompletionStage(Single<?> asyncResponse)
35 {
36 return new SingleAdaptor<>(asyncResponse);
37 }
38
39 }
9999 String entity = response.readEntity(String.class);
100100 assertEquals("Wrong media type on response", TEXT_HTML_WITH_PARAMS.toString(), entity);
101101 }
102
103 /**
104 * @tpTestDetails Verifies that the q/qs factors are stripped from the response Content-type header if they are provided
105 * in the request. See RESTEASY-1765.
106 * @tpSince RESTEasy 3.0.25
107 */
108 @Test
109 public void testVariantWithQParameter() throws Exception {
110 ResteasyClient client = new ResteasyClientBuilder().build();
111 Invocation.Builder request = client.target(generateURL("/simple")).request();
112 request.accept("application/json;q=0.3, application/xml;q=0.2");
113 Response response = request.get();
114 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
115 assertEquals("application/json", response.getHeaderString("Content-Type"));
116 response.close();
117
118 request = client.target(generateURL("/simple")).request();
119 request.accept("application/json;qs=0.5, application/xml;qs=0.9");
120 response = request.get();
121 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
122 assertEquals("application/xml;charset=UTF-8", response.getHeaderString("Content-Type"));
123 }
102124 }
0 package org.jboss.resteasy.test.response.resource;
1
2 import java.util.concurrent.CountDownLatch;
3 import java.util.concurrent.TimeUnit;
4
5 import javax.ws.rs.container.CompletionCallback;
6
7 public class AsyncResponseCallback implements CompletionCallback {
8
9 private static CountDownLatch latch;
10 private static Throwable error;
11
12 public AsyncResponseCallback()
13 {
14 latch = new CountDownLatch(1);
15 error = null;
16 }
17
18 @Override
19 public void onComplete(Throwable throwable)
20 {
21 latch.countDown();
22 error = throwable;
23 }
24
25 public static void assertCalled(boolean withError)
26 {
27 boolean called = false;
28 try {
29 called = latch.await(2, TimeUnit.SECONDS);
30 } catch (Exception e) {
31 //ignore
32 }
33 if(!called)
34 throw new AssertionError("Not called");
35 if(withError && error == null
36 || !withError && error != null)
37 throw new AssertionError("Error mismatch");
38 }
39 }
0 package org.jboss.resteasy.test.response.resource;
1
2 @SuppressWarnings("serial")
3 public class AsyncResponseException extends RuntimeException
4 {
5
6 }
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class AsyncResponseExceptionMapper implements ExceptionMapper<AsyncResponseException>
8 {
9
10 @Override
11 public Response toResponse(AsyncResponseException exception)
12 {
13 return Response.ok("Got it").build();
14 }
15
16 }
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import java.util.concurrent.CompletionStage;
6
7
8 @Path("")
9 public interface CompletionStageProxy {
10 @GET
11 @Path("sleep")
12 @Produces("text/plain")
13 CompletionStage<String> sleep();
14 }
0 package org.jboss.resteasy.test.response.resource;
1
2 import java.io.IOException;
3 import java.io.OutputStream;
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.Type;
6 import java.nio.charset.StandardCharsets;
7
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.WebApplicationException;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.MultivaluedMap;
12 import javax.ws.rs.ext.MessageBodyWriter;
13 import javax.ws.rs.ext.Provider;
14
15 @Provider
16 @Produces("abc/xyz")
17 public class CompletionStageResponseMessageBodyWriter implements MessageBodyWriter<CompletionStageResponseTestClass> {
18
19 @Override
20 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
21 {
22 return CompletionStageResponseTestClass.class.isAssignableFrom(type);
23 }
24
25 @Override
26 public void writeTo(CompletionStageResponseTestClass t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
27 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
28 throws IOException, WebApplicationException
29 {
30 entityStream.write(t.s.getBytes(StandardCharsets.UTF_8));
31 }
32 }
0 package org.jboss.resteasy.test.response.resource;
1
2 import java.util.concurrent.CompletableFuture;
3 import java.util.concurrent.CompletionStage;
4 import java.util.concurrent.ExecutorService;
5 import java.util.concurrent.Executors;
6
7 import javax.ws.rs.GET;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.WebApplicationException;
11 import javax.ws.rs.core.Context;
12 import javax.ws.rs.core.Response;
13 import javax.ws.rs.core.UriInfo;
14
15 import org.jboss.resteasy.spi.HttpRequest;
16
17 import io.reactivex.Single;
18
19 @Path("")
20 public class CompletionStageResponseResource {
21
22 public static final String HELLO = "Hello CompletionStage world!";
23 public static final String EXCEPTION = "CompletionStage exception";
24
25 @GET
26 @Path("text")
27 @Produces("text/plain")
28 public CompletionStage<String> text(@Context HttpRequest req) {
29 req.getAsyncContext().getAsyncResponse().register(new AsyncResponseCallback());
30 CompletableFuture<String> cs = new CompletableFuture<>();
31 ExecutorService executor = Executors.newSingleThreadExecutor();
32 executor.submit(
33 new Runnable() {
34 public void run() {
35 cs.complete(HELLO);
36 }
37 });
38 return cs;
39 }
40
41 @GET
42 @Path("textSingle")
43 @Produces("text/plain")
44 public Single<String> textSingle() {
45 return Single.create(emitter -> {
46 ExecutorService executor = Executors.newSingleThreadExecutor();
47 executor.submit(
48 new Runnable() {
49 public void run() {
50 emitter.onSuccess(HELLO);
51 }
52 });
53 });
54 }
55
56 @GET
57 @Path("testclass")
58 public CompletionStage<CompletionStageResponseTestClass> entityTestClass() {
59 CompletableFuture<CompletionStageResponseTestClass> cs = new CompletableFuture<>();
60 ExecutorService executor = Executors.newSingleThreadExecutor();
61 executor.submit(
62 new Runnable() {
63 public void run() {
64 cs.complete(new CompletionStageResponseTestClass("pdq"));
65 }
66 });
67 return cs;
68 }
69
70 @GET
71 @Path("response")
72 @Produces("text/xxx")
73 public CompletionStage<Response> response() {
74 CompletableFuture<Response> cs = new CompletableFuture<>();
75 ExecutorService executor = Executors.newSingleThreadExecutor();
76 executor.submit(
77 new Runnable() {
78 public void run() {
79 cs.complete(Response.ok(HELLO, "text/plain").build());
80 }
81 });
82 return cs;
83 }
84
85 @GET
86 @Path("responsetestclass")
87 public CompletionStage<Response> responseTestClass() {
88 CompletableFuture<Response> cs = new CompletableFuture<>();
89 ExecutorService executor = Executors.newSingleThreadExecutor();
90 executor.submit(
91 new Runnable() {
92 public void run() {
93 cs.complete(Response.ok(new CompletionStageResponseTestClass("pdq")).build());
94 }
95 });
96 return cs;
97 }
98
99 @GET
100 @Path("null")
101 @Produces("text/plain")
102 public CompletionStage<String> nullEntity() {
103 CompletableFuture<String> cs = new CompletableFuture<>();
104 ExecutorService executor = Executors.newSingleThreadExecutor();
105 executor.submit(
106 new Runnable() {
107 public void run() {
108 cs.complete(null);
109 }
110 });
111 return cs;
112 }
113
114 @GET
115 @Path("exception/delay")
116 @Produces("text/plain")
117 public CompletionStage<String> exceptionDelay(@Context HttpRequest req) {
118 req.getAsyncContext().getAsyncResponse().register(new AsyncResponseCallback());
119 CompletableFuture<String> cs = new CompletableFuture<>();
120 ExecutorService executor = Executors.newSingleThreadExecutor();
121 executor.submit(
122 new Runnable() {
123 public void run() {
124 try {
125 Thread.sleep(3000L); // make sure that response will be created after end-point method ends
126 } catch (InterruptedException e) {
127 throw new RuntimeException(e);
128 }
129 Response response = Response.status(444).entity(EXCEPTION).build();
130 cs.completeExceptionally(new WebApplicationException(response));
131 }
132 });
133 return cs;
134 }
135
136 @GET
137 @Path("exception/immediate/runtime")
138 @Produces("text/plain")
139 public CompletionStage<String> exceptionImmediateRuntime(@Context HttpRequest req) {
140 req.getAsyncContext().getAsyncResponse().register(new AsyncResponseCallback());
141 throw new RuntimeException(EXCEPTION + ": expect stacktrace");
142 }
143
144 @GET
145 @Path("exception/immediate/notruntime")
146 @Produces("text/plain")
147 public CompletionStage<String> exceptionImmediateNotRuntime(@Context HttpRequest req) throws Exception {
148 req.getAsyncContext().getAsyncResponse().register(new AsyncResponseCallback());
149 throw new Exception( EXCEPTION + ": expect stacktrace");
150 }
151
152 @GET
153 @Path("callback-called-no-error")
154 public String callbackCalledNoError() {
155 AsyncResponseCallback.assertCalled(false);
156 return "OK";
157 }
158
159 @GET
160 @Path("callback-called-with-error")
161 public String callbackCalledWithError() {
162 AsyncResponseCallback.assertCalled(true);
163 return "OK";
164 }
165
166 @GET
167 @Path("host")
168 public String getHost(@Context UriInfo uri) {
169 return uri.getRequestUri().getHost();
170 }
171
172 @GET
173 @Path("sleep")
174 @Produces("text/plain")
175 public CompletionStage<String> sleep() {
176 CompletableFuture<String> cs = new CompletableFuture<>();
177 ExecutorService executor = Executors.newSingleThreadExecutor();
178 executor.submit(() -> {
179 try {
180 Thread.sleep(3000L);
181 } catch (InterruptedException e) {
182 throw new RuntimeException(e);
183 }
184 cs.complete(HELLO);
185 });
186 return cs;
187 }
188 }
0 package org.jboss.resteasy.test.response.resource;
1
2 public class CompletionStageResponseTestClass
3 {
4 String s;
5
6 public CompletionStageResponseTestClass(String s) {
7 this.s = s;
8 }
9 }
0 package org.jboss.resteasy.test.response.resource;
1
2 import java.util.Arrays;
3 import java.util.concurrent.TimeUnit;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.MediaType;
10
11 import org.jboss.resteasy.annotations.Stream;
12 import org.jboss.resteasy.spi.HttpRequest;
13 import org.reactivestreams.Publisher;
14
15 import io.reactivex.Flowable;
16
17 @Path("")
18 public class PublisherResponseResource {
19
20 private static boolean terminated = false;
21
22 @GET
23 @Path("text")
24 @Produces("application/json")
25 public Publisher<String> text(@Context HttpRequest req) {
26 req.getAsyncContext().getAsyncResponse().register(new AsyncResponseCallback());
27 return Flowable.fromArray("one", "two");
28 }
29
30 @GET
31 @Path("text-infinite")
32 @Produces("application/json")
33 public Publisher<String> textInfinite() {
34 terminated = false;
35 System.err.println("Starting ");
36 return Flowable.interval(1, TimeUnit.SECONDS).map(v -> {
37 return "one";
38 }).doFinally(() -> {
39 terminated = true;
40 });
41 }
42
43 @GET
44 @Path("callback-called-no-error")
45 public String callbackCalledNoError() {
46 AsyncResponseCallback.assertCalled(false);
47 return "OK";
48 }
49
50 @GET
51 @Path("text-error-immediate")
52 @Produces("application/json")
53 public Publisher<String> textErrorImmediate(@Context HttpRequest req) {
54 req.getAsyncContext().getAsyncResponse().register(new AsyncResponseCallback());
55 throw new AsyncResponseException();
56 }
57
58 @GET
59 @Path("text-error-deferred")
60 @Produces("application/json")
61 public Publisher<String> textErrorDeferred(@Context HttpRequest req) {
62 req.getAsyncContext().getAsyncResponse().register(new AsyncResponseCallback());
63 return Flowable.error(new AsyncResponseException());
64 }
65
66 @GET
67 @Path("callback-called-with-error")
68 public String callbackCalledWithError() {
69 AsyncResponseCallback.assertCalled(true);
70 return "OK";
71 }
72
73 @Stream
74 @GET
75 @Path("chunked")
76 @Produces("application/json")
77 public Publisher<String> chunked() {
78 return Flowable.fromArray("one", "two");
79 }
80
81 @Stream
82 @GET
83 @Path("chunked-infinite")
84 @Produces("application/json")
85 public Publisher<String> chunkedInfinite() {
86 terminated = false;
87 System.err.println("Starting ");
88 char[] chunk = new char[8192];
89 Arrays.fill(chunk, 'a');
90 String ret = new String(chunk);
91 return Flowable.interval(1, TimeUnit.SECONDS).map(v -> {
92 return ret;
93 }).doFinally(() -> {
94 terminated = true;
95 });
96 }
97
98 @GET
99 @Path("sse")
100 @Produces(MediaType.SERVER_SENT_EVENTS)
101 public Publisher<String> sse() {
102 return Flowable.fromArray("one", "two");
103 }
104
105 @GET
106 @Path("sse-infinite")
107 @Produces(MediaType.SERVER_SENT_EVENTS)
108 public Publisher<String> sseInfinite() {
109 terminated = false;
110 return Flowable.interval(1, TimeUnit.SECONDS).map(v -> {
111 return "one";
112 }).doFinally(() -> {
113 terminated = true;
114 });
115 }
116
117 @GET
118 @Path("infinite-done")
119 public String sseInfiniteDone() {
120 return String.valueOf(terminated);
121 }
122 }
8080 public Response nullEntityResponse() {
8181 RuntimeDelegate rd = RuntimeDelegate.getInstance();
8282 Response.ResponseBuilder rb = rd.createResponseBuilder();
83 return rb.entity(null).build();
83 return rb.entity((Object)null).build();
8484 }
8585 }
1414 public Response readContent(@PathParam("documentId") java.lang.String id)
1515 {
1616 StringBuffer sb = new StringBuffer();
17 for (int i = 0; i < 100000000; i++)
17 for (int i = 0; i < 10000000; i++)
1818 {
1919 sb.append("a");
2020 }
3636 MediaType selected = request.selectVariant(variants).getMediaType();
3737 return selected.toString();
3838 }
39
40 @GET
41 @Path("simple")
42 public String simple() {
43 return "Hello";
44 }
3945 }
99 import org.jboss.arquillian.container.test.api.RunAsClient;
1010 import org.jboss.arquillian.junit.Arquillian;
1111 import org.jboss.as.arquillian.api.ServerSetup;
12 import org.jboss.resteasy.category.NotForForwardCompatibility;
1213 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
1314 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
1415 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
2425 import org.junit.Assert;
2526 import org.junit.BeforeClass;
2627 import org.junit.Test;
28 import org.junit.experimental.categories.Category;
2729 import org.junit.runner.RunWith;
2830
2931 import javax.ws.rs.core.Response;
3638 /**
3739 * @tpSubChapter Security
3840 * @tpChapter Integration tests
39 * @tpTestCaseDetails Custom ExceptionMapper is used when Forbidden is thrown from RoleBasedSecurityFilter
40 * @tpSince RESTEasy 3.1.0
41 * @tpTestCaseDetails Custom ExceptionMapper is used when Forbidden is thrown from RoleBasedSecurityFilter, see RESTEASY-1342
42 * @tpSince RESTEasy 3.0.21.Final
4143 */
4244 @ServerSetup({CustomForbiddenMessageTest.SecurityDomainSetup.class})
4345 @RunWith(Arquillian.class)
4446 @RunAsClient
47 @Category({NotForForwardCompatibility.class})
4548 public class CustomForbiddenMessageTest {
4649
4750 private static ResteasyClient authorizedClient;
8588
8689 /**
8790 * @tpTestDetails Tests custom message from custom ExceptionMapper
88 * @tpSince RESTEasy 3.1.0
91 * @tpSince RESTEasy 3.0.21.Final
8992 */
9093 @Test
9194 public void testCustomExceptionMapper() throws Exception {
5757 @Test
5858 public void testSourceWithStringReader() throws Exception {
5959 Response response = client.target(generateURL("/test")).request()
60 .post(Entity.entity(new StreamSource(new StringReader(book)), "application/*+xml"));
60 .post(Entity.entity(new StreamSource(new StringReader(book)), "application/*+xml"));
6161 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
6262 String entity = response.readEntity(String.class);
6363 Assert.assertTrue(entity.contentEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><book><title>Monkey kingdom</title></book>"));
6767 public void testSourceWithInputStream() throws Exception {
6868 InputStream stream = new ByteArrayInputStream(book.getBytes(StandardCharsets.UTF_8));
6969 Response response = client.target(generateURL("/test")).request()
70 .post(Entity.entity(new StreamSource(stream), "application/*+xml"));
70 .post(Entity.entity(new StreamSource(stream), "application/*+xml"));
7171 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
7272 String entity = response.readEntity(String.class);
7373 Assert.assertTrue(entity.contentEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><book><title>Monkey kingdom</title></book>"));
0 package org.jboss.resteasy.test.validation;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Test for old client)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Test for old client)
7 import org.jboss.resteasy.test.validation.resource.ContextProvidersCustomer;
8 import org.jboss.resteasy.test.validation.resource.ContextProvidersCustomerForm;
9 import org.jboss.resteasy.test.validation.resource.ContextProvidersName;
10 import org.jboss.resteasy.test.validation.resource.ContextProvidersResource;
11 import org.jboss.resteasy.test.validation.resource.ContextProvidersXop;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Assert;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.core.MediaType;
22 import java.lang.annotation.Annotation;
23 import java.lang.reflect.Type;
24
25 /**
26 * @tpSubChapter Multipart provider
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Regression test for RESTEASY-1119. Test for old client.
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class ContextProvidersOldClientTest extends ContextProvidersTestBase {
34 @Deployment
35 public static Archive<?> createTestArchive() {
36 WebArchive war = TestUtil.prepareArchive(ContextProvidersOldClientTest.class.getSimpleName())
37 .addClasses(ContextProvidersCustomer.class, ContextProvidersCustomerForm.class, ContextProvidersName.class, ContextProvidersXop.class)
38 .addClass(ContextProvidersTestBase.class)
39 .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
40
41 return TestUtil.finishContainerPrepare(war, null, ContextProvidersResource.class);
42 }
43
44 private static String generateURL(String path) {
45 return PortProviderUtil.generateURL(path, ContextProvidersOldClientTest.class.getSimpleName());
46 }
47
48 @Override
49 <T> T get(String path, Class<T> clazz, Annotation[] annotations) throws Exception {
50 ClientRequest request = new ClientRequest(generateURL(path));
51 ClientResponse<T> response = request.get(clazz);
52 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
53 T entity = response.getEntity(clazz, null, annotations);
54 return entity;
55 }
56
57 @Override
58 <S, T> T post(String path, S payload, MediaType mediaType,
59 Class<T> returnType, Type genericReturnType, Annotation[] annotations) throws Exception {
60 ClientRequest request = new ClientRequest(generateURL(path));
61 request.body(mediaType, payload, payload.getClass(), null, annotations);
62 ClientResponse response = request.post();
63 T entity;
64 if (genericReturnType != null) {
65 entity = (T) response.getEntity(returnType, genericReturnType);
66 } else {
67 entity = (T) response.getEntity(returnType);
68 }
69
70 return entity;
71 }
72
73 }
8383
8484 // Get parts by name.
8585 ContextProvidersCustomer c = entity.getFormDataPart("bill", ContextProvidersCustomer.class, null);
86 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bill", c.getName());
86 Assert.assertTrue(RESPONSE_ERROR_MSG, c.getName().startsWith("Bill"));
8787 String s = entity.getFormDataPart("bob", String.class, null);
8888 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bob", s);
89
90 Assert.assertTrue(RESPONSE_ERROR_MSG, 2 == entity.getFormDataMap().get("bill").size());
8991
9092 // Iterate over list of parts.
9193 Map<String, List<InputPart>> map = entity.getFormDataMap();
9698 InputPart inputPart = it2.next();
9799 if (MediaType.APPLICATION_XML_TYPE.equals(inputPart.getMediaType())) {
98100 c = inputPart.getBody(ContextProvidersCustomer.class, null);
99 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bill", c.getName());
101 Assert.assertTrue(RESPONSE_ERROR_MSG, c.getName().startsWith("Bill"));
100102 } else {
101103 s = inputPart.getBody(String.class, null);
102104 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bob", s);
285285 } catch (ValidationException ve) {
286286 // OK
287287 } catch (Exception e) {
288 if (e.getCause() != null && e.getCause().getMessage().contains("Caused by: javax.validation.ValidationException")) {
288 if (e.getMessage().contains("Caused by: javax.validation.ValidationException") ||
289 (e.getCause() != null && e.getCause().getMessage().contains("Caused by: javax.validation.ValidationException"))) {
289290 // OK
290291 return;
291292 }
4040 import org.jboss.resteasy.test.validation.resource.ValidationComplexResourceWithAllFivePotentialViolations;
4141 import org.jboss.resteasy.test.validation.resource.ValidationComplexResourceWithArray;
4242 import org.jboss.resteasy.test.validation.resource.ValidationComplexResourceWithClassConstraint;
43 import org.jboss.resteasy.test.validation.resource.ValidationComplexResourceWithClassConstraintInterface;
4344 import org.jboss.resteasy.test.validation.resource.ValidationComplexResourceWithFieldAndProperty;
4445 import org.jboss.resteasy.test.validation.resource.ValidationComplexResourceWithGraph;
4546 import org.jboss.resteasy.test.validation.resource.ValidationComplexResourceWithInvalidField;
7576 import javax.ws.rs.core.MediaType;
7677 import javax.ws.rs.core.Response;
7778 import java.lang.reflect.ReflectPermission;
79 import java.net.SocketPermission;
7880 import java.util.*;
81 import java.util.logging.LoggingPermission;
7982
8083 /**
8184 * @tpSubChapter Response
126129 ValidationComplexClassValidatorSuperInheritance.class,
127130 ValidationComplexClassConstraint2.class, ValidationComplexClassValidator2.class);
128131 // Arquillian in the deployment
129 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(new ReflectPermission("suppressAccessChecks"),
132 war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
133 new LoggingPermission("control", ""),
134 new PropertyPermission("arquillian.*", "read"),
135 new PropertyPermission("ipv6", "read"),
136 new PropertyPermission("node", "read"),
137 new PropertyPermission("org.jboss.resteasy.port", "read"),
138 new ReflectPermission("suppressAccessChecks"),
130139 new RuntimePermission("accessDeclaredMembers"),
131 new PropertyPermission("arquillian.*", "read")), "permissions.xml");
140 new RuntimePermission("getenv.RESTEASY_PORT"),
141 new SocketPermission(PortProviderUtil.getHost(), "connect,resolve")
142 ), "permissions.xml");
132143 war.addClasses(TestUtil.class, PortProviderUtil.class);
133144 return war;
134145 }
141152 return war;
142153 }
143154
144 public static Archive<?> basicDeployment(Class<?> clazz) {
145 WebArchive war = TestUtil.prepareArchive(BASIC_DEPLOYMENT + clazz.getSimpleName());
155 public static Archive<?> basicDeployment(Class<?>... clazz) {
156 WebArchive war = TestUtil.prepareArchive(BASIC_DEPLOYMENT + clazz[0].getSimpleName());
146157 war = addBasicClasses(war);
147158 return TestUtil.finishContainerPrepare(war, null, clazz);
148159 }
185196
186197 @Deployment(name = "basicDeploymentTestResourceWithClassConstraint")
187198 public static Archive<?> basicDeploymentTestResourceWithClassConstraint() {
188 return basicDeployment(ValidationComplexResourceWithClassConstraint.class);
199 return basicDeployment(ValidationComplexResourceWithClassConstraint.class, ValidationComplexResourceWithClassConstraintInterface.class);
189200 }
190201
191202 @Deployment(name = "basicDeploymentTestResourceWithGraph")
256267
257268 @Deployment(name = "basicDeploymentTestResourceWithOtherGroups")
258269 public static Archive<?> basicDeploymentTestResourceWithOtherGroups() {
259 return basicDeployment(ValidationComplexResourceWithOtherGroups.class);
270 return basicDeployment(ValidationComplexResourceWithOtherGroups.class, ValidationComplexResourceWithClassConstraintInterface.class);
260271 }
261272
262273 /**
88 import org.jboss.arquillian.container.test.api.OperateOnDeployment;
99 import org.jboss.arquillian.container.test.api.RunAsClient;
1010 import org.jboss.arquillian.junit.Arquillian;
11 import org.jboss.resteasy.api.validation.ResteasyConstraintViolation;
1112 import org.jboss.resteasy.api.validation.ResteasyViolationException;
1213 import org.jboss.resteasy.api.validation.Validation;
1314 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
1617 import org.jboss.resteasy.test.validation.resource.ValidationExceptionCrazyConstraint;
1718 import org.jboss.resteasy.test.validation.resource.ValidationExceptionCrazyValidator;
1819 import org.jboss.resteasy.test.validation.resource.ValidationExceptionIncorrectConstraint;
20 import org.jboss.resteasy.test.validation.resource.ValidationExceptionMapper;
1921 import org.jboss.resteasy.test.validation.resource.ValidationExceptionOtherConstraint;
2022 import org.jboss.resteasy.test.validation.resource.ValidationExceptionOtherValidationException;
2123 import org.jboss.resteasy.test.validation.resource.ValidationExceptionOtherValidationException2;
4143
4244 import static org.jboss.resteasy.utils.PortProviderUtil.generateURL;
4345
46 import java.util.List;
47
4448 /**
4549 * @tpSubChapter Validator provider
4650 * @tpChapter Integration tests
5458 static ResteasyClient client;
5559
5660 private static final String DEF_EXCEPTION = "constraintDefinitionException";
61 private static final String CUSTOM_DEF_EXCEPTION = "customConstraintDefinitionException";
5762 private static final String DECL_EXCEPTION = "constraintDeclarationException";
63 private static final String CUSTOM_DECL_EXCEPTION = "customConstraintDeclarationException";
5864 private static final String GROUP_DEF_EXCEPTION = "groupDefinitionException";
65 private static final String CUSTOM_GROUP_DEF_EXCEPTION = "customGroupDefinitionException";
5966 private static final String OTHER_EXCEPTION = "otherException";
6067 private static final String CRAZY_EXCEPTION = "crazyException";
6168 private static final String ERROR_MESSAGE = "Expected other response";
7582 war.addClass(ValidationExceptionOtherValidator.class);
7683 war.addClass(ValidationExceptionTestGroup1.class);
7784 war.addClass(ValidationExceptionTestGroup2.class);
85 war.addClass(ValidationExceptionMapper.class);
7886 return TestUtil.finishContainerPrepare(war, null, resourceClasses);
7987 }
8088
93101 return deploy(DEF_EXCEPTION, ValidationExceptionResourceWithIncorrectConstraint.class);
94102 }
95103
104 @Deployment(name = CUSTOM_DEF_EXCEPTION)
105 public static Archive<?> customConstraintDefinitionExceptionDeploy() throws Exception {
106 return deploy(CUSTOM_DEF_EXCEPTION, ValidationExceptionResourceWithIncorrectConstraint.class,
107 ValidationExceptionResourceWithIncorrectConstraint.ConstraintDefinitionExceptionMapper.class);
108 }
109
96110 @Deployment(name = DECL_EXCEPTION)
97111 public static Archive<?> constraintDeclarationExceptionDeploy() throws Exception {
98112 return deploy(DECL_EXCEPTION, ValidationExceptionSubResourceWithInvalidOverride.class, ValidationExceptionSuperResource.class);
99113 }
100114
115 @Deployment(name = CUSTOM_DECL_EXCEPTION)
116 public static Archive<?> customConstraintDeclarationExceptionDeploy() throws Exception {
117 return deploy(CUSTOM_DECL_EXCEPTION, ValidationExceptionSubResourceWithInvalidOverride.class,
118 ValidationExceptionSuperResource.class,
119 ValidationExceptionSubResourceWithInvalidOverride.ConstraintDeclarationExceptionMapper.class);
120 }
121
101122 @Deployment(name = GROUP_DEF_EXCEPTION)
102123 public static Archive<?> groupDefinitionExceptionDeploy() throws Exception {
103124 return deploy(GROUP_DEF_EXCEPTION, ValidationExceptionResourceWithInvalidConstraintGroup.class);
125 }
126
127 @Deployment(name = CUSTOM_GROUP_DEF_EXCEPTION)
128 public static Archive<?> customGroupDefinitionExceptionDeploy() throws Exception {
129 return deploy(CUSTOM_GROUP_DEF_EXCEPTION, ValidationExceptionResourceWithInvalidConstraintGroup.class,
130 ValidationExceptionResourceWithInvalidConstraintGroup.GroupDefinitionExceptionMapper.class);
104131 }
105132
106133 @Deployment(name = OTHER_EXCEPTION)
130157 Assert.assertTrue(ERROR_MESSAGE, entity.contains("ConstraintDefinitionException"));
131158 }
132159
160 @Test
161 @OperateOnDeployment(CUSTOM_DEF_EXCEPTION)
162 public void testCustomConstraintDefinitionException() throws Exception {
163 Response response = client.target(generateURL("/", CUSTOM_DEF_EXCEPTION)).request().post(null);
164 Assert.assertEquals(HttpResponseCodes.SC_INTERNAL_SERVER_ERROR, response.getStatus());
165 String header = response.getStringHeaders().getFirst(Validation.VALIDATION_HEADER);
166 Assert.assertNotNull(ERROR_HEADER_MESSAGE, header);
167 Assert.assertTrue(ERROR_HEADER_VALIDATION_EXCEPTION_MESSAGE, Boolean.valueOf(header));
168 String entity = response.readEntity(String.class);
169 logger.info("entity: " + entity);
170 Assert.assertTrue(ERROR_MESSAGE, entity.contains("ConstraintDefinitionException"));
171 Assert.assertTrue(ERROR_MESSAGE,
172 entity.contains(ValidationExceptionResourceWithIncorrectConstraint.ConstraintDefinitionExceptionMapper.class.getName()));
173 }
174
133175 /**
134176 * @tpTestDetails Resource with incorrect constraint declaration, constraint definition exception is expected
135177 * @tpSince RESTEasy 3.0.16
146188 logger.info("entity: " + entity);
147189 Assert.assertTrue(ERROR_MESSAGE, entity.contains("ConstraintDeclarationException"));
148190 }
191
192 @Test
193 @OperateOnDeployment(CUSTOM_DECL_EXCEPTION)
194 public void testCustomConstraintDeclarationException() throws Exception {
195 Response response = client.target(generateURL("/", CUSTOM_DECL_EXCEPTION)).request().post(null);
196 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-3459"),
197 HttpResponseCodes.SC_INTERNAL_SERVER_ERROR, response.getStatus());
198 String header = response.getStringHeaders().getFirst(Validation.VALIDATION_HEADER);
199 Assert.assertNotNull(ERROR_HEADER_MESSAGE, header);
200 Assert.assertTrue(ERROR_HEADER_VALIDATION_EXCEPTION_MESSAGE, Boolean.valueOf(header));
201 String entity = response.readEntity(String.class);
202 logger.info("entity: " + entity);
203 Assert.assertTrue(ERROR_MESSAGE, entity.contains("ConstraintDeclarationException"));
204 Assert.assertTrue(ERROR_MESSAGE,
205 entity.contains(ValidationExceptionSubResourceWithInvalidOverride.ConstraintDeclarationExceptionMapper.class.getName()));
206 }
149207
150208 /**
151209 * @tpTestDetails Resource with incorrect group definition, group definition exception is expected
163221 logger.info("entity: " + entity);
164222 Assert.assertTrue(ERROR_MESSAGE, entity.contains("GroupDefinitionException"));
165223 }
224
225 @Test
226 @OperateOnDeployment(CUSTOM_GROUP_DEF_EXCEPTION)
227 public void testCustomGroupDefinitionException() throws Exception {
228 Response response = client.target(generateURL("/", CUSTOM_GROUP_DEF_EXCEPTION)).request().get();
229 Assert.assertEquals(HttpResponseCodes.SC_INTERNAL_SERVER_ERROR, response.getStatus());
230 String header = response.getStringHeaders().getFirst(Validation.VALIDATION_HEADER);
231 Assert.assertNotNull(ERROR_HEADER_MESSAGE, header);
232 Assert.assertTrue(ERROR_HEADER_VALIDATION_EXCEPTION_MESSAGE, Boolean.valueOf(header));
233 String entity = response.readEntity(String.class);
234 logger.info("entity: " + entity);
235 Assert.assertTrue(ERROR_MESSAGE, entity.contains("GroupDefinitionException"));
236 Assert.assertTrue(ERROR_MESSAGE,
237 entity.contains(ValidationExceptionResourceWithInvalidConstraintGroup.GroupDefinitionExceptionMapper.class.getName()));
238 }
166239
167240 /**
168241 * @tpTestDetails Tests for: Exception thrown during validation of field, Exception thrown during validation of parameter,
236309 String header = response.getStringHeaders().getFirst(Validation.VALIDATION_HEADER);
237310 Assert.assertNotNull(ERROR_HEADER_MESSAGE, header);
238311 Assert.assertTrue(ERROR_HEADER_VALIDATION_EXCEPTION_MESSAGE, Boolean.valueOf(header));
239 String entity = response.readEntity(String.class);
240 logger.info("entity: " + entity);
241 ResteasyViolationException e = new ResteasyViolationException(entity);
312 ResteasyViolationException resteasyViolationException = new ResteasyViolationException(
313 response.readEntity(String.class));
314 List<ResteasyConstraintViolation> classViolations = resteasyViolationException.getClassViolations();
315 Assert.assertEquals(1, classViolations.size());
316 Assert.assertEquals(ValidationExceptionCrazyConstraint.DEFAULT_MESSAGE, classViolations.get(0).getMessage());
317 logger.info("entity: " + resteasyViolationException);
242318 }
243319 }
6161 Response response = builder.post(Entity.entity("-1", MediaType.APPLICATION_JSON_TYPE));
6262 String responseBody = response.readEntity(String.class);
6363 Assert.assertThat("Wrong validation error", responseBody, containsString("must be greater than or equal to 1"));
64 Assert.assertThat("Wrong validation error", responseBody, containsString("may not be null"));
64 Assert.assertTrue("Wrong validation error", responseBody.contains("may not be null") || responseBody.contains("must not be null"));
6565 }
6666 }
3030 * @tpSubChapter Validation
3131 * @tpChapter Integration tests
3232 * @tpTestCaseDetails Regression test for RESTEASY-1459
33 * @tpSince RESTEasy 3.1.0.Final
33 * @tpSince RESTEasy 3.0.20.Final
3434 */
3535 @RunWith(Arquillian.class)
3636 @RunAsClient
00 package org.jboss.resteasy.test.validation.cdi.resource;
1
2 import org.jboss.logging.Logger;
13
24 import javax.enterprise.context.ApplicationScoped;
35
46 @ApplicationScoped
57 public class ApplicationScopeRestServiceAppScoped implements ApplicationScopeIRestServiceAppScoped {
68
9 private final static Logger logger = Logger.getLogger(ApplicationScopeRestServiceAppScoped.class);
10
711 public String sendDto(ApplicationScopeMyDto myDto) {
8 System.out.println("RestServiceAppScoped: Nevertheless: " + myDto);
9 new Exception("RestServiceAppScoped").printStackTrace();
12 if (logger.isDebugEnabled())
13 {
14 logger.debug("RestServiceAppScoped: Nevertheless: " + myDto, new Exception("RestServiceAppScoped"));
15 }
1016 return myDto == null ? null : myDto.getPath();
1117 }
1218 }
00 package org.jboss.resteasy.test.validation.cdi.resource;
1
2 import org.jboss.logging.Logger;
13
24 import javax.enterprise.context.RequestScoped;
35 import javax.ws.rs.core.Response;
46
57 @RequestScoped
68 public class ApplicationScopeRestServiceReqScoped implements ApplicationScopeIRestServiceReqScoped {
7
9
10 private final static Logger logger = Logger.getLogger(ApplicationScopeRestServiceReqScoped.class);
11
812 public Response sendDto(ApplicationScopeMyDto myDto) {
9 System.out.println("RestServiceReqScoped: Nevertheless: " + myDto);
10 new Exception("RestServiceReqScoped").printStackTrace();
13 if (logger.isDebugEnabled())
14 {
15 logger.debug("RestServiceReqScoped: Nevertheless: " + myDto, new Exception("RestServiceReqScoped"));
16 }
1117 return Response.ok(myDto == null ? "null" : myDto.getPath()).header("entered", "true").build();
1218 }
1319 }
4141 @Path("get/form")
4242 public MultipartFormDataOutput getForm() {
4343 MultipartFormDataOutput output = new MultipartFormDataOutput();
44 output.addFormData("bill", new ContextProvidersCustomer("Bill-2"), MediaType.APPLICATION_XML_TYPE, "tmp2");
45 output.addFormData("bob", "Bob", MediaType.TEXT_PLAIN_TYPE);
4446 output.addFormData("bill", new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE, "tmp1");
45 output.addFormData("bob", "Bob", MediaType.TEXT_PLAIN_TYPE);
4647 return output;
4748 }
4849
22 import javax.validation.ConstraintValidator;
33 import javax.validation.ConstraintValidatorContext;
44
5 public class ValidationComplexClassValidator implements ConstraintValidator<ValidationComplexClassConstraint, ValidationComplexResourceWithClassConstraint> {
5 public class ValidationComplexClassValidator implements ConstraintValidator<ValidationComplexClassConstraint, ValidationComplexResourceWithClassConstraintInterface> {
66 public int length;
77
88 public void initialize(ValidationComplexClassConstraint constraintAnnotation) {
99 length = constraintAnnotation.value();
1010 }
1111
12 public boolean isValid(ValidationComplexResourceWithClassConstraint value, ConstraintValidatorContext context) {
13 return value.s.length() + value.t.length() >= length;
12 public boolean isValid(ValidationComplexResourceWithClassConstraintInterface value, ConstraintValidatorContext context) {
13 return value.getS().length() + value.getT().length() >= length;
1414 }
1515
1616 }
66
77 @Path("/{s}/{t}")
88 @ValidationComplexClassConstraint(5)
9 public class ValidationComplexResourceWithClassConstraint {
9 public class ValidationComplexResourceWithClassConstraint implements ValidationComplexResourceWithClassConstraintInterface {
1010 @NotNull
1111 public String s;
1212 @NotNull
2424 public String toString() {
2525 return "ValidationComplexResourceWithClassConstraint(\"" + s + "\", \"" + t + "\")";
2626 }
27
28 @Override
29 public String getS() {
30 return s;
31 }
32
33 @Override
34 public String getT() {
35 return t;
36 }
2737 }
0 package org.jboss.resteasy.test.validation.resource;
1
2 public interface ValidationComplexResourceWithClassConstraintInterface {
3
4 public String getS();
5 public String getT();
6
7 }
1313 @Target({FIELD, METHOD, PARAMETER, TYPE})
1414 @Retention(RUNTIME)
1515 public @interface ValidationExceptionCrazyConstraint {
16 String message() default "a[][]][][b";
16
17 String DEFAULT_MESSAGE="a[][]][][b";
18
19 String message() default DEFAULT_MESSAGE;
1720
1821 Class<?>[] groups() default {};
1922
0 package org.jboss.resteasy.test.validation.resource;
1
2 import javax.validation.ValidationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.Response;
5 import javax.ws.rs.core.Response.ResponseBuilder;
6 import javax.ws.rs.core.Response.Status;
7 import javax.ws.rs.ext.ExceptionMapper;
8
9 import org.jboss.resteasy.api.validation.Validation;
10
11 /**
12 *
13 * @author Nicolas NESMON
14 *
15 */
16 public abstract class ValidationExceptionMapper<T extends ValidationException> implements ExceptionMapper<T> {
17
18 @Override
19 public Response toResponse(T validationException) {
20 ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR)
21 .entity(getClass().getName() + ":" + validationException.getMessage());
22 builder.type(MediaType.TEXT_PLAIN);
23 builder.header(Validation.VALIDATION_HEADER, "true");
24 return builder.build();
25 }
26
27 }
00 package org.jboss.resteasy.test.validation.resource;
11
2 import javax.validation.ConstraintDefinitionException;
23 import javax.ws.rs.POST;
34 import javax.ws.rs.Path;
5 import javax.ws.rs.ext.Provider;
46
57 @Path("/")
68 @ValidationExceptionIncorrectConstraint
79 public class ValidationExceptionResourceWithIncorrectConstraint {
10
11 @Provider
12 public static class ConstraintDefinitionExceptionMapper extends ValidationExceptionMapper<ConstraintDefinitionException> {
13 }
14
815 @POST
916 public void test() {
1017 }
00 package org.jboss.resteasy.test.validation.resource;
11
2 import javax.validation.GroupDefinitionException;
23 import javax.validation.GroupSequence;
34 import javax.ws.rs.GET;
45 import javax.ws.rs.Path;
6 import javax.ws.rs.ext.Provider;
57
68 @Path("/")
79 @GroupSequence({ValidationExceptionTestGroup1.class, ValidationExceptionTestGroup2.class})
810 public class ValidationExceptionResourceWithInvalidConstraintGroup {
11
12 @Provider
13 public static class GroupDefinitionExceptionMapper extends ValidationExceptionMapper<GroupDefinitionException> {
14 }
15
916 private String s;
1017
1118 @GET
00 package org.jboss.resteasy.test.validation.resource;
11
2 import javax.validation.ConstraintDeclarationException;
23 import javax.validation.constraints.Size;
34 import javax.ws.rs.POST;
45 import javax.ws.rs.Path;
6 import javax.ws.rs.ext.Provider;
57
68 @Path("/")
79 public class ValidationExceptionSubResourceWithInvalidOverride extends ValidationExceptionSuperResource {
10
11 @Provider
12 public static class ConstraintDeclarationExceptionMapper extends ValidationExceptionMapper<ConstraintDeclarationException> {
13 }
14
815 @POST
916 public void test(@Size(max = 3) String s) {
1017 }
0 package org.jboss.resteasy.test.warning;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.core.interceptors.resource.TestResource1;
6 import org.jboss.resteasy.test.core.interceptors.resource.TestResource2;
7 import org.jboss.resteasy.test.core.interceptors.resource.TestSubResource;
8 import org.jboss.resteasy.test.warning.resource.SubResourceWarningResource;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.AfterClass;
13 import org.junit.Assert;
14 import org.junit.BeforeClass;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17 import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
18
19 /**
20 * @tpSubChapter Miscellaneous
21 * @tpChapter Integration tests
22 * @tpSince RESTEasy 3.5
23 * Created by rsearls on 9/11/17.
24 */
25 @RunWith(Arquillian.class)
26 @RunAsClient
27 public class SubResourceWarningTest {
28
29 private static int base = TestUtil.getWarningCount("have the same path, [test", false);
30
31 @Deployment
32 public static Archive<?> deploySimpleResource() {
33 WebArchive war = TestUtil.prepareArchive(SubResourceWarningTest.class.getSimpleName());
34 return TestUtil.finishContainerPrepare(war, null, SubResourceWarningResource.class,
35 TestResource1.class, TestResource2.class, TestSubResource.class);
36 }
37 @BeforeClass
38 public static void initLogging() throws Exception {
39 OnlineManagementClient client = TestUtil.clientInit();
40 TestUtil.runCmd(client, "/subsystem=logging/logger=org.jboss.resteasy:add(level=WARN)");
41 client.close();
42 }
43
44 @AfterClass
45 public static void removeLogging() throws Exception {
46 OnlineManagementClient client = TestUtil.clientInit();
47 TestUtil.runCmd(client, "/subsystem=logging/logger=org.jboss.resteasy:remove()");
48 client.close();
49 }
50
51 /**
52 * Confirms that 2 warning messages about this incorrect coding is printed to the server.log
53 * Must check for path because warning text, RESTEASY002195, exist in log for a previous test
54 * in the suite.
55 * @throws Exception
56 */
57 @Test
58 public void testWarningMsg () throws Exception {
59 int cnt = TestUtil.getWarningCount("have the same path, [test", false);
60 Assert.assertEquals( "Improper log WARNING count",cnt - base, 2);
61 }
62 }
0 package org.jboss.resteasy.test.warning.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5
6 /**
7 * Created by rsearls on 9/11/17.
8 */
9 @Path("test")
10 public class SubResourceWarningResource {
11
12 @GET
13 @Path("get")
14 public Response getCookie() {
15 TestSubResource sr = new TestSubResource();
16 return Response.ok().entity(sr).build();
17 }
18
19 @Path("get")
20 public String testString() {
21 return "My test sub-locator.";
22 }
23
24 }
0 package org.jboss.resteasy.test.warning.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5 import javax.ws.rs.Produces;
6
7 /**
8 * Created by rsearls on 9/5/17.
9 */
10 @Path("test")
11 public class TestResource1 {
12
13 @GET
14 @Path("x")
15 @Produces("text/plain")
16 public Response method() {
17 return Response.ok("ok").build();
18 }
19 }
0 package org.jboss.resteasy.test.warning.resource;
1
2 import org.jboss.resteasy.test.core.interceptors.resource.TestSubResource;
3
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6
7 /**
8 * Created by rsearls on 9/5/17.
9 */
10 @Path("test")
11 public class TestResource2 {
12
13 @Path("x")
14 @Produces("text/plain")
15 public TestSubResource locator() {
16 return new TestSubResource();
17 }
18 }
0 package org.jboss.resteasy.test.warning.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;
4
5 /**
6 * Created by rsearls on 9/5/17.
7 */
8 public class TestSubResource {
9
10 @POST
11 @Path("")
12 public String sub(String s) {
13 return "sub(" + s + ")";
14 }
15 }
370370 * @tpTestDetails "resteasy.document.secure.processing.feature" is set to default value
371371 * "resteasy.document.secure.disableDTDs" is set to true
372372 * "resteasy.document.expand.entity.references" is set to true
373 * @tpSince RESTEasy 3.1.0
373 * @tpInfo RESTEASY-1485
374 * @tpSince RESTEasy 3.0.20.Final
374375 */
375376 @Test
376377 @Category({NotForForwardCompatibility.class})
386386 * @tpTestDetails "resteasy.document.secure.processing.feature" is set to true
387387 * "resteasy.document.secure.disableDTDs" is set to true
388388 * "resteasy.document.expand.entity.references" is set to true
389 * @tpSince RESTEasy 3.1.0
389 * @tpInfo RESTEASY-1485
390 * @tpSince RESTEasy 3.0.20.Final
390391 */
391392 @Test
392393 @Category({NotForForwardCompatibility.class})
2929 })
3030 public class FavoriteMovie {
3131
32 @XmlElement(required = true)
32 @XmlElement(required = true, namespace = "http://abc.com")
3333 protected String title;
3434
3535 /**
66 <container qualifier="jbossas-managed" default="true">
77 <configuration>
88 <property name="jbossHome">${jboss.home}</property>
9 <property name="jbossArguments">${securityManagerArg}</property>
910 <property name="serverConfig">${jboss.server.config.file.name:standalone-full.xml}</property>
1011 <!--<property name="javaVmArguments">-Xmx512m -XX:MaxPermSize=128m
1112 -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y
1213 </property>-->
13 <property name="javaVmArguments">-server -Xms256m -Xmx1G -Djboss.bind.address=${node} -Djboss.bind.address.management=${node} -Dnode=${node} -Dipv6=${ipv6} ${additionalJvmArgs} ${ipv6ArquillianSettings} ${jacoco.agent}</property>
14 <property name="javaVmArguments">-server -Xms256m -Xmx1G -Djboss.bind.address=${node} -Djboss.bind.address.management=${node} -Dnode=${node} -Dipv6=${ipv6} ${additionalJvmArgs} ${ipv6ArquillianSettings} ${jacoco.agent} -Dee8.preview.mode=${ee8.preview.mode}</property>
1415 <property name="managementAddress">${node}</property>
1516 </configuration>
1617 </container>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <jboss-deployment-structure>
2 <deployment>
3 <dependencies>
4 <module name="org.jboss.resteasy.resteasy-json-binding-provider" services="import"/>
5 </dependencies>
6 </deployment>
7 </jboss-deployment-structure>
0 org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter
1 org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor
2 org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor
0 org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter
1 org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor
2 org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor
0 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
3 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
4 metadata-complete="false"
5 version="3.1">
6
7 </web-app>
0 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
3
4 <display-name>sse</display-name>
5 <welcome-file-list>
6 <welcome-file>index.html</welcome-file>
7 </welcome-file-list>
8 <servlet>
9 <servlet-name>sse</servlet-name>
10
11 <servlet-class>
12 org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher
13 </servlet-class>
14 <init-param>
15 <param-name>javax.ws.rs.Application</param-name>
16 <param-value>org.jboss.resteasy.test.providers.sse.SseFilterApplication</param-value>
17 </init-param>
18 <init-param>
19 <param-name>resteasy.servlet.mapping.prefix</param-name>
20 <param-value>/service</param-value>
21 </init-param>
22 <async-supported>true</async-supported>
23 </servlet>
24
25 <servlet-mapping>
26 <servlet-name>sse</servlet-name>
27 <url-pattern>/service/*</url-pattern>
28 </servlet-mapping>
29
30 </web-app>
0 <!DOCTYPE html>
1 <html>
2 <head>
3 <title>HTML5 SSE Examples</title>
4 <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.3.min.js"></script>
5 <script src="https://code.highcharts.com/highcharts.js"></script>
6
7 </head>
8
9 <body>
10 <div id="content">
11 <div id="chart">
12 </div>
13 </div>
14 </body>
15 </html>
16
17 <script type="text/javascript">
18 var chart = new Highcharts.Chart({
19 chart: {
20 renderTo: 'chart',
21 defaultSeriesType: 'spline'
22 },
23 title: {
24 text: 'GreenHouse Status'
25 },
26 xAxis: {
27 type: 'datetime'
28 },
29 series: [{
30 name: "Temperature",
31 data: []
32 },
33 {
34 name: "Humidity",
35 data: [],
36 color: '#00ff00'
37 }
38 ]
39 });
40
41 if( !!window.EventSource ) {
42 var event = new EventSource("http://localhost:8080/resteasy-sse/service/server-sent-events/sse/1");
43
44 event.addEventListener('message', function( event ) {
45 var datapoint = jQuery.parseJSON( event.data );
46
47 chart.series[ 0 ].addPoint({
48 x: datapoint.timestamp,
49 y: datapoint.tempe
50 }, true, chart.series[ 0 ].data.length >= 50 );
51 chart.series[ 1 ].addPoint({
52 x: datapoint.timestamp,
53 y: datapoint.humid
54 }, true, chart.series[ 0 ].data.length >= 50 )
55 } );
56
57 $('#content').bind('unload',function() {
58 event.close();
59 });
60 }
61 </script>
0 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
3
4 <servlet>
5 <servlet-name>sse</servlet-name>
6
7 <servlet-class>
8 org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
9 </servlet-class>
10 <init-param>
11 <param-name>javax.ws.rs.Application</param-name>
12 <param-value>org.jboss.resteasy.test.providers.sse.SsePostResourceMethodInvokerApplication</param-value>
13 </init-param>
14 <init-param>
15 <param-name>resteasy.servlet.mapping.prefix</param-name>
16 <param-value>/</param-value>
17 </init-param>
18 </servlet>
19
20 <servlet-mapping>
21 <servlet-name>sse</servlet-name>
22 <url-pattern>/*</url-pattern>
23 </servlet-mapping>
24
25 </web-app>
0 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
3
4 <display-name>sse</display-name>
5 <welcome-file-list>
6 <welcome-file>index.html</welcome-file>
7 </welcome-file-list>
8 <servlet>
9 <servlet-name>sse</servlet-name>
10
11 <servlet-class>
12 org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher
13 </servlet-class>
14 <init-param>
15 <param-name>javax.ws.rs.Application</param-name>
16 <param-value>org.jboss.resteasy.test.providers.sse.SseApplication</param-value>
17 </init-param>
18 <init-param>
19 <param-name>resteasy.servlet.mapping.prefix</param-name>
20 <param-value>/service</param-value>
21 </init-param>
22 <async-supported>true</async-supported>
23 </servlet>
24
25 <servlet-mapping>
26 <servlet-name>sse</servlet-name>
27 <url-pattern>/service/*</url-pattern>
28 </servlet-mapping>
29
30 </web-app>
66 <parent>
77 <groupId>org.jboss.resteasy</groupId>
88 <artifactId>resteasy-integration-tests-spring</artifactId>
9 <version>3.1.4.Final</version>
9 <version>3.5.0.Final</version>
1010 <relativePath>../pom.xml</relativePath>
1111 </parent>
1212
00 package org.jboss.resteasy.test.spring.deployment;
11
22 import java.io.File;
3 import java.io.FilePermission;
34 import java.io.IOException;
5 import java.lang.reflect.ReflectPermission;
46 import java.nio.charset.StandardCharsets;
7 import java.security.SecurityPermission;
8 import java.util.PropertyPermission;
9 import java.util.logging.LoggingPermission;
510
611 import org.apache.http.HttpEntity;
712 import org.apache.http.client.methods.CloseableHttpResponse;
1823 import org.jboss.arquillian.junit.Arquillian;
1924 import org.jboss.resteasy.plugins.spring.SpringContextLoaderListener;
2025 import org.jboss.resteasy.test.spring.deployment.resource.TestResource;
26 import org.jboss.resteasy.utils.PermissionUtil;
2127 import org.jboss.resteasy.utils.PortProviderUtil;
2228 import org.jboss.resteasy.utils.TestUtil;
2329 import org.jboss.resteasy.utils.TestUtilSpring;
7682 .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/web.xml", "web.xml")
7783 .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/mvc-dispatcher-servlet.xml", "mvc-dispatcher-servlet.xml")
7884 .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/applicationContext.xml", "applicationContext.xml");
85
86 // PropertyPermission needed for "arquillian.debug" to run
87 // remaining permissions needed to run springframework
88 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
89 //new PropertyPermission("arquillian.*", "read"),
90 new ReflectPermission("suppressAccessChecks"),
91 new RuntimePermission("accessDeclaredMembers"),
92 new RuntimePermission("getClassLoader"),
93 new FilePermission("<<ALL FILES>>", "read"),
94 new LoggingPermission("control", "")
95 ), "permissions.xml");
96
7997 TestUtilSpring.addSpringLibraries(archive);
8098 archive.as(ZipExporter.class).exportTo(new File("target", deploymentWithSpringMvcDispatcherSpringIncluded + ".war"), true);
8199 return archive;
102120 .addClass(TestResource.class)
103121 .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "web.xml", "web.xml")
104122 .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "applicationContext.xml", "applicationContext.xml");
123
124 // remaining permissions needed to run springframework
125 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
126 new RuntimePermission("accessDeclaredMembers"),
127 new FilePermission("<<ALL FILES>>", "read"),
128 new LoggingPermission("control", "")
129 ), "permissions.xml");
130
105131 TestUtilSpring.addSpringLibraries(archive);
106132 archive.as(ZipExporter.class).exportTo(new File("target", deploymentWithSpringContextLoaderListenerSpringIncluded + ".war"), true);
107133 return archive;
129155 WebArchive archive = TestUtil.prepareArchive(deploymentWithoutSpringMvcDispatcherOrListenerSpringIncluded);
130156 archive.addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "web-no-mvc-no-listener.xml", "web.xml")
131157 .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "applicationContext.xml", "applicationContext.xml");
158
132159 TestUtilSpring.addSpringLibraries(archive);
133160 archive.as(ZipExporter.class).exportTo(new File("target", deploymentWithoutSpringMvcDispatcherOrListenerSpringIncluded + ".war"), true);
134161 return TestUtil.finishContainerPrepare(archive, null, TestResource.class);
177204 Assert.assertEquals("The server resource didn't send correct response", TestResource.TEST_RESPONSE, responseString);
178205 httpget.releaseConnection();
179206 }
180
181 /* private static void addSpringLibraries(WebArchive archive, String springVersion) {
182 if (springDependenciesInDeployment()) {
183 archive.addAsLibraries(resolveSpringDependencies(springVersion));
184 } else {
185 // you need to use the 'meta-inf' attribute to import the contents of meta-inf so spring can find the correct namespace handlers
186 if (isDefinedSystemProperty("use-jboss-deployment-structure")) {
187 archive.addAsManifestResource("jboss-deployment-structure.xml");
188 } else {
189 archive.addAsManifestResource(new StringAsset("Dependencies: org.springframework.spring meta-inf\n"), "MANIFEST.MF");
190 }
191 }
192 }
193
194 private static File[] resolveSpringDependencies(String springVersion) {
195 MavenUtil mavenUtil;
196 mavenUtil = MavenUtil.create(true);
197 List<File> runtimeDependencies = new ArrayList<>();
198
199 try {
200 runtimeDependencies.addAll(mavenUtil.createMavenGavRecursiveFiles("org.springframework:spring-core:" + springVersion));
201 runtimeDependencies.addAll(mavenUtil.createMavenGavRecursiveFiles("org.springframework:spring-web:" + springVersion));
202 runtimeDependencies.addAll(mavenUtil.createMavenGavRecursiveFiles("org.springframework:spring-webmvc:" + springVersion));
203 } catch (Exception e) {
204 throw new RuntimeException("Unable to get artifacts from maven via Aether library", e);
205 }
206
207 File[] dependencies = runtimeDependencies.toArray(new File []{});
208 return dependencies;
209 }
210
211 private static boolean springDependenciesInDeployment() {
212 return true;
213 }
214
215 private static String getSpringVersion() {
216 return readSystemProperty("version.org.springframework", defaultSpringVersion);
217 }
218
219 private static String readSystemProperty(String name, String defaultValue) {
220 String value = System.getProperty(name);
221 return (value == null) ? defaultValue : value;
222 }
223
224 private static boolean isDefinedSystemProperty(String name) {
225 String value = System.getProperty(name);
226 return (value != null);
227 }*/
228
229207 }
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
55 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.annotations.ClientURI;
6 import org.jboss.resteasy.client.ClientURI;
77 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
88 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
99 import org.jboss.resteasy.test.spring.deployment.resource.Contact;
1111 import org.jboss.resteasy.test.spring.deployment.resource.Contacts;
1212 import org.jboss.resteasy.test.spring.deployment.resource.ContactsResource;
1313 import org.jboss.resteasy.util.HttpHeaderNames;
14 import org.jboss.resteasy.utils.PermissionUtil;
1415 import org.jboss.resteasy.utils.PortProviderUtil;
1516 import org.jboss.resteasy.utils.TestUtilSpring;
1617 import org.jboss.shrinkwrap.api.Archive;
2021 import org.junit.Test;
2122 import org.junit.runner.RunWith;
2223
24 import javax.management.MBeanPermission;
25 import javax.management.MBeanServerPermission;
26 import javax.management.MBeanTrustPermission;
2327 import javax.ws.rs.Consumes;
2428 import javax.ws.rs.GET;
2529 import javax.ws.rs.POST;
2731 import javax.ws.rs.Produces;
2832 import javax.ws.rs.core.MediaType;
2933 import javax.ws.rs.core.Response;
34 import java.io.FilePermission;
35 import java.lang.reflect.ReflectPermission;
36 import java.util.PropertyPermission;
37 import java.util.logging.LoggingPermission;
3038
3139 /**
3240 * @tpSubChapter Spring
6775 .addClass(ContactsDependenciesInDeploymentTest.class)
6876 .addAsWebInfResource(ContactsDependenciesInDeploymentTest.class.getPackage(), "contacts/web.xml", "web.xml")
6977 .addAsWebInfResource(ContactsDependenciesInDeploymentTest.class.getPackage(), "contacts/springmvc-servlet.xml", "springmvc-servlet.xml");
78
79 // spring specific permissions needed.
80 // Permission accessClassInPackage.sun.reflect.annotation is required in order
81 // for spring to introspect annotations. Security exception is eaten by spring
82 // and not posted via the server.
83 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
84 new MBeanServerPermission("createMBeanServer"),
85 new MBeanPermission("org.springframework.context.support.LiveBeansView#-[liveBeansView:application=/ContactsDependenciesInDeploymentTest]", "registerMBean,unregisterMBean"),
86 new MBeanTrustPermission("register"),
87 new PropertyPermission("spring.liveBeansView.mbeanDomain", "read"),
88 new RuntimePermission("getenv.spring.liveBeansView.mbeanDomain"),
89 new ReflectPermission("suppressAccessChecks"),
90 new RuntimePermission("accessDeclaredMembers"),
91 new RuntimePermission("getClassLoader"),
92 new RuntimePermission("accessClassInPackage.sun.reflect.annotation"),
93 new FilePermission("<<ALL FILES>>", "read"),
94 new LoggingPermission("control", "")
95 ), "permissions.xml");
96
7097 TestUtilSpring.addSpringLibraries(archive);
7198 return archive;
7299 }
55 import org.jboss.resteasy.category.NotForWildFly9;
66 import org.jboss.resteasy.test.spring.deployment.resource.ContextRefreshResource;
77 import org.jboss.resteasy.test.spring.deployment.resource.ContextRefreshTrigger;
8 import org.jboss.resteasy.utils.PermissionUtil;
89 import org.jboss.resteasy.utils.TestUtilSpring;
910 import org.jboss.shrinkwrap.api.Archive;
1011 import org.jboss.shrinkwrap.api.ShrinkWrap;
1415 import org.junit.experimental.categories.Category;
1516 import org.junit.runner.RunWith;
1617 import org.springframework.web.context.WebApplicationContext;
18
19 import java.io.FilePermission;
20 import java.lang.reflect.ReflectPermission;
1721 import java.util.Enumeration;
22 import java.util.PropertyPermission;
23 import java.util.logging.LoggingPermission;
1824
1925
2026 /**
3945 .addClass(NotForWildFly9.class) //required as this test is not @RunAsClient annotated
4046 .addAsWebInfResource(ContextRefreshDependenciesInDeploymentTest.class.getPackage(), "web.xml", "web.xml")
4147 .addAsWebInfResource(ContextRefreshDependenciesInDeploymentTest.class.getPackage(), "contextRefresh/applicationContext.xml", "applicationContext.xml");
48
49 // PropertyPermission for test to run in arquillian
50 // remaining permissions needed to run springframework
51 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
52 new PropertyPermission("arquillian.*", "read"),
53 new ReflectPermission("suppressAccessChecks"),
54 new RuntimePermission("accessDeclaredMembers"),
55 new RuntimePermission("getClassLoader"),
56 new FilePermission("<<ALL FILES>>", "read"),
57 new LoggingPermission("control", "")
58 ), "permissions.xml");
59
4260 TestUtilSpring.addSpringLibraries(archive);
4361 return archive;
4462 }
77 import org.jboss.resteasy.test.spring.deployment.resource.JavaConfigResource;
88 import org.jboss.resteasy.test.spring.deployment.resource.JavaConfigService;
99 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PermissionUtil;
1011 import org.jboss.resteasy.utils.PortProviderUtil;
1112 import org.jboss.resteasy.utils.TestUtilSpring;
1213 import org.jboss.shrinkwrap.api.Archive;
1920 import javax.ws.rs.client.Client;
2021 import javax.ws.rs.client.WebTarget;
2122 import javax.ws.rs.core.Response;
23 import java.io.FilePermission;
24 import java.lang.reflect.ReflectPermission;
25 import java.util.PropertyPermission;
26 import java.util.logging.LoggingPermission;
2227
2328 /**
2429 * @tpSubChapter Spring
4449 .addClass(JavaConfigService.class)
4550 .addClass(JavaConfigBeanConfiguration.class)
4651 .addAsWebInfResource(JavaConfigDependenciesInDeploymentTest.class.getPackage(), "javaConfig/web.xml", "web.xml");
52
53 // Permission needed for "arquillian.debug" to run
54 // "suppressAccessChecks" required for access to arquillian-core.jar
55 // remaining permissions needed to run springframework
56 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
57 new PropertyPermission("arquillian.*", "read"),
58 new PropertyPermission("cglib.debugLocation", "read"),
59 new RuntimePermission("accessClassInPackage.sun.reflect.annotation"),
60 new RuntimePermission("getProtectionDomain"),
61 new ReflectPermission("suppressAccessChecks"),
62 new RuntimePermission("accessDeclaredMembers"),
63 new RuntimePermission("getClassLoader"),
64 new FilePermission("<<ALL FILES>>", "read"),
65 new LoggingPermission("control", "")
66 ), "permissions.xml");
67
4768 TestUtilSpring.addSpringLibraries(archive);
4869 return archive;
4970 }
00 package org.jboss.resteasy.test.spring.deployment;
11
2 import java.security.AllPermission;
23 import javax.json.JsonArray;
34
5 import javax.xml.ws.WebServicePermission;
46 import org.apache.http.HttpEntity;
57 import org.apache.http.util.EntityUtils;
68 import org.jboss.arquillian.container.test.api.Deployment;
1012 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
1113 import org.jboss.resteasy.test.spring.deployment.resource.*;
1214 import org.jboss.resteasy.util.HttpResponseCodes;
15 import org.jboss.resteasy.utils.PermissionUtil;
1316 import org.jboss.resteasy.utils.PortProviderUtil;
1417 import org.jboss.resteasy.utils.TestUtilSpring;
1518 import org.jboss.shrinkwrap.api.Archive;
2023 import org.junit.Before;
2124 import org.junit.Test;
2225 import org.junit.runner.RunWith;
26
27 import javax.management.MBeanPermission;
28 import javax.management.MBeanServerPermission;
29 import javax.management.MBeanTrustPermission;
2330 import javax.ws.rs.client.Entity;
2431 import javax.ws.rs.client.WebTarget;
2532 import javax.ws.rs.core.Response;
33 import java.io.FilePermission;
34 import java.lang.reflect.ReflectPermission;
2635 import java.nio.ByteBuffer;
2736 import java.nio.charset.Charset;
2837 import java.nio.charset.StandardCharsets;
38 import java.util.PropertyPermission;
39 import java.util.logging.LoggingPermission;
2940
3041 /**
3142 * Test that springframework MVC works in conjuction with jaxrs Application subclass.
4960 archive.addClass(Greeting.class);
5061 archive.addClass(NumbersResource.class);
5162 archive.addClass(JaxrsApplication.class);
63
64 // spring specific permissions needed.
65 // Permission accessClassInPackage.sun.reflect.annotation is required in order
66 // for spring to introspect annotations. Security exception is eaten by spring
67 // and not posted via the server.
68 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
69 new MBeanServerPermission("createMBeanServer"),
70 new MBeanPermission("org.springframework.context.support.LiveBeansView#-[liveBeansView:application=/JaxrsWithSpringMVCTest]", "registerMBean,unregisterMBean"),
71 new MBeanTrustPermission("register"),
72 new PropertyPermission("spring.liveBeansView.mbeanDomain", "read"),
73 new RuntimePermission("getenv.spring.liveBeansView.mbeanDomain"),
74 new ReflectPermission("suppressAccessChecks"),
75 new RuntimePermission("accessDeclaredMembers"),
76 new RuntimePermission("getClassLoader"),
77 new RuntimePermission("accessClassInPackage.sun.reflect.annotation"),
78 new FilePermission("<<ALL FILES>>", "read"),
79 new LoggingPermission("control", "")
80 ), "permissions.xml");
81
5282 TestUtilSpring.addSpringLibraries(archive);
5383 return archive;
5484 }
1111 import org.jboss.resteasy.test.spring.deployment.resource.RequestScopedBeanBean;
1212 import org.jboss.resteasy.test.spring.deployment.resource.RequestScopedBeanTestBeanResource;
1313 import org.jboss.resteasy.test.spring.deployment.resource.RequestScopedBeanBeanFactoryBean;
14 import org.jboss.resteasy.utils.PermissionUtil;
1415 import org.jboss.resteasy.utils.PortProviderUtil;
1516 import org.jboss.resteasy.utils.TestUtilSpring;
1617 import org.jboss.shrinkwrap.api.Archive;
2324 import javax.ws.rs.client.WebTarget;
2425 import javax.ws.rs.core.MediaType;
2526 import javax.ws.rs.core.Response;
27
28 import java.io.FilePermission;
29 import java.lang.reflect.ReflectPermission;
30 import java.util.PropertyPermission;
31 import java.util.logging.LoggingPermission;
2632
2733 import static org.junit.Assert.assertEquals;
2834
4955 archive.addClass(RequestScopedBeanBean.class);
5056 archive.addClass(RequestScopedBeanTestBeanResource.class);
5157 archive.addClass(RequestScopedBeanBeanFactoryBean.class);
58
59 // Permission needed for "arquillian.debug" to run
60 // "suppressAccessChecks" required for access to arquillian-core.jar
61 // remaining permissions needed to run springframework
62 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
63 new PropertyPermission("arquillian.*", "read"),
64 new ReflectPermission("suppressAccessChecks"),
65 new RuntimePermission("accessDeclaredMembers"),
66 new RuntimePermission("getClassLoader"),
67 new FilePermission("<<ALL FILES>>", "read"),
68 new LoggingPermission("control", "")
69 ), "permissions.xml");
70
5271 TestUtilSpring.addSpringLibraries(archive);
5372 return archive;
5473 }
1818 import org.jboss.resteasy.test.spring.deployment.resource.SpringBeanProcessorMyResource;
1919 import org.jboss.resteasy.test.spring.deployment.resource.SpringBeanProcessorMyWriter;
2020 import org.jboss.resteasy.test.spring.deployment.resource.SpringBeanProcessorResourceConfiguration;
21 import org.jboss.resteasy.test.spring.deployment.resource.SpringBeanProcessorCustomerParamConverter;
22 import org.jboss.resteasy.test.spring.deployment.resource.SpringBeanProcessorCustomerParamConverterProvider;
21 import org.jboss.resteasy.test.spring.deployment.resource.SpringBeanProcessorCustomerStringConverter;
2322 import org.jboss.resteasy.test.spring.deployment.resource.SpringBeanProcessorScannedResource;
2423 import org.jboss.resteasy.util.HttpResponseCodes;
24 import org.jboss.resteasy.utils.PermissionUtil;
2525 import org.jboss.resteasy.utils.PortProviderUtil;
2626 import org.jboss.resteasy.utils.TestUtil;
2727 import org.jboss.resteasy.utils.TestUtilSpring;
3636
3737 import javax.ws.rs.client.WebTarget;
3838 import javax.ws.rs.core.Response;
39 import java.io.FilePermission;
40 import java.lang.reflect.ReflectPermission;
41 import java.util.PropertyPermission;
42 import java.util.logging.LoggingPermission;
3943
4044 /**
4145 * @tpSubChapter Spring
8589 archive.addClass(SpringBeanProcessorMyResource.class);
8690 archive.addClass(SpringBeanProcessorMyWriter.class);
8791 archive.addClass(SpringBeanProcessorResourceConfiguration.class);
88 archive.addClass(SpringBeanProcessorCustomerParamConverter.class);
89 archive.addClass(SpringBeanProcessorCustomerParamConverterProvider.class);
92 archive.addClass(SpringBeanProcessorCustomerStringConverter.class);
9093 archive.addClass(SpringBeanProcessorScannedResource.class);
94
95 // Permission needed for "arquillian.debug" to run
96 // "suppressAccessChecks" required for access to arquillian-core.jar
97 // remaining permissions needed to run springframework
98 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
99 new PropertyPermission("arquillian.*", "read"),
100 new PropertyPermission("cglib.debugLocation", "read"),
101 new RuntimePermission("getProtectionDomain"),
102 new RuntimePermission("accessClassInPackage.sun.reflect.annotation"),
103 new ReflectPermission("suppressAccessChecks"),
104 new RuntimePermission("accessDeclaredMembers"),
105 new RuntimePermission("getClassLoader"),
106 new FilePermission("<<ALL FILES>>", "read"),
107 new LoggingPermission("control", "")
108 ), "permissions.xml");
109
91110 TestUtilSpring.addSpringLibraries(archive);
92111 TestUtil.addOtherLibrary(archive, "aopalliance:aopalliance:" + System.getProperty("version.aopalliance", "1.0"));
93112 return archive;
77 import org.jboss.resteasy.test.spring.deployment.resource.SpringLocatingLocatingResource;
88 import org.jboss.resteasy.test.spring.deployment.resource.SpringLocatingSimpleResource;
99 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PermissionUtil;
1011 import org.jboss.resteasy.utils.PortProviderUtil;
1112 import org.jboss.resteasy.utils.TestUtilSpring;
1213 import org.jboss.shrinkwrap.api.Archive;
2021 import javax.ws.rs.client.Entity;
2122 import javax.ws.rs.client.WebTarget;
2223 import javax.ws.rs.core.Response;
24 import java.io.FilePermission;
25 import java.lang.reflect.ReflectPermission;
26 import java.util.PropertyPermission;
27 import java.util.logging.LoggingPermission;
2328
2429 /**
2530 * @tpSubChapter Spring
4045 "springLocatingResource/applicationContext.xml", "applicationContext.xml");
4146 archive.addClass(SpringLocatingLocatingResource.class);
4247 archive.addClass(SpringLocatingSimpleResource.class);
48
49 // Permission needed for "arquillian.debug" to run
50 // "suppressAccessChecks" required for access to arquillian-core.jar
51 // remaining permissions needed to run springframework
52 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
53 new PropertyPermission("arquillian.*", "read"),
54 new ReflectPermission("suppressAccessChecks"),
55 new RuntimePermission("accessDeclaredMembers"),
56 new RuntimePermission("getClassLoader"),
57 new FilePermission("<<ALL FILES>>", "read"),
58 new LoggingPermission("control", "")
59 ), "permissions.xml");
60
4361 TestUtilSpring.addSpringLibraries(archive);
4462 return archive;
4563 }
33 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
44 import org.jboss.resteasy.test.spring.deployment.resource.SpringWebappContextResource;
55 import org.jboss.resteasy.util.HttpResponseCodes;
6 import org.jboss.resteasy.utils.PermissionUtil;
67 import org.jboss.resteasy.utils.TestUtilSpring;
78 import org.jboss.shrinkwrap.api.ShrinkWrap;
89 import org.junit.Assert;
1718 import javax.ws.rs.client.Client;
1819 import javax.ws.rs.client.WebTarget;
1920 import javax.ws.rs.core.Response;
21 import java.io.FilePermission;
22 import java.lang.reflect.ReflectPermission;
2023 import java.util.HashMap;
2124 import java.util.Map;
25 import java.util.PropertyPermission;
26 import java.util.logging.LoggingPermission;
2227
2328 /**
2429 * @tpSubChapter Spring
4247 .addClass(SpringWebappContextResource.class)
4348 .addAsWebInfResource(SpringWebappContextDependenciesInDeploymentTest.class.getPackage(), "web.xml", "web.xml")
4449 .addAsWebInfResource(SpringWebappContextDependenciesInDeploymentTest.class.getPackage(), "springWebAppContext/applicationContext.xml", "applicationContext.xml");
50
51 // Permission needed for "arquillian.debug" to run
52 // "suppressAccessChecks" required for access to arquillian-core.jar
53 // remaining permissions needed to run springframework
54 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
55 new PropertyPermission("arquillian.*", "read"),
56 new ReflectPermission("suppressAccessChecks"),
57 new RuntimePermission("accessDeclaredMembers"),
58 new RuntimePermission("getClassLoader"),
59 new FilePermission("<<ALL FILES>>", "read"),
60 new LoggingPermission("control", "")
61 ), "permissions.xml");
62
4563 TestUtilSpring.addSpringLibraries(archive);
4664 return archive;
4765 }
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.category.ExpectedFailing;
65 import org.jboss.resteasy.category.NotForForwardCompatibility;
76 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
87 import org.jboss.resteasy.test.spring.deployment.resource.TypeMappingResource;
98 import org.jboss.resteasy.util.HttpResponseCodes;
109 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
1210 import org.jboss.resteasy.utils.TestUtilSpring;
1311 import org.jboss.shrinkwrap.api.Archive;
1412 import org.jboss.shrinkwrap.api.ShrinkWrap;
00 package org.jboss.resteasy.test.spring.deployment.resource;
11
2 import java.util.stream.Stream;
32 import javax.json.Json;
43 import javax.json.JsonArray;
54 import javax.json.JsonArrayBuilder;
1817 @Path("numbers")
1918 public class NumbersResource {
2019
21 @GET
22 @Produces("application/json")
23 public JsonArray numbers() {
24 JsonArrayBuilder array = Json.createArrayBuilder();
25 Stream<String> numberStream = Stream.generate(System::currentTimeMillis)
26 .map(String::valueOf)
27 .limit(10);
28 numberStream.forEach(array::add);
29 return array.build();
20 @GET
21 @Produces("application/json")
22 public JsonArray numbers()
23 {
24 JsonArrayBuilder array = Json.createArrayBuilder();
25 for (int i = 0; i < 10; i++)
26 {
27 array.add(String.valueOf(System.currentTimeMillis()));
28 }
29 return array.build();
3030
31 }
31 }
3232
3333 }
3434
+0
-26
testsuite/integration-tests-spring/deployment/src/test/java/org/jboss/resteasy/test/spring/deployment/resource/SpringBeanProcessorCustomerParamConverter.java less more
0 package org.jboss.resteasy.test.spring.deployment.resource;
1
2 import org.springframework.beans.factory.annotation.Autowired;
3
4 import javax.ws.rs.ext.ParamConverter;
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 public class SpringBeanProcessorCustomerParamConverter implements ParamConverter<SpringBeanProcessorCustomer> {
9
10 // this isn't a complex service, but it provides a test to confirm that
11 // RESTEasy doesn't muck up the @Autowired annotation handling in the Spring
12 // life-cycle
13 @Autowired
14 SpringBeanProcessorCustomerService service;
15
16 @Override
17 public SpringBeanProcessorCustomer fromString(String name) {
18 return service.convert(name);
19 }
20
21 public String toString(SpringBeanProcessorCustomer springBeanProcessorCustomer) {
22 return service.convert(springBeanProcessorCustomer);
23 }
24
25 }
+0
-29
testsuite/integration-tests-spring/deployment/src/test/java/org/jboss/resteasy/test/spring/deployment/resource/SpringBeanProcessorCustomerParamConverterProvider.java less more
0 package org.jboss.resteasy.test.spring.deployment.resource;
1
2 import org.springframework.beans.factory.annotation.Autowired;
3
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.Type;
6
7 import javax.ws.rs.ext.ParamConverter;
8 import javax.ws.rs.ext.ParamConverterProvider;
9 import javax.ws.rs.ext.Provider;
10
11 @Provider
12 public class SpringBeanProcessorCustomerParamConverterProvider implements ParamConverterProvider {
13
14 // this isn't a complex service, but it provides a test to confirm that
15 // RESTEasy doesn't muck up the @Autowired annotation handling in the Spring
16 // life-cycle
17 @Autowired
18 SpringBeanProcessorCustomerService service;
19
20
21 @SuppressWarnings("unchecked")
22 @Override
23 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations)
24 {
25 if (!SpringBeanProcessorCustomerParamConverter.class.equals(rawType)) return null;
26 return (ParamConverter<T>)new SpringBeanProcessorCustomerParamConverter();
27 }
28 }
0 package org.jboss.resteasy.test.spring.deployment.resource;
1
2 import org.jboss.resteasy.spi.StringConverter;
3 import org.springframework.beans.factory.annotation.Autowired;
4
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 public class SpringBeanProcessorCustomerStringConverter implements StringConverter<SpringBeanProcessorCustomer> {
9
10 // this isn't a complex service, but it provides a test to confirm that
11 // RESTEasy doesn't muck up the @Autowired annotation handling in the Spring
12 // life-cycle
13 @Autowired
14 SpringBeanProcessorCustomerService service;
15
16 @Override
17 public SpringBeanProcessorCustomer fromString(String name) {
18 return service.convert(name);
19 }
20
21 public String toString(SpringBeanProcessorCustomer springBeanProcessorCustomer) {
22 return service.convert(springBeanProcessorCustomer);
23 }
24
25 }
66 <container qualifier="jbossas-managed" default="true">
77 <configuration>
88 <property name="jbossHome">${jboss.home}</property>
9 <property name="jbossArguments">${securityManagerArg}</property>
910 <!--<property name="serverConfig">${jboss.server.config.file.name:standalone-full.xml}</property>-->
1011 <!--<property name="javaVmArguments">-Xmx512m -XX:MaxPermSize=128m
1112 -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y
1213 </property>-->
1314 <property name="javaVmArguments">-server -Xms96m -Xmx1024m -Djboss.bind.address=${node} -Dnode=${node}
14 -Dipv6=${ipv6} ${additionalJvmArgs} ${ipv6ArquillianSettings} ${jacoco.agent}
15 -Dipv6=${ipv6} ${additionalJvmArgs} ${ipv6ArquillianSettings} ${jacoco.agent} -Dee8.preview.mode=${ee8.preview.mode}
1516 </property>
1617 </configuration>
1718 </container>
1717 <url-pattern>/contacts/*</url-pattern>
1818 </servlet-mapping>
1919
20 <!-- These 3 params appear to be needed in conjunction with permission setting -->
21 <context-param>
22 <param-name>spring.profiles.active</param-name>
23 <param-value>dev</param-value>
24 </context-param>
25 <context-param>
26 <param-name>spring.profiles.default</param-name>
27 <param-value>dev</param-value>
28 </context-param>
29
30 <context-param>
31 <param-name>spring.liveBeansView.mbeanDomain</param-name>
32 <param-value>liveBeansView</param-value>
33 </context-param>
34
2035 </web-app>
1919 <url-pattern>/*</url-pattern>
2020 </servlet-mapping>
2121
22 <!-- These 3 params appear to be needed in conjunction with permission setting -->
23 <context-param>
24 <param-name>spring.profiles.active</param-name>
25 <param-value>dev</param-value>
26 </context-param>
27 <context-param>
28 <param-name>spring.profiles.default</param-name>
29 <param-value>dev</param-value>
30 </context-param>
31
32 <context-param>
33 <param-name>spring.liveBeansView.mbeanDomain</param-name>
34 <param-value>liveBeansView</param-value>
35 </context-param>
36
2237 <context-param>
2338 <param-name>resteasy.scan.resources</param-name>
2439 <param-value>true</param-value>
66 <parent>
77 <groupId>org.jboss.resteasy</groupId>
88 <artifactId>resteasy-integration-tests-spring</artifactId>
9 <version>3.1.4.Final</version>
9 <version>3.5.0.Final</version>
1010 <relativePath>../pom.xml</relativePath>
1111 </parent>
1212
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
55 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.annotations.ClientURI;
6 import org.jboss.resteasy.client.ClientURI;
77 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
88 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
99 import org.jboss.resteasy.test.spring.inmodule.resource.Contact;
00 package org.jboss.resteasy.test.spring.inmodule;
11
2 import java.security.AllPermission;
23 import org.jboss.arquillian.container.test.api.Deployment;
34 import org.jboss.arquillian.junit.Arquillian;
45 import org.jboss.logging.Logger;
56 import org.jboss.resteasy.category.NotForWildFly9;
67 import org.jboss.resteasy.test.spring.inmodule.resource.ContextRefreshResource;
78 import org.jboss.resteasy.test.spring.inmodule.resource.ContextRefreshTrigger;
9 import org.jboss.resteasy.utils.PermissionUtil;
810 import org.jboss.shrinkwrap.api.Archive;
911 import org.jboss.shrinkwrap.api.ShrinkWrap;
1012 import org.jboss.shrinkwrap.api.asset.StringAsset;
1416 import org.junit.experimental.categories.Category;
1517 import org.junit.runner.RunWith;
1618 import org.springframework.web.context.WebApplicationContext;
19
20 import java.io.FilePermission;
21 import java.lang.reflect.ReflectPermission;
1722 import java.util.Enumeration;
23 import java.util.PropertyPermission;
24 import java.util.logging.LoggingPermission;
1825
1926
2027 /**
4047 .addAsWebInfResource(ContextRefreshTest.class.getPackage(), "web.xml", "web.xml")
4148 .addAsWebInfResource(ContextRefreshTest.class.getPackage(), "contextRefresh/applicationContext.xml", "applicationContext.xml");
4249 archive.addAsManifestResource(new StringAsset("Dependencies: org.springframework.spring meta-inf\n"), "MANIFEST.MF");
50
51 // Permission needed for "arquillian.debug" to run
52 // "suppressAccessChecks" required for access to arquillian-core.jar
53 // remaining permissions needed to run springframework
54 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
55 new PropertyPermission("arquillian.*", "read"),
56 new ReflectPermission("suppressAccessChecks"),
57 new RuntimePermission("accessDeclaredMembers"),
58 new RuntimePermission("getClassLoader"),
59 new FilePermission("<<ALL FILES>>", "read"),
60 new LoggingPermission("control", "")
61 ), "permissions.xml");
62
4363 return archive;
4464 }
4565
77 import org.jboss.resteasy.test.spring.inmodule.resource.JavaConfigService;
88 import org.jboss.resteasy.test.spring.inmodule.resource.JavaConfigBeanConfiguration;
99 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PermissionUtil;
1011 import org.jboss.resteasy.utils.PortProviderUtil;
1112 import org.jboss.shrinkwrap.api.Archive;
1213 import org.jboss.shrinkwrap.api.ShrinkWrap;
1920 import javax.ws.rs.client.Client;
2021 import javax.ws.rs.client.WebTarget;
2122 import javax.ws.rs.core.Response;
23 import java.io.FilePermission;
24 import java.lang.reflect.ReflectPermission;
25 import java.util.PropertyPermission;
26 import java.util.logging.LoggingPermission;
2227
2328 /**
2429 * @tpSubChapter Spring
4550 .addClass(JavaConfigBeanConfiguration.class)
4651 .addAsWebInfResource(JavaConfigTest.class.getPackage(), "javaConfig/web.xml", "web.xml");
4752 archive.addAsManifestResource(new StringAsset("Dependencies: org.springframework.spring meta-inf\n"), "MANIFEST.MF");
53
54 // Permission needed for "arquillian.debug" to run
55 // "suppressAccessChecks" required for access to arquillian-core.jar
56 // remaining permissions needed to run springframework
57 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
58 new PropertyPermission("arquillian.*", "read"),
59 new ReflectPermission("suppressAccessChecks"),
60 new RuntimePermission("accessDeclaredMembers"),
61 new RuntimePermission("getClassLoader"),
62 new FilePermission("<<ALL FILES>>", "read"),
63 new LoggingPermission("control", "")
64 ), "permissions.xml");
65
4866 return archive;
4967 }
5068
1010 import org.jboss.resteasy.test.spring.inmodule.resource.RequestScopedBeanQualifierInjectorFactoryImpl;
1111 import org.jboss.resteasy.test.spring.inmodule.resource.RequestScopedBeanTestBean;
1212 import org.jboss.resteasy.test.spring.inmodule.resource.RequestScopedBeanTestBeanResource;
13 import org.jboss.resteasy.utils.PermissionUtil;
1314 import org.jboss.resteasy.utils.PortProviderUtil;
1415 import org.jboss.shrinkwrap.api.Archive;
1516 import org.jboss.shrinkwrap.api.ShrinkWrap;
2223 import javax.ws.rs.client.WebTarget;
2324 import javax.ws.rs.core.MediaType;
2425 import javax.ws.rs.core.Response;
26
27 import java.io.FilePermission;
28 import java.lang.reflect.ReflectPermission;
29 import java.util.PropertyPermission;
30 import java.util.logging.LoggingPermission;
2531
2632 import static org.junit.Assert.assertEquals;
2733
4955 archive.addClass(RequestScopedBeanBean.class);
5056 archive.addClass(RequestScopedBeanTestBeanResource.class);
5157 archive.addClass(RequestScopedBeanBeanFactoryBean.class);
58
59 // Permission needed for "arquillian.debug" to run
60 // "suppressAccessChecks" required for access to arquillian-core.jar
61 // remaining permissions needed to run springframework
62 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
63 new PropertyPermission("arquillian.*", "read"),
64 new ReflectPermission("suppressAccessChecks"),
65 new RuntimePermission("accessDeclaredMembers"),
66 new RuntimePermission("getClassLoader"),
67 new FilePermission("<<ALL FILES>>", "read"),
68 new LoggingPermission("control", "")
69 ), "permissions.xml");
70
5271 return archive;
5372 }
5473
1818 import org.jboss.resteasy.test.spring.inmodule.resource.SpringBeanProcessorMyResource;
1919 import org.jboss.resteasy.test.spring.inmodule.resource.SpringBeanProcessorMyWriter;
2020 import org.jboss.resteasy.test.spring.inmodule.resource.SpringBeanProcessorResourceConfiguration;
21 import org.jboss.resteasy.test.spring.inmodule.resource.SpringBeanProcessorCustomerParamConverter;
22 import org.jboss.resteasy.test.spring.inmodule.resource.SpringBeanProcessorCustomerParamConverterProvider;
21 import org.jboss.resteasy.test.spring.inmodule.resource.SpringBeanProcessorCustomerStringConverter;
2322 import org.jboss.resteasy.test.spring.inmodule.resource.SpringBeanProcessorScannedResource;
2423 import org.jboss.resteasy.util.HttpResponseCodes;
24 import org.jboss.resteasy.utils.PermissionUtil;
2525 import org.jboss.resteasy.utils.PortProviderUtil;
2626 import org.jboss.shrinkwrap.api.Archive;
2727 import org.jboss.shrinkwrap.api.ShrinkWrap;
3535
3636 import javax.ws.rs.client.WebTarget;
3737 import javax.ws.rs.core.Response;
38 import java.io.FilePermission;
39 import java.lang.reflect.ReflectPermission;
40 import java.util.PropertyPermission;
41 import java.util.logging.LoggingPermission;
3842
3943 /**
4044 * @tpSubChapter Spring
8589 archive.addClass(SpringBeanProcessorMyResource.class);
8690 archive.addClass(SpringBeanProcessorMyWriter.class);
8791 archive.addClass(SpringBeanProcessorResourceConfiguration.class);
88 archive.addClass(SpringBeanProcessorCustomerParamConverter.class);
89 archive.addClass(SpringBeanProcessorCustomerParamConverterProvider.class);
92 archive.addClass(SpringBeanProcessorCustomerStringConverter.class);
9093 archive.addClass(SpringBeanProcessorScannedResource.class);
94
95 // Permission needed for "arquillian.debug" to run
96 // "suppressAccessChecks" required for access to arquillian-core.jar
97 // remaining permissions needed to run springframework
98 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
99 new PropertyPermission("arquillian.*", "read"),
100 new ReflectPermission("suppressAccessChecks"),
101 new RuntimePermission("accessDeclaredMembers"),
102 new RuntimePermission("getClassLoader"),
103 new FilePermission("<<ALL FILES>>", "read"),
104 new LoggingPermission("control", "")
105 ), "permissions.xml");
106
91107 return archive;
92108 }
93109
77 import org.jboss.resteasy.test.spring.inmodule.resource.SpringLocatingLocatingResource;
88 import org.jboss.resteasy.test.spring.inmodule.resource.SpringLocatingSimpleResource;
99 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PermissionUtil;
1011 import org.jboss.resteasy.utils.PortProviderUtil;
1112 import org.jboss.shrinkwrap.api.Archive;
1213 import org.jboss.shrinkwrap.api.ShrinkWrap;
2021 import javax.ws.rs.client.Entity;
2122 import javax.ws.rs.client.WebTarget;
2223 import javax.ws.rs.core.Response;
24 import java.io.FilePermission;
25 import java.lang.reflect.ReflectPermission;
26 import java.util.PropertyPermission;
27 import java.util.logging.LoggingPermission;
2328
2429 /**
2530 * @tpSubChapter Spring
4146 archive.addAsManifestResource(new StringAsset("Dependencies: org.springframework.spring meta-inf\n"), "MANIFEST.MF");
4247 archive.addClass(SpringLocatingLocatingResource.class);
4348 archive.addClass(SpringLocatingSimpleResource.class);
49
50 // Permission needed for "arquillian.debug" to run
51 // "suppressAccessChecks" required for access to arquillian-core.jar
52 // remaining permissions needed to run springframework
53 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
54 new PropertyPermission("arquillian.*", "read"),
55 new ReflectPermission("suppressAccessChecks"),
56 new RuntimePermission("accessDeclaredMembers"),
57 new RuntimePermission("getClassLoader"),
58 new FilePermission("<<ALL FILES>>", "read"),
59 new LoggingPermission("control", "")
60 ), "permissions.xml");
61
4462 return archive;
4563 }
4664
22 import org.jboss.logging.Logger;
33 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
44 import org.jboss.resteasy.util.HttpResponseCodes;
5 import org.jboss.resteasy.utils.PermissionUtil;
56 import org.jboss.shrinkwrap.api.ShrinkWrap;
67 import org.jboss.shrinkwrap.api.asset.StringAsset;
78 import org.junit.Assert;
1718 import javax.ws.rs.client.Client;
1819 import javax.ws.rs.client.WebTarget;
1920 import javax.ws.rs.core.Response;
21 import java.io.FilePermission;
22 import java.lang.reflect.ReflectPermission;
2023 import java.util.HashMap;
2124 import java.util.Map;
25 import java.util.PropertyPermission;
26 import java.util.logging.LoggingPermission;
2227
2328 /**
2429 * @tpSubChapter Spring
4348 .addAsWebInfResource(SpringWebappContextTest.class.getPackage(), "web.xml", "web.xml")
4449 .addAsWebInfResource(SpringWebappContextTest.class.getPackage(), "springWebAppContext/applicationContext.xml", "applicationContext.xml");
4550 archive.addAsManifestResource(new StringAsset("Dependencies: org.springframework.spring meta-inf\n"), "MANIFEST.MF");
51
52 // Permission needed for "arquillian.debug" to run
53 // "suppressAccessChecks" required for access to arquillian-core.jar
54 // remaining permissions needed to run springframework
55 archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset(
56 new PropertyPermission("arquillian.*", "read"),
57 new ReflectPermission("suppressAccessChecks"),
58 new RuntimePermission("accessDeclaredMembers"),
59 new RuntimePermission("getClassLoader"),
60 new FilePermission("<<ALL FILES>>", "read"),
61 new LoggingPermission("control", "")
62 ), "permissions.xml");
63
4664 return archive;
4765 }
4866
22 import org.jboss.arquillian.container.test.api.Deployment;
33 import org.jboss.arquillian.container.test.api.RunAsClient;
44 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.category.ExpectedFailing;
65 import org.jboss.resteasy.category.NotForForwardCompatibility;
76 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
87 import org.jboss.resteasy.test.spring.inmodule.resource.TypeMappingResource;
98 import org.jboss.resteasy.util.HttpResponseCodes;
109 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
1210 import org.jboss.shrinkwrap.api.Archive;
1311 import org.jboss.shrinkwrap.api.ShrinkWrap;
1412 import org.jboss.shrinkwrap.api.asset.StringAsset;
+0
-26
testsuite/integration-tests-spring/inmodule/src/test/java/org/jboss/resteasy/test/spring/inmodule/resource/SpringBeanProcessorCustomerParamConverter.java less more
0 package org.jboss.resteasy.test.spring.inmodule.resource;
1
2 import org.springframework.beans.factory.annotation.Autowired;
3
4 import javax.ws.rs.ext.ParamConverter;
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 public class SpringBeanProcessorCustomerParamConverter implements ParamConverter<SpringBeanProcessorCustomer> {
9
10 // this isn't a complex service, but it provides a test to confirm that
11 // RESTEasy doesn't muck up the @Autowired annotation handling in the Spring
12 // life-cycle
13 @Autowired
14 SpringBeanProcessorCustomerService service;
15
16 @Override
17 public SpringBeanProcessorCustomer fromString(String name) {
18 return service.convert(name);
19 }
20
21 public String toString(SpringBeanProcessorCustomer springBeanProcessorCustomer) {
22 return service.convert(springBeanProcessorCustomer);
23 }
24
25 }
+0
-29
testsuite/integration-tests-spring/inmodule/src/test/java/org/jboss/resteasy/test/spring/inmodule/resource/SpringBeanProcessorCustomerParamConverterProvider.java less more
0 package org.jboss.resteasy.test.spring.inmodule.resource;
1
2 import org.springframework.beans.factory.annotation.Autowired;
3
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.Type;
6
7 import javax.ws.rs.ext.ParamConverter;
8 import javax.ws.rs.ext.ParamConverterProvider;
9 import javax.ws.rs.ext.Provider;
10
11 @Provider
12 public class SpringBeanProcessorCustomerParamConverterProvider implements ParamConverterProvider {
13
14 // this isn't a complex service, but it provides a test to confirm that
15 // RESTEasy doesn't muck up the @Autowired annotation handling in the Spring
16 // life-cycle
17 @Autowired
18 SpringBeanProcessorCustomerService service;
19
20 @SuppressWarnings("unchecked")
21 @Override
22 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations)
23 {
24 if (!SpringBeanProcessorCustomerParamConverter.class.equals(rawType)) return null;
25 return (ParamConverter<T>)new SpringBeanProcessorCustomerParamConverter();
26 }
27
28 }
0 package org.jboss.resteasy.test.spring.inmodule.resource;
1
2 import org.jboss.resteasy.spi.StringConverter;
3 import org.springframework.beans.factory.annotation.Autowired;
4
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 public class SpringBeanProcessorCustomerStringConverter implements StringConverter<SpringBeanProcessorCustomer> {
9
10 // this isn't a complex service, but it provides a test to confirm that
11 // RESTEasy doesn't muck up the @Autowired annotation handling in the Spring
12 // life-cycle
13 @Autowired
14 SpringBeanProcessorCustomerService service;
15
16 @Override
17 public SpringBeanProcessorCustomer fromString(String name) {
18 return service.convert(name);
19 }
20
21 public String toString(SpringBeanProcessorCustomer springBeanProcessorCustomer) {
22 return service.convert(springBeanProcessorCustomer);
23 }
24
25 }
66 <container qualifier="jbossas-managed" default="true">
77 <configuration>
88 <property name="jbossHome">${jboss.home}</property>
9 <property name="jbossArguments">${securityManagerArg}</property>
910 <property name="serverConfig">${jboss.server.config.file.name:standalone.xml}</property>
1011 <!--<property name="javaVmArguments">-Xmx512m -XX:MaxPermSize=128m
1112 -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y
1213 </property>-->
13 <property name="javaVmArguments">-server -Xms96m -Xmx1024m -Djboss.bind.address=${node} -Djboss.bind.address.management=${node} -Dnode=${node} -Dipv6=${ipv6} ${additionalJvmArgs} ${ipv6ArquillianSettings} ${jacoco.agent}</property>
14 <property name="javaVmArguments">-server -Xms96m -Xmx1024m -Djboss.bind.address=${node} -Djboss.bind.address.management=${node} -Dnode=${node} -Dipv6=${ipv6} ${additionalJvmArgs} ${ipv6ArquillianSettings} ${jacoco.agent} -Dee8.preview.mode=${ee8.preview.mode}</property>
1415 <property name="managementAddress">${node}</property>
1516 </configuration>
1617 </container>
66 <parent>
77 <groupId>org.jboss.resteasy</groupId>
88 <artifactId>resteasy-testsuite</artifactId>
9 <version>3.1.4.Final</version>
9 <version>3.5.0.Final</version>
1010 <relativePath>../pom.xml</relativePath>
1111 </parent>
1212
121121 <version>${version.resteasy.testsuite}</version>
122122 <scope>provided</scope>
123123 </dependency>
124
125 <dependency>
126 <groupId>org.jboss.resteasy</groupId>
127 <artifactId>resteasy-json-binding-provider</artifactId>
128 <version>${version.resteasy.testsuite}</version>
129 <scope>provided</scope>
130 </dependency>
131
124132 </dependencies>
125
126133 </project>
66 <parent>
77 <groupId>org.jboss.resteasy</groupId>
88 <artifactId>resteasy-integration-tests-spring</artifactId>
9 <version>3.1.4.Final</version>
9 <version>3.5.0.Final</version>
1010 <relativePath>../pom.xml</relativePath>
1111 </parent>
1212
+0
-380
testsuite/legacy-integration-tests/pom.xml less more
0 <?xml version="1.0"?>
1 <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
2 xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.jboss.resteasy</groupId>
8 <artifactId>resteasy-testsuite</artifactId>
9 <version>3.1.4.Final</version>
10 <relativePath>../pom.xml</relativePath>
11 </parent>
12
13 <artifactId>resteasy-legacy-integration-tests</artifactId>
14 <name>RESTEasy Main testsuite: Legacy integration tests</name>
15
16 <profiles>
17 <!--
18 Name: download
19 Descr: Download WildFly
20 -->
21 <profile>
22 <id>download</id>
23 <activation>
24 <property>
25 <name>!server.home</name>
26 </property>
27 </activation>
28 <build>
29 <plugins>
30 <plugin>
31 <artifactId>maven-dependency-plugin</artifactId>
32 <executions>
33 <execution>
34 <id>unpack</id>
35 <phase>process-test-classes</phase>
36 <goals>
37 <goal>unpack</goal>
38 </goals>
39 <configuration>
40 <artifactItems>
41 <artifactItem>
42 <groupId>org.wildfly</groupId>
43 <artifactId>wildfly-dist</artifactId>
44 <version>${server.version}</version>
45 <type>zip</type>
46 <overWrite>false</overWrite>
47 <outputDirectory>${project.build.directory}/test-server</outputDirectory>
48 </artifactItem>
49 </artifactItems>
50 </configuration>
51 </execution>
52 </executions>
53 </plugin>
54 <plugin>
55 <groupId>org.apache.maven.plugins</groupId>
56 <artifactId>maven-antrun-plugin</artifactId>
57 <executions>
58 <execution>
59 <id>unpack resteasy</id>
60 <phase>process-test-classes</phase>
61 <configuration>
62 <target>
63 <!-- Explicitly remove resteasy-spring contents as the module.xml does not reference resource jars in this case
64 so adding jars without removing old ones basically messes up the classloader -->
65 <delete>
66 <fileset dir="${project.build.directory}/test-server/wildfly-${server.version}/modules/system/layers/base/org/jboss/resteasy/resteasy-spring/main" includes="**/*.jar"/>
67 </delete>
68 <unzip src="../../jboss-modules/target/resteasy-jboss-modules-${project.version}.zip"
69 dest="${project.build.directory}/test-server/wildfly-${server.version}/modules/system/layers/base"
70 overwrite="true"/>
71 <delete dir="target/dependency-maven-plugin-markers"/>
72 </target>
73 </configuration>
74 <goals>
75 <goal>run</goal>
76 </goals>
77 </execution>
78 </executions>
79 </plugin>
80 </plugins>
81 </build>
82 <properties>
83 <jboss.home>${project.build.directory}/test-server/wildfly-${server.version}</jboss.home>
84 </properties>
85 </profile>
86
87 <profile>
88 <id>groovy</id>
89 <activation>
90 <property>
91 <name>!no.groovy</name>
92 </property>
93 </activation>
94 <build>
95 <plugins>
96
97 <plugin>
98 <groupId>org.codehaus.gmavenplus</groupId>
99 <artifactId>gmavenplus-plugin</artifactId>
100 <version>1.5</version>
101 <dependencies>
102 <dependency>
103 <groupId>org.codehaus.groovy</groupId>
104 <artifactId>groovy-all</artifactId>
105 <version>2.4.7</version>
106 <scope>runtime</scope>
107 </dependency>
108 </dependencies>
109 <executions>
110 <execution>
111 <id>testsuite-default</id>
112 <phase>process-test-classes</phase>
113 <goals>
114 <goal>execute</goal>
115 </goals>
116 <configuration>
117 <scripts><script>file:///${basedir}/src/test/scripts/legacy.groovy</script></scripts>
118 <properties>
119 <property>
120 <name>inputFile</name>
121 <value>${jboss.home}/standalone/configuration/standalone-full.xml</value>
122 </property>
123 <property>
124 <name>outputFile</name>
125 <value>${jboss.home}/standalone/configuration/standalone-resteasy-legacy.xml</value>
126 </property>
127 </properties>
128 </configuration>
129 </execution>
130 </executions>
131 </plugin>
132
133 </plugins>
134 </build>
135 </profile>
136
137
138 </profiles>
139
140
141 <dependencies>
142 <!-- TODO Workaround dependency for arquillian to work with container using Remoting 5. Remove when updated version of
143 wildfly-arquillian-container-managed is available -->
144 <dependency>
145 <groupId>org.wildfly.security</groupId>
146 <artifactId>wildfly-elytron</artifactId>
147 <scope>test</scope>
148 </dependency>
149
150 <dependency>
151 <groupId>org.jboss.resteasy</groupId>
152 <artifactId>resteasy-legacy</artifactId>
153 <version>${version.resteasy.testsuite}</version>
154 </dependency>
155
156 <dependency>
157 <groupId>org.jboss.resteasy</groupId>
158 <artifactId>arquillian-utils</artifactId>
159 <version>${project.version}</version>
160 </dependency>
161
162 <dependency>
163 <groupId>org.jboss.resteasy</groupId>
164 <artifactId>resteasy-jaxb-provider</artifactId>
165 <version>${version.resteasy.testsuite}</version>
166 </dependency>
167
168 <dependency>
169 <groupId>org.jboss.resteasy</groupId>
170 <artifactId>resteasy-client</artifactId>
171 <version>${version.resteasy.testsuite}</version>
172 </dependency>
173
174 <dependency>
175 <groupId>org.jboss.resteasy</groupId>
176 <artifactId>resteasy-validator-provider-11</artifactId>
177 <version>${version.resteasy.testsuite}</version>
178 </dependency>
179
180 <dependency>
181 <groupId>org.jboss.resteasy</groupId>
182 <artifactId>resteasy-multipart-provider</artifactId>
183 <version>${version.resteasy.testsuite}</version>
184 </dependency>
185
186 <dependency>
187 <groupId>org.jboss.resteasy</groupId>
188 <artifactId>resteasy-jackson-provider</artifactId>
189 <version>${version.resteasy.testsuite}</version>
190 </dependency>
191
192 <dependency>
193 <groupId>org.jboss.resteasy</groupId>
194 <artifactId>resteasy-jackson2-provider</artifactId>
195 <version>${version.resteasy.testsuite}</version>
196 </dependency>
197
198 <dependency>
199 <groupId>org.jboss.resteasy</groupId>
200 <artifactId>resteasy-jettison-provider</artifactId>
201 <version>${version.resteasy.testsuite}</version>
202 </dependency>
203
204 <dependency>
205 <groupId>org.jboss.resteasy</groupId>
206 <artifactId>resteasy-json-p-provider</artifactId>
207 <version>${version.resteasy.testsuite}</version>
208 </dependency>
209
210 <dependency>
211 <groupId>org.jboss.resteasy</groupId>
212 <artifactId>resteasy-yaml-provider</artifactId>
213 <version>${version.resteasy.testsuite}</version>
214 </dependency>
215
216 <dependency>
217 <groupId>org.jboss.resteasy</groupId>
218 <artifactId>resteasy-atom-provider</artifactId>
219 <version>${version.resteasy.testsuite}</version>
220 </dependency>
221
222 <dependency>
223 <groupId>org.jboss.resteasy</groupId>
224 <artifactId>resteasy-cache-core</artifactId>
225 <version>${project.version}</version>
226 </dependency>
227
228 <dependency>
229 <groupId>org.jboss.resteasy</groupId>
230 <artifactId>resteasy-cdi</artifactId>
231 <version>${version.resteasy.testsuite}</version>
232 </dependency>
233
234 <dependency>
235 <groupId>org.jboss.resteasy</groupId>
236 <artifactId>resteasy-crypto</artifactId>
237 <version>${version.resteasy.testsuite}</version>
238 </dependency>
239
240 <dependency>
241 <groupId>org.jboss.resteasy</groupId>
242 <artifactId>resteasy-wadl</artifactId>
243 <version>${project.version}</version>
244 </dependency>
245
246 <dependency>
247 <groupId>org.jboss.resteasy</groupId>
248 <artifactId>resteasy-jdk-http</artifactId>
249 <version>${project.version}</version>
250 </dependency>
251
252 <dependency>
253 <groupId>org.jboss.resteasy</groupId>
254 <artifactId>resteasy-netty</artifactId>
255 <version>${project.version}</version>
256 </dependency>
257
258 <dependency>
259 <groupId>org.jboss.resteasy</groupId>
260 <artifactId>resteasy-netty4</artifactId>
261 <version>${project.version}</version>
262 </dependency>
263
264 <dependency>
265 <groupId>org.jboss.resteasy</groupId>
266 <artifactId>resteasy-wadl-undertow-connector</artifactId>
267 <version>${project.version}</version>
268 </dependency>
269
270 <dependency>
271 <groupId>org.apache.logging.log4j</groupId>
272 <artifactId>log4j-api</artifactId>
273 </dependency>
274
275 <dependency>
276 <groupId>org.apache.logging.log4j</groupId>
277 <artifactId>log4j-core</artifactId>
278 </dependency>
279
280 <dependency>
281 <groupId>org.jboss.spec.javax.ejb</groupId>
282 <artifactId>jboss-ejb-api_3.2_spec</artifactId>
283 </dependency>
284
285 <dependency>
286 <groupId>javax.enterprise</groupId>
287 <artifactId>cdi-api</artifactId>
288 </dependency>
289
290 <dependency>
291 <groupId>org.hibernate.javax.persistence</groupId>
292 <artifactId>hibernate-jpa-2.1-api</artifactId>
293 </dependency>
294
295 <dependency>
296 <groupId>org.jboss.spec.javax.jms</groupId>
297 <artifactId>jboss-jms-api_2.0_spec</artifactId>
298 </dependency>
299
300 <dependency>
301 <groupId>org.jboss.spec.javax.el</groupId>
302 <artifactId>jboss-el-api_3.0_spec</artifactId>
303 </dependency>
304
305 <dependency>
306 <groupId>org.jboss.spec.javax.servlet</groupId>
307 <artifactId>jboss-servlet-api_3.1_spec</artifactId>
308 </dependency>
309
310 <dependency>
311 <groupId>org.apache.httpcomponents</groupId>
312 <artifactId>httpclient</artifactId>
313 </dependency>
314
315 <dependency>
316 <groupId>org.hamcrest</groupId>
317 <artifactId>hamcrest-all</artifactId>
318 </dependency>
319
320 <dependency>
321 <groupId>org.wildfly.extras.creaper</groupId>
322 <artifactId>creaper-core</artifactId>
323 <exclusions>
324 <exclusion>
325 <groupId>org.jboss.as</groupId>
326 <artifactId>jboss-as-controller-client</artifactId>
327 </exclusion>
328 <exclusion>
329 <groupId>org.jboss.as</groupId>
330 <artifactId>jboss-as-cli</artifactId>
331 </exclusion>
332 </exclusions>
333 </dependency>
334
335 <dependency>
336 <groupId>org.wildfly.extras.creaper</groupId>
337 <artifactId>creaper-commands</artifactId>
338 <exclusions>
339 <exclusion>
340 <groupId>org.wildfly</groupId>
341 <artifactId>wildfly-patching</artifactId>
342 </exclusion>
343 </exclusions>
344 </dependency>
345
346 <dependency>
347 <groupId>org.wildfly.core</groupId>
348 <artifactId>wildfly-cli</artifactId>
349 </dependency>
350
351 <dependency>
352 <groupId>org.glassfish</groupId>
353 <artifactId>javax.el</artifactId>
354 </dependency>
355
356 </dependencies>
357
358 <build>
359 <testResources>
360 <testResource>
361 <directory>src/test/resources</directory>
362 <filtering>true</filtering>
363 <includes>
364 <include>arquillian.xml</include>
365 </includes>
366 </testResource>
367 <testResource>
368 <directory>src/test/resources</directory>
369 <excludes>
370 <exclude>arquillian.xml</exclude>
371 </excludes>
372 </testResource>
373 </testResources>
374 <plugins>
375
376 </plugins>
377 </build>
378
379 </project>
+0
-125
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/AsyncPostProcessingTest.java less more
0 package org.jboss.resteasy.test.asynch;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
6 import org.jboss.resteasy.test.asynch.resource.AsyncPostProcessingMsgBodyWriterInterceptor;
7 import org.jboss.resteasy.test.asynch.resource.AsyncPostProcessingInterceptor;
8 import org.jboss.resteasy.test.asynch.resource.AsyncPostProcessingResource;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.asset.StringAsset;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import org.jboss.logging.Logger;
22
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Asynchronous RESTEasy
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Regression test for RESTEASY-767
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 public class AsyncPostProcessingTest {
33
34 private static Logger logger = Logger.getLogger(AsyncPostProcessingTest.class);
35 static ResteasyClient client;
36
37 @Deployment
38 public static Archive<?> createTestArchive() {
39 WebArchive war = TestUtil.prepareArchive(AsyncPostProcessingTest.class.getSimpleName());
40 war.addClasses(TestUtil.class, PortProviderUtil.class);
41 war.addAsWebInfResource(AsyncPostProcessingTest.class.getPackage(), "AsyncPostProcessingTestWeb.xml", "web.xml");
42 return TestUtil.finishContainerPrepare(war, null, AsyncPostProcessingResource.class,
43 AsyncPostProcessingMsgBodyWriterInterceptor.class, AsyncPostProcessingInterceptor.class);
44 }
45
46 private String generateURL(String path) {
47 return PortProviderUtil.generateURL(path, AsyncPostProcessingTest.class.getSimpleName());
48 }
49
50 @Before
51 public void init() {
52 client = new ResteasyClientBuilder().build();
53 }
54
55 @After
56 public void after() throws Exception {
57 client.close();
58 }
59
60 /**
61 * @tpTestDetails Test synchronized request.
62 * @tpSince RESTEasy 3.0.16
63 */
64 @Test
65 public void testSync() throws Exception {
66 reset();
67 Response response = client.target(generateURL("/sync")).request().get();
68 logger.info("Status: " + response.getStatus());
69 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
70 logger.info("TestMessageBodyWriterInterceptor.called: " + AsyncPostProcessingMsgBodyWriterInterceptor.called);
71 logger.info("TestPostProcessInterceptor.called: " + AsyncPostProcessingInterceptor.called);
72 response.bufferEntity();
73 logger.info("returned entity: " + response.readEntity(String.class));
74 Assert.assertTrue("AsyncPostProcessingMsgBodyWriterInterceptor interceptor was not called",
75 AsyncPostProcessingMsgBodyWriterInterceptor.called);
76 Assert.assertTrue("AsyncPostProcessingInterceptor interceptor was not called", AsyncPostProcessingInterceptor.called);
77 Assert.assertEquals("Entity has wrong content", "sync", response.readEntity(String.class));
78 }
79
80 /**
81 * @tpTestDetails Test async request with delay.
82 * @tpSince RESTEasy 3.0.16
83 */
84 @Test
85 public void testAsyncWithDelay() throws Exception {
86 reset();
87 Response response = client.target(generateURL("/async/delay")).request().get();
88 logger.info("Status: " + response.getStatus());
89 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
90 logger.info("TestMessageBodyWriterInterceptor.called: " + AsyncPostProcessingMsgBodyWriterInterceptor.called);
91 logger.info("TestPostProcessInterceptor.called: " + AsyncPostProcessingInterceptor.called);
92 response.bufferEntity();
93 logger.info("returned entity: " + response.readEntity(String.class));
94 Assert.assertTrue("AsyncPostProcessingMsgBodyWriterInterceptor interceptor was not called",
95 AsyncPostProcessingMsgBodyWriterInterceptor.called);
96 Assert.assertTrue("AsyncPostProcessingInterceptor interceptor was not called", AsyncPostProcessingInterceptor.called);
97 Assert.assertEquals("Entity has wrong content", "async/delay", response.readEntity(String.class));
98 }
99
100 /**
101 * @tpTestDetails Test async request without delay.
102 * @tpSince RESTEasy 3.0.16
103 */
104 @Test
105 public void testAsyncWithNoDelay() throws Exception {
106 reset();
107 Response response = client.target(generateURL("/async/nodelay")).request().get();
108 logger.info("Status: " + response.getStatus());
109 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
110 logger.info("TestMessageBodyWriterInterceptor.called: " + AsyncPostProcessingMsgBodyWriterInterceptor.called);
111 logger.info("TestPostProcessInterceptor.called: " + AsyncPostProcessingInterceptor.called);
112 response.bufferEntity();
113 logger.info("returned entity: " + response.readEntity(String.class));
114 Assert.assertTrue("AsyncPostProcessingMsgBodyWriterInterceptor interceptor was not called",
115 AsyncPostProcessingMsgBodyWriterInterceptor.called);
116 Assert.assertTrue("AsyncPostProcessingInterceptor interceptor was not called", AsyncPostProcessingInterceptor.called);
117 Assert.assertEquals("Entity has wrong content", "async/nodelay", response.readEntity(String.class));
118 }
119
120 private void reset() {
121 AsyncPostProcessingMsgBodyWriterInterceptor.called = false;
122 AsyncPostProcessingInterceptor.called = false;
123 }
124 }
+0
-75
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/AsyncServletTest.java less more
0 package org.jboss.resteasy.test.asynch;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.asynch.resource.AsyncServletResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.After;
14 import org.junit.Assert;
15 import org.junit.Before;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.core.Response;
20
21
22 /**
23 * @tpSubChapter Asynchronous RESTEasy
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Test for asyncHttpServlet module
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class AsyncServletTest {
31
32 static ResteasyClient client;
33
34 @Before
35 public void init() {
36 client = new ResteasyClientBuilder().build();
37 }
38
39 @After
40 public void after() throws Exception {
41 client.close();
42 }
43
44 @Deployment
45 public static Archive<?> createTestArchive() {
46 WebArchive war = TestUtil.prepareArchive(AsyncServletTest.class.getSimpleName());
47 return TestUtil.finishContainerPrepare(war, null, AsyncServletResource.class);
48 }
49
50 private String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, AsyncServletTest.class.getSimpleName());
52 }
53
54 /**
55 * @tpTestDetails Test for correct response
56 * @tpSince RESTEasy 3.0.16
57 */
58 @Test
59 public void testAsync() throws Exception {
60 Response response = client.target(generateURL("/async")).request().get();
61 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
62 Assert.assertEquals("Wrong response content", "hello", response.readEntity(String.class));
63 }
64
65 /**
66 * @tpTestDetails Service unavailable test
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void testTimeout() throws Exception {
71 Response response = client.target(generateURL("/async/timeout")).request().get();
72 Assert.assertEquals(HttpResponseCodes.SC_SERVICE_UNAVAILABLE, response.getStatus());
73 }
74 }
+0
-286
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/AsynchBasicTest.java less more
0 package org.jboss.resteasy.test.asynch;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.OperateOnDeployment;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.asynch.resource.AsynchBasicResource;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.asset.StringAsset;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.servlet.http.HttpServletResponse;
18 import javax.ws.rs.client.Entity;
19 import javax.ws.rs.core.HttpHeaders;
20 import javax.ws.rs.core.Response;
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.TimeUnit;
26
27 import static org.jboss.resteasy.utils.PortProviderUtil.generateURL;
28
29 /**
30 * @tpSubChapter Asynchronous RESTEasy
31 * @tpChapter Integration tests
32 * @tpTestCaseDetails Basic asynchronous test for "resteasy.async.job.service.max.job.results" property.
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 public class AsynchBasicTest {
37 private static org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger(AsynchBasicTest.class);
38
39 public static CountDownLatch latch;
40
41 private static final String DEFAULT_DEPLOYMENT = "AsynchBasicTestBasic";
42 private static final String ONE_MAX_DEPLOYMENT = "AsynchBasicTestOne";
43 private static final String TEN_MAX_DEPLOYMENT = "AsynchBasicTestTen";
44
45
46 public static Archive<?> deploy(String deploymentName, String maxSize) {
47 WebArchive war = TestUtil.prepareArchive(deploymentName);
48 war.addClass(PortProviderUtil.class);
49 war.addClass(TestUtil.class);
50 Map<String, String> contextParam = new HashMap<>();
51 contextParam.put("resteasy.async.job.service.enabled", "true");
52 if (maxSize != null) {
53 contextParam.put("resteasy.async.job.service.max.job.results", maxSize);
54 }
55 return TestUtil.finishContainerPrepare(war, contextParam, AsynchBasicResource.class);
56 }
57
58 @Deployment(name = DEFAULT_DEPLOYMENT)
59 public static Archive<?> deployDefault() {
60 return deploy(DEFAULT_DEPLOYMENT, null);
61 }
62
63 @Deployment(name = ONE_MAX_DEPLOYMENT)
64 public static Archive<?> deployOne() {
65 return deploy(ONE_MAX_DEPLOYMENT, "1");
66 }
67
68 @Deployment(name = TEN_MAX_DEPLOYMENT)
69 public static Archive<?> deployTen() {
70 return deploy(TEN_MAX_DEPLOYMENT, "10");
71 }
72
73 private ResteasyClient initClient() {
74 return new ResteasyClientBuilder()
75 .socketTimeout(5, TimeUnit.SECONDS)
76 .connectionCheckoutTimeout(5, TimeUnit.SECONDS)
77 .establishConnectionTimeout(5, TimeUnit.SECONDS)
78 .build();
79 }
80
81 /**
82 * @tpTestDetails Test oneway=true query parameter
83 * @tpSince RESTEasy 3.0.16
84 */
85 @Test
86 @OperateOnDeployment(DEFAULT_DEPLOYMENT)
87 public void testOneway() throws Exception {
88 ResteasyClient client = initClient();
89 Response response = null;
90 try {
91 latch = new CountDownLatch(1);
92 long start = System.currentTimeMillis();
93 response = client.target(generateURL("?oneway=true", DEFAULT_DEPLOYMENT)).request().put(Entity.entity("content", "text/plain"));
94
95 //response = request.put();
96 long end = System.currentTimeMillis() - start;
97 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
98 Assert.assertTrue(end < 1000);
99 Assert.assertTrue("Request was not sent correctly", latch.await(2, TimeUnit.SECONDS));
100 } finally {
101 response.close();
102 client.close();
103 }
104 }
105
106 /**
107 * @tpTestDetails Use default value of resteasy.async.job.service.max.job.results
108 * @tpSince RESTEasy 3.0.16
109 */
110 @Test
111 @OperateOnDeployment(DEFAULT_DEPLOYMENT)
112 public void testAsynchBasic() throws Exception {
113 final int MAX = 4;
114 ResteasyClient client = initClient();
115
116 latch = new CountDownLatch(1);
117 long start = System.currentTimeMillis();
118 Response response = client.target(generateURL("?asynch=true", DEFAULT_DEPLOYMENT)).request().post(Entity.entity("content", "text/plain"));
119 @SuppressWarnings("unused")
120 long end = System.currentTimeMillis() - start;
121 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
122 String jobUrl = response.getHeaderString(HttpHeaders.LOCATION);
123 response.close();
124
125 response = client.target(jobUrl).request().get();
126 Assert.assertTrue("Request was not sent correctly", latch.await(3, TimeUnit.SECONDS));
127 response.close();
128
129 // there's a lag between when the latch completes and the executor
130 // registers the completion of the call
131 for (int i = 0; i <= MAX; i++) {
132 response = client.target(jobUrl).request().get();
133 Thread.sleep(1000);
134 if (HttpServletResponse.SC_OK == response.getStatus()) {
135 Assert.assertEquals("Wrong response content", "content", response.readEntity(String.class));
136 response.close();
137 break;
138 }
139 response.close();
140 if (i == MAX) {
141 Assert.fail("Expected response with status code 200");
142 }
143 }
144
145 // test its still there
146 response = client.target(jobUrl).request().get();
147 Thread.sleep(1000);
148 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
149 Assert.assertEquals("Wrong response content", "content", response.readEntity(String.class));
150 response.close();
151
152 // delete and test delete
153 response = client.target(jobUrl).request().delete();
154 Assert.assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
155 response.close();
156
157 response = client.target(jobUrl).request().get();
158 Thread.sleep(1000);
159 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
160 response.close();
161
162 client.close();
163 }
164
165 /**
166 * @tpTestDetails Set value of resteasy.async.job.service.max.job.results to 1. Try to store to cache to items.
167 * @tpSince RESTEasy 3.0.16
168 */
169 @Test
170 @OperateOnDeployment(ONE_MAX_DEPLOYMENT)
171 public void testAsynchOne() throws Exception {
172 ResteasyClient client = initClient();
173
174 // test cache size
175 latch = new CountDownLatch(1);
176 Response response = client.target(generateURL("?asynch=true", ONE_MAX_DEPLOYMENT)).request().post(Entity.entity("content", "text/plain"));
177 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
178 String jobUrl1 = response.getHeaderString(HttpHeaders.LOCATION);
179 Assert.assertTrue("Request was not sent correctly", latch.await(3, TimeUnit.SECONDS));
180 response.close();
181
182 latch = new CountDownLatch(1);
183 response = client.target(generateURL("?asynch=true", ONE_MAX_DEPLOYMENT)).request().post(Entity.entity("content", "text/plain"));
184 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
185 String jobUrl2 = response.getHeaderString(HttpHeaders.LOCATION);
186 Assert.assertTrue("Request was not sent correctly", latch.await(3, TimeUnit.SECONDS));
187 Assert.assertTrue("There are only one response for two requests", !jobUrl1.equals(jobUrl2));
188 response.close();
189
190 response = client.target(jobUrl1).request().get();
191 Thread.sleep(1000);
192 Assert.assertEquals("Response should be gone, but server still remember it", HttpServletResponse.SC_GONE, response.getStatus());
193 response.close();
194
195 // test its still there
196 response = client.target(jobUrl2).request().get();
197 Thread.sleep(1000);
198 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
199 Assert.assertEquals("Wrong content of response", "content", response.readEntity(String.class));
200 response.close();
201
202 // delete and test delete
203 response = client.target(jobUrl2).request().delete();
204 Assert.assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
205 response.close();
206 response = client.target(jobUrl2).request().get();
207 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
208 response.close();
209 }
210
211
212 /**
213 * @tpTestDetails Test default value of resteasy.server.cache.maxsize. It should be 100. Try to store 110 items to cache. 10 items should be gone.
214 * @tpSince RESTEasy 3.0.16
215 */
216 @Test
217 @OperateOnDeployment(DEFAULT_DEPLOYMENT)
218 public void testAsynchMaxSizeDefault() throws Exception {
219 ResteasyClient client = initClient();
220
221 ArrayList<String> jobs = new ArrayList<>();
222 for (int i = 0; i < 110; i++) {
223 // test cache size
224 latch = new CountDownLatch(1);
225 Response response = client.target(generateURL("?asynch=true", DEFAULT_DEPLOYMENT)).request().post(Entity.entity("content", "text/plain"));
226 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
227 String jobUrl = response.getHeaderString(HttpHeaders.LOCATION);
228 logger.info(i + ": " + jobUrl);
229 jobs.add(jobUrl);
230 response.close();
231 Thread.sleep(50);
232 }
233
234 Thread.sleep(2000);
235
236 for (int i = 0; i < 10; i++) {
237 Response response = client.target(jobs.get(i)).request().get();
238 logger.info(i + " (" + jobs.get(i) + "): get " + response.getStatus() + ", expected: " + HttpServletResponse.SC_GONE);
239 Assert.assertEquals("Response should be gone, but server still remember it", HttpServletResponse.SC_GONE, response.getStatus());
240 response.close();
241 Thread.sleep(50);
242 }
243
244 for (int i = 10; i < 110; i++) {
245 Response response = client.target(jobs.get(i)).request().get();
246 logger.info(i + " (" + jobs.get(i) + "): get " + response.getStatus() + ", expected: " + HttpServletResponse.SC_OK);
247 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
248 Assert.assertEquals("Wrong content of response", "content", response.readEntity(String.class));
249 response.close();
250 Thread.sleep(50);
251 }
252 }
253
254 /**
255 * @tpTestDetails Set value of resteasy.server.cache.maxsize to 10. Try to restore item from cache.
256 * @tpSince RESTEasy 3.0.16
257 */
258 @Test
259 @OperateOnDeployment(TEN_MAX_DEPLOYMENT)
260 public void testAsynchTen() throws Exception {
261 ResteasyClient client = initClient();
262
263 // test readAndRemove
264 latch = new CountDownLatch(1);
265 Response response = client.target(generateURL("?asynch=true", TEN_MAX_DEPLOYMENT)).request().post(Entity.entity("content", "text/plain"));
266 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
267 String jobUrl2 = response.getHeaderString(HttpHeaders.LOCATION);
268 Assert.assertTrue("Request was not sent correctly", latch.await(3, TimeUnit.SECONDS));
269 response.close();
270 Thread.sleep(50);
271
272 // test its still there
273 response = client.target(jobUrl2).request().post(Entity.text(new String()));
274 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
275 Assert.assertEquals("Wrong content of response", "content", response.readEntity(String.class));
276 response.close();
277 Thread.sleep(50);
278
279 response = client.target(jobUrl2).request().get();
280 Thread.sleep(1000);
281 Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus());
282 response.close();
283 }
284
285 }
+0
-80
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/AsynchCounterTest.java less more
0 package org.jboss.resteasy.test.asynch;
1
2 import java.util.HashMap;
3 import java.util.Map;
4
5 import javax.servlet.http.HttpServletResponse;
6 import javax.ws.rs.client.Client;
7 import javax.ws.rs.client.ClientBuilder;
8 import javax.ws.rs.core.HttpHeaders;
9 import javax.ws.rs.core.Response;
10
11 import org.jboss.arquillian.container.test.api.Deployment;
12 import org.jboss.arquillian.container.test.api.RunAsClient;
13 import org.jboss.arquillian.junit.Arquillian;
14 import org.jboss.resteasy.test.asynch.resource.AsynchCounterResource;
15 import org.jboss.resteasy.utils.PortProviderUtil;
16 import org.jboss.resteasy.utils.TestUtil;
17 import org.jboss.shrinkwrap.api.Archive;
18 import org.jboss.shrinkwrap.api.spec.WebArchive;
19 import org.junit.AfterClass;
20 import org.junit.Assert;
21 import org.junit.BeforeClass;
22 import org.junit.Test;
23 import org.junit.runner.RunWith;
24
25 /**
26 * @tpSubChapter Asynchronous RESTEasy
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Tests use of SecureRandom to generate location job ids
29 * @tpSince RESTEasy 3.1.0.Final
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class AsynchCounterTest {
34
35 static Client client;
36
37 @BeforeClass
38 public static void setup() {
39 client = ClientBuilder.newClient();
40 }
41
42 @AfterClass
43 public static void close() {
44 client.close();
45 }
46
47 @Deployment
48 public static Archive<?> deploy() {
49 WebArchive war = TestUtil.prepareArchive(AsynchCounterTest.class.getSimpleName());
50 Map<String, String> contextParam = new HashMap<>();
51 contextParam.put("resteasy.async.job.service.enabled", "true");
52 contextParam.put("resteasy.secure.random.max.use", "2");
53 return TestUtil.finishContainerPrepare(war, contextParam, AsynchCounterResource.class);
54 }
55
56 private String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, AsynchCounterTest.class.getSimpleName());
58 }
59
60 /**
61 * @tpTestDetails Test that job ids are no longer consecutive
62 * @tpSince RESTEasy 3.1.0.Final
63 */
64 @Test
65 public void testAsynchCounter() throws Exception {
66
67 Response response = client.target(generateURL("?asynch=true")).request().get();
68 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
69 String jobUrl = response.getHeaderString(HttpHeaders.LOCATION);
70 int job1 = Integer.parseInt(jobUrl.substring(jobUrl.lastIndexOf('-') + 1));
71 response.close();
72 response = client.target(generateURL("?asynch=true")).request().get();
73 Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus());
74 jobUrl = response.getHeaderString(HttpHeaders.LOCATION);
75 int job2 = Integer.parseInt(jobUrl.substring(jobUrl.lastIndexOf('-') + 1));
76 Assert.assertTrue(job2 != job1 + 1);
77 response.close();
78 }
79 }
+0
-171
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/CallbackTest.java less more
0 package org.jboss.resteasy.test.asynch;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
6 import org.jboss.resteasy.test.asynch.resource.CallbackResource;
7 import org.jboss.resteasy.test.asynch.resource.CallbackExceptionThrowingStringBean;
8 import org.jboss.resteasy.test.asynch.resource.CallbackResourceBase;
9 import org.jboss.resteasy.test.asynch.resource.CallbackSecondSettingCompletionCallback;
10 import org.jboss.resteasy.test.asynch.resource.CallbackStringBean;
11 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletAsyncResponseBlockingQueue;
12 import org.jboss.resteasy.test.asynch.resource.CallbackTimeoutHandler;
13 import org.jboss.resteasy.test.asynch.resource.CallbackSettingCompletionCallback;
14 import org.jboss.resteasy.test.asynch.resource.CallbackStringBeanEntityProvider;
15 import org.jboss.resteasy.util.HttpResponseCodes;
16 import org.jboss.resteasy.utils.PortProviderUtil;
17 import org.jboss.resteasy.utils.TestUtil;
18 import org.jboss.shrinkwrap.api.Archive;
19 import org.jboss.shrinkwrap.api.spec.WebArchive;
20 import org.junit.AfterClass;
21 import org.junit.Assert;
22 import org.junit.BeforeClass;
23 import org.junit.Test;
24 import org.junit.runner.RunWith;
25
26 import javax.ws.rs.client.Client;
27 import javax.ws.rs.core.Response;
28 import java.io.IOException;
29 import java.util.concurrent.Future;
30
31 /**
32 * @tpSubChapter Asynchronous RESTEasy
33 * @tpChapter Integration tests
34 * @tpTestCaseDetails Test for async exception handling
35 * @tpSince RESTEasy 3.0.16
36 */
37 @RunWith(Arquillian.class)
38 @RunAsClient
39 public class CallbackTest {
40 public static Client client;
41
42 @BeforeClass
43 public static void initClient() {
44 client = new ResteasyClientBuilder().connectionPoolSize(10).build();
45 }
46
47 @AfterClass
48 public static void closeClient() {
49 client.close();
50 }
51
52 @Deployment
53 public static Archive<?> createTestArchive() {
54 WebArchive war = TestUtil.prepareArchive(CallbackTest.class.getSimpleName());
55 war.addClasses(CallbackResource.class,
56 CallbackExceptionThrowingStringBean.class,
57 CallbackTimeoutHandler.class,
58 CallbackResourceBase.class,
59 CallbackSecondSettingCompletionCallback.class,
60 CallbackSettingCompletionCallback.class,
61 CallbackStringBean.class,
62 CallbackStringBeanEntityProvider.class,
63 JaxrsAsyncServletAsyncResponseBlockingQueue.class);
64 war.addAsWebInfResource(AsyncPostProcessingTest.class.getPackage(), "CallbackTestWeb.xml", "web.xml");
65 return TestUtil.finishContainerPrepare(war, null, CallbackResource.class, CallbackStringBeanEntityProvider.class);
66 }
67
68 private String generateURL(String path) {
69 return PortProviderUtil.generateURL(path, CallbackTest.class.getSimpleName());
70 }
71
72 protected void invokeClear() {
73 Response response = client.target(generateURL("/resource/clear")).request().get();
74 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
75 response.close();
76 }
77
78 protected void invokeReset() {
79 Response response = client.target(generateURL("/resource/reset")).request().get();
80 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
81 response.close();
82 }
83
84 protected void assertString(Future<Response> future, String check) throws Exception {
85 Response response = future.get();
86 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
87 String entity = response.readEntity(String.class);
88 Assert.assertEquals(entity, check);
89
90 }
91
92 /**
93 * @tpTestDetails Argument contains exception in two callback classes
94 * @tpSince RESTEasy 3.0.16
95 */
96 @Test
97 public void argumentContainsExceptionInTwoCallbackClassesTest() throws Exception {
98 invokeClear();
99 invokeReset();
100 Future<Response> suspend = client.target(generateURL("/resource/suspend")).request().async().get();
101
102 Future<Response> register = client.target(generateURL("/resource/registerclasses?stage=0")).request().async().get();
103 assertString(register, CallbackResourceBase.FALSE);
104
105 Future<Response> exception = client.target(generateURL("/resource/exception?stage=1")).request().async().get();
106 Response response = exception.get();
107 Assert.assertEquals("Request return wrong response", CallbackResourceBase.TRUE, response.readEntity(String.class));
108
109 Response suspendResponse = suspend.get();
110 Assert.assertEquals(suspendResponse.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR);
111 suspendResponse.close();
112
113 Future<Response> error = client.target(generateURL("/resource/error")).request().async().get();
114 assertString(error, RuntimeException.class.getName());
115 error = client.target(generateURL("/resource/seconderror")).request().async().get();
116 assertString(error, RuntimeException.class.getName());
117 }
118
119 /**
120 * @tpTestDetails Argument contains exception in two callback instances
121 * @tpSince RESTEasy 3.0.16
122 */
123 @Test
124 public void argumentContainsExceptionInTwoCallbackInstancesTest() throws Exception {
125 invokeClear();
126 invokeReset();
127 Future<Response> suspend = client.target(generateURL("/resource/suspend")).request().async().get();
128
129 Future<Response> register = client.target(generateURL("/resource/registerobjects?stage=0")).request().async().get();
130 assertString(register, CallbackResourceBase.FALSE);
131
132 Future<Response> exception = client.target(generateURL("/resource/exception?stage=1")).request().async().get();
133 Response response = exception.get();
134 Assert.assertEquals("Request return wrong response", CallbackResourceBase.TRUE, response.readEntity(String.class));
135
136 Response suspendResponse = suspend.get();
137 Assert.assertEquals(suspendResponse.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR);
138 suspendResponse.close();
139
140 Future<Response> error = client.target(generateURL("/resource/error")).request().async().get();
141 assertString(error, RuntimeException.class.getName());
142 error = client.target(generateURL("/resource/seconderror")).request().async().get();
143 assertString(error, RuntimeException.class.getName());
144 }
145
146 /**
147 * @tpTestDetails Argument contains exception when sending IO exception
148 * @tpSince RESTEasy 3.0.16
149 */
150 @Test
151 public void argumentContainsExceptionWhenSendingIoExceptionTest() throws Exception {
152 invokeClear();
153 invokeReset();
154 Future<Response> suspend = client.target(generateURL("/resource/suspend")).request().async().get();
155
156 Future<Response> register = client.target(generateURL("/resource/register?stage=0")).request().async().get();
157 assertString(register, CallbackResourceBase.FALSE);
158
159 Future<Response> exception = client.target(generateURL("/resource/resumechecked?stage=1")).request().async().get();
160 Response response = exception.get();
161 Assert.assertEquals("Request return wrong response", CallbackResourceBase.TRUE, response.readEntity(String.class));
162
163 Response suspendResponse = suspend.get();
164 Assert.assertEquals(suspendResponse.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR);
165 suspendResponse.close();
166
167 Future<Response> error = client.target(generateURL("/resource/error")).request().async().get();
168 assertString(error, IOException.class.getName());
169 }
170 }
+0
-603
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/ComprehensiveJaxrsTest.java less more
0 package org.jboss.resteasy.test.asynch;
1
2 import java.io.ByteArrayInputStream;
3 import java.io.IOException;
4 import java.text.DateFormat;
5 import java.text.ParseException;
6 import java.text.SimpleDateFormat;
7 import java.util.Date;
8 import java.util.Locale;
9 import java.util.TimeZone;
10 import java.util.concurrent.Future;
11
12 import javax.ws.rs.client.AsyncInvoker;
13 import javax.ws.rs.client.Client;
14 import javax.ws.rs.client.ClientBuilder;
15 import javax.ws.rs.client.Entity;
16 import javax.ws.rs.client.WebTarget;
17 import javax.ws.rs.core.HttpHeaders;
18 import javax.ws.rs.core.MediaType;
19 import javax.ws.rs.core.Response;
20 import javax.ws.rs.core.Response.Status;
21
22 import org.apache.logging.log4j.LogManager;
23 import org.apache.logging.log4j.Logger;
24 import org.jboss.arquillian.container.test.api.Deployment;
25 import org.jboss.arquillian.container.test.api.RunAsClient;
26 import org.jboss.arquillian.junit.Arquillian;
27 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
28 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletApp;
29 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletAsyncResponseBlockingQueue;
30 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletJaxrsResource;
31 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletPrintingErrorHandler;
32 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletResource;
33 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletServiceUnavailableExceptionMapper;
34 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletTimeoutHandler;
35 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletXmlData;
36 import org.jboss.resteasy.util.HttpResponseCodes;
37 import org.jboss.resteasy.utils.PortProviderUtil;
38 import org.jboss.shrinkwrap.api.Archive;
39 import org.jboss.shrinkwrap.api.ShrinkWrap;
40 import org.jboss.shrinkwrap.api.spec.WebArchive;
41 import org.junit.After;
42 import org.junit.Assert;
43 import org.junit.Before;
44 import org.junit.Test;
45 import org.junit.runner.RunWith;
46
47 /**
48 * @tpSubChapter Asynchronous RESTEasy
49 * @tpChapter Integration tests
50 * @tpTestCaseDetails Test for asyncHttpServlet module. Check stage URL
51 * property.
52 * @tpSince RESTEasy 3.0.16
53 */
54 @RunWith(Arquillian.class)
55 @RunAsClient
56 public class ComprehensiveJaxrsTest
57 {
58 protected static final Logger logger = LogManager.getLogger(ComprehensiveJaxrsTest.class.getName());
59
60 @Deployment
61 public static Archive<?> createTestArchive()
62 {
63 WebArchive war = ShrinkWrap.create(WebArchive.class, AsyncServletTest.class.getSimpleName() + ".war");
64 war.addClasses(JaxrsAsyncServletXmlData.class, JaxrsAsyncServletAsyncResponseBlockingQueue.class,
65 JaxrsAsyncServletJaxrsResource.class, JaxrsAsyncServletApp.class,
66 JaxrsAsyncServletPrintingErrorHandler.class, JaxrsAsyncServletTimeoutHandler.class,
67 JaxrsAsyncServletResource.class, JaxrsAsyncServletServiceUnavailableExceptionMapper.class,
68 JaxrsAsyncServletXmlData.class);
69 war.addAsWebInfResource(AsyncPostProcessingTest.class.getPackage(), "JaxrsAsyncServletWeb.xml", "web.xml");
70 return war;
71 }
72
73 private String generateURL(String path)
74 {
75 return PortProviderUtil.generateURL(path, AsyncServletTest.class.getSimpleName());
76 }
77
78 protected Client client;
79
80 @Before
81 public void beforeTest()
82 {
83 client = new ResteasyClientBuilder().connectionPoolSize(10).build();
84 }
85
86 @After
87 public void afterTest()
88 {
89 client.close();
90 }
91
92 protected static String objectsToString(Object... objects)
93 {
94 StringBuilder sb = new StringBuilder();
95 for (Object o : objects)
96 {
97 sb.append(o).append(" ");
98 }
99 return sb.toString().trim();
100 }
101
102 public static void logMsg(Object... msg)
103 {
104 logger.info(objectsToString(msg));
105 }
106
107 protected static void checkEquals(Object expected, Object actual, Object... msg)
108 {
109 Assert.assertEquals(objectsToString(msg), expected, actual);
110 }
111
112 public static final TimeZone findTimeZoneInDate(String date)
113 {
114 StringBuilder sb = new StringBuilder();
115 StringBuilder dateBuilder = new StringBuilder(date.trim()).reverse();
116 int index = 0;
117 char c;
118 while ((c = dateBuilder.charAt(index++)) != ' ')
119 {
120 sb.append(c);
121 }
122 TimeZone timezone = TimeZone.getTimeZone(sb.reverse().toString());
123 return timezone;
124 }
125
126 public static final DateFormat createDateFormat(TimeZone timezone)
127 {
128 SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
129 sdf.setTimeZone(timezone);
130 return sdf;
131 }
132
133 private void suspendResumeTestInternal() throws Exception
134 {
135 invokeClear();
136 String expectedResponse = "Expected response";
137 Future<Response> suspend = invokeRequest("suspend");
138 Future<Response> resume = invokeRequest("resume?stage=0", expectedResponse);
139 checkString(resume, JaxrsAsyncServletResource.TRUE);
140 checkString(suspend, expectedResponse);
141 }
142
143 private void cancelVoidTestInternal() throws Exception
144 {
145 invokeClear();
146 Future<Response> suspend = invokeRequest("suspend");
147 Future<Response> cancel = invokeRequest("cancelvoid?stage=0");
148 checktStatus(getResponse(suspend), Status.SERVICE_UNAVAILABLE);
149 checkString(cancel, JaxrsAsyncServletResource.TRUE);
150 }
151
152 private void setTimeoutTestInternal() throws Exception
153 {
154 invokeClear();
155 logMsg("here 1");
156 Future<Response> suspend = invokeRequest("suspend");
157 logMsg("here 2");
158 Future<Response> setTimeout = invokeRequest("settimeout?stage=0", 200);
159 logMsg("here 3");
160 checktStatus(getResponse(setTimeout), Status.NO_CONTENT);
161 logMsg("here 4");
162 // WebApplication exception with 503 is caught by
163 // ServiceUnavailableExceptionMapper
164 Response fromMapper = getResponse(suspend);
165 logMsg("here 5");
166 checktStatus(fromMapper, Status.REQUEST_TIMEOUT);
167 String entity = fromMapper.readEntity(String.class);
168 checkContains(entity, 503);
169 logMsg("Found expected status 503");
170 }
171
172 private void cancelDateTestInternal() throws Exception
173 {
174 long milis = (System.currentTimeMillis() / 1000) * 1000 + 20000;
175 invokeClear();
176
177 Future<Response> suspend = invokeRequest("suspend");
178 Future<Response> cancel = invokeRequest("canceldate?stage=0", milis);
179 Response response = getResponse(suspend);
180 checktStatus(response, Status.SERVICE_UNAVAILABLE);
181 checkString(cancel, JaxrsAsyncServletResource.TRUE);
182 String header = response.getHeaderString(HttpHeaders.RETRY_AFTER);
183 TimeZone timezone = findTimeZoneInDate(header);
184 Date retry = null;
185 try
186 {
187 retry = createDateFormat(timezone).parse(header);
188 }
189 catch (ParseException e)
190 {
191 throw new Exception(e);
192 }
193 checkEquals(new Date(milis), retry, "Unexpected", HttpHeaders.RETRY_AFTER, "header value received",
194 retry.getTime(), "expected", milis);
195 logMsg("Found expected", HttpHeaders.RETRY_AFTER, "=", header);
196 }
197
198 private void cancelIntTestInternal() throws Exception
199 {
200 String seconds = "20";
201 invokeClear();
202
203 Future<Response> suspend = invokeRequest("suspend");
204 Future<Response> cancel = invokeRequest("cancelretry?stage=0", seconds);
205 Response response = getResponse(suspend);
206 checktStatus(response, Status.SERVICE_UNAVAILABLE);
207 checkString(cancel, JaxrsAsyncServletResource.TRUE);
208 String retry = response.getHeaderString(HttpHeaders.RETRY_AFTER);
209 checkEquals(seconds, retry, "Unexpected", HttpHeaders.RETRY_AFTER, "header value received", retry, "expected",
210 seconds);
211 logMsg("Found expected", HttpHeaders.RETRY_AFTER, "=", retry);
212 }
213
214 /**
215 * @tpTestDetails Complex test. Check stage=0 and stage=1 values.
216 * @tpSince RESTEasy 3.0.16
217 */
218
219 @Test
220 public void cancelVoidTest() throws Exception
221 {
222 cancelVoidTestInternal();
223 }
224
225 @Test
226 public void cancelVoidOnResumedTest() throws Exception
227 {
228 suspendResumeTestInternal();
229 Future<Response> cancel = invokeRequest("cancelvoid?stage=1");
230 checkString(cancel, JaxrsAsyncServletResource.FALSE);
231 }
232
233 @Test
234 public void cancelVoidOnCanceledTest() throws Exception
235 {
236 cancelVoidTestInternal();
237 Future<Response> cancel = invokeRequest("cancelvoid?stage=1");
238 checkString(cancel, JaxrsAsyncServletResource.TRUE);
239 }
240
241 @Test
242 public void resumeCanceledTest() throws Exception
243 {
244 cancelVoidTestInternal();
245 Future<Response> resumeCanceled = invokeRequest("resume?stage=1", "");
246 checkString(resumeCanceled, JaxrsAsyncServletResource.FALSE);
247 }
248
249 @Test
250 public void cancelIntTest() throws Exception
251 {
252 cancelIntTestInternal();
253 }
254
255 @Test
256 public void cancelIntOnResumedTest() throws Exception
257 {
258 suspendResumeTestInternal();
259 Future<Response> cancel = invokeRequest("cancelretry?stage=1", "20");
260 checkString(cancel, JaxrsAsyncServletResource.FALSE);
261 }
262
263 @Test
264 public void cancelIntOnCanceledTest() throws Exception
265 {
266 cancelVoidTestInternal();
267 Future<Response> cancel = invokeRequest("cancelretry?stage=1", "20");
268 checkString(cancel, JaxrsAsyncServletResource.TRUE);
269 }
270
271 @Test
272 public void resumeCanceledIntTest() throws Exception
273 {
274 cancelIntTestInternal();
275 Future<Response> resume = invokeRequest("resume?stage=1", "");
276 checkString(resume, JaxrsAsyncServletResource.FALSE);
277 }
278
279 @Test
280 public void cancelDateTest() throws Exception
281 {
282 cancelDateTestInternal();
283 }
284
285 @Test
286 public void cancelDateOnResumedTest() throws Exception
287 {
288 suspendResumeTestInternal();
289 Future<Response> cancel = invokeRequest("canceldate?stage=1", System.currentTimeMillis());
290 checkString(cancel, JaxrsAsyncServletResource.FALSE);
291 }
292
293 @Test
294 public void cancelDateOnCanceledTest() throws Exception
295 {
296 cancelVoidTestInternal();
297 Future<Response> cancel = invokeRequest("canceldate?stage=1", System.currentTimeMillis());
298 checkString(cancel, JaxrsAsyncServletResource.TRUE);
299 }
300
301 @Test
302 public void resumeCanceledDateTest() throws Exception
303 {
304 cancelDateTestInternal();
305 Future<Response> resumeResumed = invokeRequest("resume?stage=1", "");
306 checkString(resumeResumed, JaxrsAsyncServletResource.FALSE);
307 }
308
309 @Test
310 public void isCanceledWhenCanceledTest() throws Exception
311 {
312 cancelVoidTestInternal();
313 Future<Response> is = invokeRequest("iscanceled?stage=1");
314 checkString(is, JaxrsAsyncServletResource.TRUE);
315 }
316
317 @Test
318 public void isCanceledWhenSuspendedTest() throws Exception
319 {
320 invokeClear();
321 invokeRequest("suspend");
322 Future<Response> is = invokeRequest("iscanceled?stage=0");
323 checkString(is, JaxrsAsyncServletResource.FALSE);
324 }
325
326 @Test
327 public void isCanceledWhenResumedTest() throws Exception
328 {
329 suspendResumeTestInternal();
330 Future<Response> is = invokeRequest("iscanceled?stage=1");
331 checkString(is, JaxrsAsyncServletResource.FALSE);
332 }
333
334 @Test
335 public void isDoneWhenResumedTest() throws Exception
336 {
337 suspendResumeTestInternal();
338 Future<Response> is = invokeRequest("isdone?stage=1");
339 checkString(is, JaxrsAsyncServletResource.TRUE);
340 }
341
342 @Test
343 public void isDoneWhenSuspendedTest() throws Exception
344 {
345 invokeClear();
346 invokeRequest("suspend");
347 Future<Response> is = invokeRequest("isdone?stage=0");
348 checkString(is, JaxrsAsyncServletResource.FALSE);
349 }
350
351 @Test
352 public void isDoneWhenCanceledTest() throws Exception
353 {
354 cancelVoidTestInternal();
355 Future<Response> is = invokeRequest("isdone?stage=1");
356 checkString(is, JaxrsAsyncServletResource.TRUE);
357 }
358
359 @Test
360 public void isDoneWhenTimedOutTest() throws Exception
361 {
362 setTimeoutTestInternal();
363 Future<Response> is = invokeRequest("isdone?stage=1");
364 checkString(is, JaxrsAsyncServletResource.TRUE);
365 }
366
367 @Test
368 public void isSuspendedWhenSuspendedTest() throws Exception
369 {
370 invokeClear();
371 invokeRequest("suspend");
372 Future<Response> is = invokeRequest("issuspended?stage=0");
373 checkString(is, JaxrsAsyncServletResource.TRUE);
374 }
375
376 @Test
377 public void isSuspendedWhenCanceledTest() throws Exception
378 {
379 cancelVoidTestInternal();
380 Future<Response> is = invokeRequest("issuspended?stage=1");
381 checkString(is, JaxrsAsyncServletResource.FALSE);
382 }
383
384 @Test
385 public void isSuspendedWhenResumedTest() throws Exception
386 {
387 suspendResumeTestInternal();
388 Future<Response> is = invokeRequest("issuspended?stage=1");
389 checkString(is, JaxrsAsyncServletResource.FALSE);
390 }
391
392 @Test
393 public void suspendResumeTest() throws Exception
394 {
395 suspendResumeTestInternal();
396 }
397
398 @Test
399 public void resumeAnyJavaObjectInputStreamTest() throws Exception
400 {
401 invokeClear();
402 String expectedResponse = "Expected response";
403 Future<Response> suspend = invokeRequest("suspend");
404 Future<Response> resume = invokeRequest("resume?stage=0", new ByteArrayInputStream(expectedResponse.getBytes()));
405 checkString(resume, JaxrsAsyncServletResource.TRUE);
406 checkString(suspend, expectedResponse);
407 }
408
409 @Test
410 public void resumeResumedTest() throws Exception
411 {
412 suspendResumeTestInternal(); // resume & store
413 Future<Response> resumeResumed = invokeRequest("resume?stage=1", "");
414 checkString(resumeResumed, JaxrsAsyncServletResource.FALSE);
415 }
416
417 @Test
418 public void resumeWithCheckedExceptionTest() throws Exception
419 {
420 invokeClear();
421 Future<Response> suspend = invokeRequest("suspend");
422 Future<Response> resume = invokeRequest("resumechecked?stage=0");
423 checkString(resume, JaxrsAsyncServletResource.TRUE);
424 checkException(suspend, IOException.class);
425 }
426
427 @Test
428 public void resumeWithRuntimeExceptionTest() throws Exception
429 {
430 invokeClear();
431 Future<Response> suspend = invokeRequest("suspend");
432 Future<Response> resume = invokeRequest("resumeruntime?stage=0");
433 checkString(resume, JaxrsAsyncServletResource.TRUE);
434 checkException(suspend, RuntimeException.class);
435 }
436
437 @Test
438 public void resumeWithExceptionReturnsFalseWhenResumedTest() throws Exception
439 {
440 suspendResumeTestInternal();
441 Future<Response> resume = invokeRequest("resumechecked?stage=1");
442 checkString(resume, JaxrsAsyncServletResource.FALSE);
443 }
444
445 @Test
446 public void setTimeoutTest() throws Exception
447 {
448 setTimeoutTestInternal();
449 }
450
451 @Test
452 public void updateTimeoutTest() throws Exception
453 {
454 invokeClear();
455 Future<Response> suspend = invokeRequest("suspend");
456 Future<Response> setTimeout = invokeRequest("settimeout?stage=0", 600000);
457 checktStatus(getResponse(setTimeout), Status.NO_CONTENT);
458 checkFalse(suspend.isDone(), "Suspended AsyncResponse already received");
459 setTimeout = invokeRequest("settimeout?stage=1", 200);
460 checktStatus(getResponse(setTimeout), Status.NO_CONTENT);
461 // WebApplication exception with 503 is caught by
462 // ServiceUnavailableExceptionMapper
463 Response fromMapper = getResponse(suspend);
464 checktStatus(fromMapper, Status.REQUEST_TIMEOUT);
465 String entity = fromMapper.readEntity(String.class);
466 checkContains(entity, HttpResponseCodes.SC_SERVICE_UNAVAILABLE);
467 logMsg("Found expected status 503");
468 }
469
470 @Test
471 public void handleTimeOutWaitsForeverTest() throws Exception
472 {
473 String responseMsg = "handleTimeOutWaitsForeverTest";
474 invokeClear();
475 Future<Response> suspend = invokeRequest("suspend");
476 Future<Response> setTimeout = invokeRequest("timeouthandler?stage=0", 1);
477 Future<Response> resume = invokeRequest("resume?stage=1", responseMsg);
478 checktStatus(getResponse(setTimeout), Status.NO_CONTENT);
479 checkString(resume, JaxrsAsyncServletResource.TRUE);
480 checkString(suspend, responseMsg);
481 }
482
483 @Test
484 public void handleTimeoutCancelsTest() throws Exception
485 {
486 invokeClear();
487 Future<Response> suspend = invokeRequest("suspend");
488 Future<Response> setTimeout = invokeRequest("timeouthandler?stage=0", 2);
489 checktStatus(getResponse(setTimeout), Status.NO_CONTENT);
490 checktStatus(getResponse(suspend), Status.SERVICE_UNAVAILABLE);
491 Future<Response> resume = invokeRequest("issuspended?stage=1");
492 checkString(resume, JaxrsAsyncServletResource.FALSE);
493
494 }
495
496 @Test
497 public void handleTimeoutResumesTest() throws Exception
498 {
499 invokeClear();
500 Future<Response> suspend = invokeRequest("suspend");
501 Future<Response> setTimeout = invokeRequest("timeouthandler?stage=0", 3);
502 checktStatus(getResponse(setTimeout), Status.NO_CONTENT);
503 checkString(suspend, JaxrsAsyncServletResource.RESUMED);
504 Future<Response> resume = invokeRequest("issuspended?stage=1");
505 checkString(resume, JaxrsAsyncServletResource.FALSE);
506 }
507 // }
508
509 protected String getAbsoluteUrl()
510 {
511 return generateURL("/resource");
512 }
513
514 private void invokeClear() throws Exception
515 {
516 Response response = client.target(getAbsoluteUrl()).path("clear").request().get();
517 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
518 }
519
520 private Future<Response> invokeRequest(String resource)
521 {
522 AsyncInvoker async = createAsyncInvoker(resource);
523 Future<Response> future = async.get();
524 return future;
525 }
526
527 private <T> Future<Response> invokeRequest(String resource, T entity)
528 {
529 AsyncInvoker async = createAsyncInvoker(resource);
530 Future<Response> future = async.post(Entity.entity(entity, MediaType.TEXT_PLAIN_TYPE));
531 return future;
532 }
533
534 private WebTarget createWebTarget(String resource)
535 {
536 Client client = ClientBuilder.newClient();
537 WebTarget target = client.target(generateURL("/resource/" + resource));
538 return target;
539 }
540
541 private AsyncInvoker createAsyncInvoker(String resource)
542 {
543 WebTarget target = createWebTarget(resource);
544 AsyncInvoker async = target.request().async();
545 return async;
546 }
547
548 private static Response getResponse(Future<Response> future) throws Exception
549 {
550 Response response = future.get();
551 return response;
552 }
553
554 private static void checktStatus(Response response, Response.Status status) throws Exception
555 {
556 checkEquals(response.getStatus(), status.getStatusCode(), "Unexpected status code received", response.getStatus(),
557 "expected was", status);
558 logMsg("Found expected status", status);
559 }
560
561 private static void checkString(Future<Response> future, String check) throws Exception
562 {
563 Response response = getResponse(future);
564 checktStatus(response, Status.OK);
565 String content = response.readEntity(String.class);
566 checkEquals(check, content, "Unexpected response content", content);
567 logMsg("Found expected string", check);
568 }
569
570 private static void checkException(Future<Response> future, Class<? extends Throwable> e) throws Exception
571 {
572 String clazz = e.getName();
573 Response response = getResponse(future);
574 checktStatus(response, Response.Status.NOT_ACCEPTABLE);
575 checkContainsString(response.readEntity(String.class), clazz, clazz, "not thrown");
576 logMsg(clazz, "has been thrown as expected");
577 }
578
579 public static void checkContainsString(String string, String substring, Object... message) throws Exception
580 {
581 checkTrue(string.contains(substring), message);
582 }
583
584 public static <T> void checkContains(T text, T subtext, Object... message) throws Exception
585 {
586 checkContainsString(text.toString(), subtext.toString(), message);
587 }
588
589 public static void checkTrue(boolean condition, Object... message)
590 {
591 if (!condition)
592 {
593 Assert.fail(objectsToString(message));
594 }
595 }
596
597 public static void checkFalse(boolean condition, Object... message) throws Exception
598 {
599 checkTrue(!condition, message);
600 }
601
602 }
+0
-200
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/JaxrsAsyncServletTest.java less more
0 package org.jboss.resteasy.test.asynch;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.plugins.providers.jaxb.JAXBXmlRootElementProvider;
8 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletAsyncResponseBlockingQueue;
9 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletJaxrsResource;
10 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletApp;
11 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletResource;
12 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletTimeoutHandler;
13 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletServiceUnavailableExceptionMapper;
14 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletXmlData;
15 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletPrintingErrorHandler;
16 import org.jboss.resteasy.util.HttpResponseCodes;
17 import org.jboss.resteasy.utils.PortProviderUtil;
18 import org.jboss.resteasy.utils.TimeoutUtil;
19 import org.jboss.shrinkwrap.api.Archive;
20 import org.jboss.shrinkwrap.api.ShrinkWrap;
21 import org.jboss.shrinkwrap.api.spec.WebArchive;
22 import org.junit.After;
23 import org.junit.Assert;
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.junit.runner.RunWith;
27
28 import javax.ws.rs.ForbiddenException;
29 import javax.ws.rs.NotFoundException;
30 import javax.ws.rs.client.Client;
31 import javax.ws.rs.client.ClientBuilder;
32 import javax.ws.rs.core.Response;
33
34 /**
35 * @tpSubChapter Asynchronous RESTEasy
36 * @tpChapter Integration tests
37 * @tpTestCaseDetails Test for asyncHttpServlet module. Check cooperation during more requests and exception mapping.
38 * @tpSince RESTEasy 3.0.16
39 */
40 @RunWith(Arquillian.class)
41 @RunAsClient
42 public class JaxrsAsyncServletTest {
43
44 static ResteasyClient client;
45
46 @Before
47 public void init() {
48 client = new ResteasyClientBuilder().build();
49 }
50
51 @After
52 public void after() throws Exception {
53 client.close();
54 }
55
56 @Deployment
57 public static Archive<?> createTestArchive() {
58 WebArchive war = ShrinkWrap.create(WebArchive.class, AsyncServletTest.class.getSimpleName() + ".war");
59 war.addClasses(JaxrsAsyncServletXmlData.class, JaxrsAsyncServletAsyncResponseBlockingQueue.class, JaxrsAsyncServletJaxrsResource.class,
60 JaxrsAsyncServletApp.class,
61 JaxrsAsyncServletTimeoutHandler.class, JaxrsAsyncServletResource.class, JaxrsAsyncServletPrintingErrorHandler.class,
62 JaxrsAsyncServletServiceUnavailableExceptionMapper.class, JaxrsAsyncServletXmlData.class);
63 war.addAsWebInfResource(AsyncPostProcessingTest.class.getPackage(), "JaxrsAsyncServletWeb.xml", "web.xml");
64 return war;
65 }
66
67 private String generateURL(String path) {
68 return PortProviderUtil.generateURL(path, AsyncServletTest.class.getSimpleName());
69 }
70
71 /**
72 * @tpTestDetails Check ForbiddenException throwing during async request. Try to inject un-exist bean.
73 * @tpSince RESTEasy 3.0.16
74 */
75 @Test
76 public void testInjectionFailure() throws Exception {
77 long start = System.currentTimeMillis();
78 Client client = ClientBuilder.newClient();
79 Response response = client.target(generateURL("/jaxrs/injection-failure/abcd")).request().get();
80 Assert.assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
81 Assert.assertTrue("ForbiddenException was not thrown", response.readEntity(String.class).contains(NotFoundException.class.getName()));
82 long end = System.currentTimeMillis() - start;
83 Assert.assertTrue("Wrong time of request", end < 1000); // should take less than 1 second
84 response.close();
85 client.close();
86 }
87
88 /**
89 * @tpTestDetails Check ForbiddenException throwing during async request. No injection of some beans.
90 * @tpSince RESTEasy 3.0.16
91 */
92 @Test
93 public void testMethodFailure() throws Exception {
94 long start = System.currentTimeMillis();
95 Client client = ClientBuilder.newClient();
96 Response response = client.target(generateURL("/jaxrs/method-failure")).request().get();
97 Assert.assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
98 Assert.assertTrue("ForbiddenException was not thrown", response.readEntity(String.class).contains(ForbiddenException.class.getName()));
99 long end = System.currentTimeMillis() - start;
100 Assert.assertTrue("Wrong time of request", end < 1000); // should take less than 1 second
101 response.close();
102 client.close();
103 }
104
105 /**
106 * @tpTestDetails Try to get xml response.
107 * @tpSince RESTEasy 3.0.16
108 */
109 @Test
110 public void testAsync() throws Exception {
111 Client client = ClientBuilder.newClient();
112 long start = System.currentTimeMillis();
113 Response response = client.target(generateURL("/jaxrs")).request().get();
114 long end = System.currentTimeMillis() - start;
115 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
116 Assert.assertEquals("Wrong content of response", "hello", response.readEntity(String.class));
117 Assert.assertTrue("Wrong time of request", end < 1000); // should take less than 1 second
118 response.close();
119 client.close();
120 }
121
122 /**
123 * @tpTestDetails Check timeout exception
124 * @tpSince RESTEasy 3.0.16
125 */
126 @Test
127 public void testTimeout() throws Exception {
128 Client client = ClientBuilder.newClient();
129 Response response = client.target(generateURL("/jaxrs/timeout")).request().get();
130 Assert.assertEquals(HttpResponseCodes.SC_REQUEST_TIMEOUT, response.getStatus()); // exception mapper from another test overrides 503 to 408
131 response.close();
132 client.close();
133 }
134
135 /**
136 * @tpTestDetails Test cooperation between two requests. Use 408 HTTP status.
137 * @tpSince RESTEasy 3.0.16
138 */
139 @Test
140 public void testCancel() throws Exception {
141 Client client = ClientBuilder.newClient();
142 Response response = client.target(generateURL("/jaxrs/cancel")).request().get();
143 Assert.assertEquals(HttpResponseCodes.SC_SERVICE_UNAVAILABLE, response.getStatus());
144 response.close();
145
146 // It is possible, that thread created in JaxrsAsyncServletJaxrsResource.cancel method
147 // don't finish before next request is called. We need to wait some time and do this request again.
148 // Default timeout is 20s
149 boolean ok = false;
150 for (int i = 0; i < TimeoutUtil.adjust(20); i++) {
151 response = client.target(generateURL("/jaxrs/cancelled")).request().get();
152 int status = response.getStatus();
153 response.close();
154 if (status == HttpResponseCodes.SC_NO_CONTENT) {
155 ok = true;
156 break;
157 }
158 Thread.sleep(1000);
159 }
160 Assert.assertTrue("Response was not canceled correctly", ok);
161 client.close();
162 }
163
164 /**
165 * @tpTestDetails Test cooperation between two requests. Use 200 HTTP status.
166 * @tpSince RESTEasy 3.0.16
167 */
168 @Test
169 public void testResumeObject() throws Exception {
170 Client client = ClientBuilder.newClient();
171 client.register(JAXBXmlRootElementProvider.class);
172 long start = System.currentTimeMillis();
173 Response response = client.target(generateURL("/jaxrs/resume/object")).request().get();
174 long end = System.currentTimeMillis() - start;
175 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
176 Assert.assertEquals("Wrong content of response", "bill", response.readEntity(JaxrsAsyncServletXmlData.class).getName());
177 Assert.assertTrue("Wrong time of request", end < 1500);
178 response.close();
179 client.close();
180 }
181
182 /**
183 * @tpTestDetails Create response in new thread.
184 * @tpSince RESTEasy 3.0.16
185 */
186 @Test
187 public void testResumeObjectThread() throws Exception {
188 Client client = ClientBuilder.newClient();
189 client.register(JAXBXmlRootElementProvider.class);
190 long start = System.currentTimeMillis();
191 Response response = client.target(generateURL("/jaxrs/resume/object/thread")).request().get();
192 long end = System.currentTimeMillis() - start;
193 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
194 Assert.assertEquals("Wrong content of response", "bill", response.readEntity(JaxrsAsyncServletXmlData.class).getName());
195 Assert.assertTrue("Wrong time of request", end < 1000); // should take less than 1 second
196 response.close();
197 client.close();
198 }
199 }
+0
-94
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/JaxrsAsyncTest.java less more
0 package org.jboss.resteasy.test.asynch;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.asynch.resource.JaxrsAsyncResource;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.PortProviderUtil;
8 import org.jboss.resteasy.utils.TestUtil;
9 import org.jboss.shrinkwrap.api.Archive;
10 import org.jboss.shrinkwrap.api.spec.WebArchive;
11 import org.junit.Assert;
12 import org.junit.Test;
13 import org.junit.runner.RunWith;
14
15 import javax.ws.rs.client.Client;
16 import javax.ws.rs.client.ClientBuilder;
17 import javax.ws.rs.core.Response;
18
19 /**
20 * @tpSubChapter Asynchronous RESTEasy
21 * @tpChapter Integration tests
22 * @tpTestCaseDetails Basic asynchronous test. Resource creates new threads.
23 * @tpSince RESTEasy 3.0.16
24 */
25 @RunWith(Arquillian.class)
26 @RunAsClient
27 public class JaxrsAsyncTest {
28
29 @Deployment
30 public static Archive<?> deploy() {
31 WebArchive war = TestUtil.prepareArchive(JaxrsAsyncTest.class.getSimpleName());
32 return TestUtil.finishContainerPrepare(war, null, JaxrsAsyncResource.class);
33 }
34
35 private static String generateURL(String path) {
36 return PortProviderUtil.generateURL(path, JaxrsAsyncTest.class.getSimpleName());
37 }
38
39 /**
40 * @tpTestDetails Correct response excepted.
41 * @tpSince RESTEasy 3.0.16
42 */
43 @Test
44 public void testSuccess() throws Exception {
45 Client client = ClientBuilder.newClient();
46 Response response = client.target(generateURL("")).request().get();
47 Assert.assertEquals(200, response.getStatus());
48 Assert.assertEquals("Wrong response", "hello", response.readEntity(String.class));
49 response.close();
50 client.close();
51 }
52
53 /**
54 * @tpTestDetails Timeout exception should be thrown.
55 * @tpSince RESTEasy 3.0.16
56 */
57 @Test
58 public void testTimeout() throws Exception {
59 Client client = ClientBuilder.newClient();
60 Response response = client.target(generateURL("/timeout")).request().get();
61 Assert.assertEquals(503, response.getStatus());
62 response.close();
63 client.close();
64 }
65
66 /**
67 * @tpTestDetails Negative timeout value is set to response in end-point. Regression test for JBEAP-4695.
68 * @tpSince RESTEasy 3.0.17
69 */
70 @Test
71 public void testNegativeTimeout() throws Exception {
72 Client client = ClientBuilder.newClient();
73 Response response = client.target(generateURL("/negative")).request().get();
74 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
75 Assert.assertEquals("Wrong response", "hello", response.readEntity(String.class));
76 response.close();
77 client.close();
78 }
79
80 /**
81 * @tpTestDetails Zero timeout value is set to response in end-point. Regression test for JBEAP-4695.
82 * @tpSince RESTEasy 3.0.17
83 */
84 @Test
85 public void testZeroTimeout() throws Exception {
86 Client client = ClientBuilder.newClient();
87 Response response = client.target(generateURL("/zero")).request().get();
88 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
89 Assert.assertEquals("Wrong response", "hello", response.readEntity(String.class));
90 response.close();
91 client.close();
92 }
93 }
+0
-73
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/SuspendAnnotationTest.java less more
0 package org.jboss.resteasy.test.asynch;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.asynch.resource.LegacySuspendResource;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.PortProviderUtil;
8 import org.jboss.resteasy.utils.TestUtil;
9 import org.jboss.shrinkwrap.api.Archive;
10 import org.jboss.shrinkwrap.api.asset.StringAsset;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.Assert;
13 import org.junit.Test;
14 import org.junit.runner.RunWith;
15
16 import javax.ws.rs.client.Client;
17 import javax.ws.rs.client.ClientBuilder;
18 import javax.ws.rs.core.Response;
19
20
21 /**
22 * @tpSubChapter Asynchronous RESTEasy
23 * @tpChapter Integration tests
24 * @tpTestCaseDetails Basic asynchronous test for suspended response.
25 * Test for org.jboss.resteasy.annotations.Suspend annotation
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class SuspendAnnotationTest {
31
32 @Deployment
33 public static Archive<?> deploy() {
34 WebArchive war = TestUtil.prepareArchive(JaxrsAsyncTest.class.getSimpleName());
35 return TestUtil.finishContainerPrepare(war, null, LegacySuspendResource.class);
36 }
37
38 private static String generateURL(String path) {
39 return PortProviderUtil.generateURL(path, JaxrsAsyncTest.class.getSimpleName());
40 }
41
42 /**
43 * @tpTestDetails Server is able to answer in requested time.
44 * @tpSince RESTEasy 3.0.16
45 */
46 @Test
47 public void testPositive() throws Exception {
48 Client client = ClientBuilder.newClient();
49 Response response = client.target(generateURL("")).request().get();
50
51 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
52 Assert.assertEquals("Wrong content of response", "hello", response.readEntity(String.class));
53
54 response.close();
55 client.close();
56 }
57
58 /**
59 * @tpTestDetails Server is not able to answer in requested time.
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void testTimeout() throws Exception {
64 Client client = ClientBuilder.newClient();
65 Response response = client.target(generateURL("/timeout")).request().get();
66
67 Assert.assertEquals(HttpResponseCodes.SC_SERVICE_UNAVAILABLE, response.getStatus());
68
69 response.close();
70 client.close();
71 }
72 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/AsyncPostProcessingInterceptor.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.ext.Provider;
3
4 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
5 import org.jboss.resteasy.core.ServerResponse;
6 import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
7
8 @Provider
9 @ServerInterceptor
10 public class AsyncPostProcessingInterceptor implements PostProcessInterceptor {
11 public static volatile boolean called;
12
13 @Override
14 public void postProcess(ServerResponse response) {
15 called = true;
16 }
17 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/AsyncPostProcessingMsgBodyWriterInterceptor.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import java.io.IOException;
3
4 import javax.ws.rs.WebApplicationException;
5 import javax.ws.rs.ext.Provider;
6
7 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
8 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
9 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
10
11 @Provider
12 @ServerInterceptor
13 public class AsyncPostProcessingMsgBodyWriterInterceptor implements MessageBodyWriterInterceptor {
14 public static volatile boolean called;
15
16 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
17 called = true;
18 context.proceed();
19 }
20 }
+0
-47
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/AsyncPostProcessingResource.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5
6 import org.jboss.logging.Logger;
7 import org.jboss.resteasy.annotations.Suspend;
8 import org.jboss.resteasy.spi.AsynchronousResponse;
9
10 @Path("/")
11 public class AsyncPostProcessingResource {
12
13 private static Logger logger = Logger.getLogger(AsyncPostProcessingResource.class);
14
15 @GET
16 @Path("sync")
17 public Response sync() {
18 return Response.ok().entity("sync").build();
19 }
20
21 @GET
22 @Path("async/delay")
23 public void asyncDelay(@Suspend(10000) final AsynchronousResponse response) throws Exception {
24 Thread t = new Thread() {
25 @Override
26 public void run() {
27 try {
28 Thread.sleep(5000);
29 Response jaxrs = Response.ok("async/delay").build();
30 response.setResponse(jaxrs);
31 } catch (Exception e) {
32 logger.info("Error: " + e.getStackTrace());
33 }
34 }
35 };
36 t.start();
37 }
38
39 @GET
40 @Path("async/nodelay")
41 public void asyncNoDelay(@Suspend(10000) final AsynchronousResponse response) throws Exception {
42 Response jaxrs = Response.ok("async/nodelay").build();
43 response.setResponse(jaxrs);
44 }
45
46 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/AsyncServletResource.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.annotations.Suspend;
4 import org.jboss.resteasy.spi.AsynchronousResponse;
5
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.Response;
11 import java.io.PrintWriter;
12 import java.io.StringWriter;
13
14 /**
15 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
16 * @version $Revision: 1 $
17 */
18 @Path("/async")
19 public class AsyncServletResource {
20 @GET
21 @Produces("text/plain")
22 public void get(@Suspend(2000) final AsynchronousResponse response) {
23 Thread t = new Thread() {
24 private Logger log = Logger.getLogger(AsyncServletResource.class);
25 @Override
26 public void run() {
27 try {
28 Thread.sleep(100);
29 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
30 response.setResponse(jaxrs);
31 } catch (Exception e) {
32 StringWriter errors = new StringWriter();
33 e.printStackTrace(new PrintWriter(errors));
34 log.error(errors.toString());
35 }
36 }
37 };
38 t.start();
39 }
40
41 @GET
42 @Path("timeout")
43 @Produces("text/plain")
44 public void timeout(@Suspend(10) final AsynchronousResponse response) {
45 Thread t = new Thread() {
46 private Logger log = Logger.getLogger(AsyncServletResource.class);
47 @Override
48 public void run() {
49 try {
50 Thread.sleep(100000);
51 Response jaxrs = Response.ok("goodbye").type(MediaType.TEXT_PLAIN).build();
52 response.setResponse(jaxrs);
53 } catch (Exception e) {
54 StringWriter errors = new StringWriter();
55 e.printStackTrace(new PrintWriter(errors));
56 log.error(errors.toString());
57 }
58 }
59 };
60 t.start();
61 }
62 }
+0
-51
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/AsynchBasicResource.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import org.jboss.resteasy.logging.Logger;
3 import org.jboss.resteasy.test.asynch.AsynchBasicTest;
4 import org.junit.Assert;
5
6 import javax.servlet.ServletConfig;
7 import javax.servlet.ServletContext;
8 import javax.ws.rs.POST;
9 import javax.ws.rs.PUT;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.core.Context;
12
13 @Path("/")
14 public class AsynchBasicResource {
15
16 private static Logger logger = Logger.getLogger(AsynchBasicResource.class);
17
18 @Context
19 private ServletConfig config;
20
21 @Context
22 private ServletContext context;
23
24 @POST
25 public String post(String content) throws Exception {
26 logger.info("in post");
27 Assert.assertNotNull(config);
28 Assert.assertNotNull(context);
29 logger.info("Asserts passed");
30 config.getServletContext();
31 context.getMajorVersion();
32 logger.info("Called injected passed");
33
34 Thread.sleep(1500);
35 AsynchBasicTest.latch.countDown();
36
37 return content;
38 }
39
40 @PUT
41 public void put(String content) throws Exception {
42 Assert.assertNotNull(config);
43 Assert.assertNotNull(context);
44 config.getServletContext();
45 context.getMajorVersion();
46 Assert.assertEquals("content", content);
47 Thread.sleep(500);
48 AsynchBasicTest.latch.countDown();
49 }
50 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/AsynchCounterResource.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 @Path("/")
6 public class AsynchCounterResource {
7
8 @GET
9 public String get() throws Exception {
10 Thread.sleep(1500);
11 return "get";
12 }
13 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/CallbackExceptionThrowingStringBean.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import java.io.IOException;
3
4 public class CallbackExceptionThrowingStringBean extends CallbackStringBean {
5
6 public CallbackExceptionThrowingStringBean(final String header) {
7 super(header);
8 }
9
10 @Override
11 public String get() {
12 throw new RuntimeException(new IOException(super.get()));
13 }
14
15 }
+0
-170
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/CallbackResource.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.QueryParam;
5 import javax.ws.rs.container.AsyncResponse;
6
7 @Path("resource")
8 public class CallbackResource extends CallbackResourceBase {
9
10 @GET
11 @Path("register")
12 public String registerObject(@QueryParam("stage") String stage) {
13 AsyncResponse async = takeAsyncResponse(stage);
14 boolean b = async.register(new CallbackSettingCompletionCallback()).isEmpty();
15 addResponse(async, stage);
16 return b ? TRUE : FALSE;
17 }
18
19 @GET
20 @Path("registerclass")
21 public String registerClass(@QueryParam("stage") String stage) {
22 AsyncResponse async = takeAsyncResponse(stage);
23 boolean b = async.register(CallbackSettingCompletionCallback.class).isEmpty();
24 addResponse(async, stage);
25 return b ? TRUE : FALSE;
26 }
27
28 @GET
29 @Path("registerobjects")
30 public String registerObjectObject(@QueryParam("stage") String stage) {
31 AsyncResponse async = takeAsyncResponse(stage);
32 boolean b = async.register(new CallbackSettingCompletionCallback(),
33 new CallbackSecondSettingCompletionCallback()).isEmpty();
34 addResponse(async, stage);
35 return b ? TRUE : FALSE;
36 }
37
38 @GET
39 @Path("registerclasses")
40 public String registerClasses(@QueryParam("stage") String stage) {
41 AsyncResponse async = takeAsyncResponse(stage);
42 boolean b = async.register(CallbackSettingCompletionCallback.class,
43 CallbackSecondSettingCompletionCallback.class).isEmpty();
44 addResponse(async, stage);
45 return b ? TRUE : FALSE;
46 }
47
48 @GET
49 @Path("registerthrows")
50 public String registerObjectThrowsNpe(@QueryParam("stage") String stage) {
51 AsyncResponse async = takeAsyncResponse(stage);
52 try {
53 CallbackSettingCompletionCallback callback = null;
54 async.register(callback);
55 } catch (NullPointerException e) {
56 return TRUE;
57 } catch (Exception e) {
58 return "Threw " + e.getClass().getName();
59 }
60 return FALSE;
61 }
62
63 @GET
64 @Path("registerclassthrows")
65 public String registerClassThrowsNpe(@QueryParam("stage") String stage) {
66 AsyncResponse async = takeAsyncResponse(stage);
67 try {
68 Class<CallbackSettingCompletionCallback> callback = null;
69 async.register(callback);
70 } catch (NullPointerException e) {
71 return TRUE;
72 } catch (Exception e) {
73 return "Threw " + e.getClass().getName();
74 }
75 return FALSE;
76 }
77
78 @GET
79 @Path("registerobjectsthrows1")
80 public String registerObjectsThrowsNpe1(@QueryParam("stage") String stage) {
81 AsyncResponse async = takeAsyncResponse(stage);
82 try {
83 CallbackSettingCompletionCallback callback = null;
84 async.register(callback, new CallbackSecondSettingCompletionCallback());
85 } catch (NullPointerException e) {
86 return TRUE;
87 } catch (Exception e) {
88 return "Threw " + e.getClass().getName();
89 }
90 return FALSE;
91 }
92
93 @GET
94 @Path("registerobjectsthrows2")
95 public String registerObjectsThrowsNpe2(@QueryParam("stage") String stage) {
96 AsyncResponse async = takeAsyncResponse(stage);
97 try {
98 CallbackSecondSettingCompletionCallback callback = null;
99 async.register(new CallbackSettingCompletionCallback(), callback);
100 } catch (NullPointerException e) {
101 return TRUE;
102 } catch (Exception e) {
103 return "Threw " + e.getClass().getName();
104 }
105 return FALSE;
106 }
107
108 @GET
109 @Path("registerclassesthrows1")
110 public String registerClassesThrowsNpe1(@QueryParam("stage") String stage) {
111 AsyncResponse async = takeAsyncResponse(stage);
112 try {
113 Class<CallbackSettingCompletionCallback> callback = null;
114 async.register(callback, CallbackSecondSettingCompletionCallback.class);
115 } catch (NullPointerException e) {
116 return TRUE;
117 } catch (Exception e) {
118 return "Threw " + e.getClass().getName();
119 }
120 return FALSE;
121 }
122
123 @GET
124 @Path("registerclassesthrows2")
125 public String registerClassesThrowsNpe2(@QueryParam("stage") String stage) {
126 AsyncResponse async = takeAsyncResponse(stage);
127 try {
128 Class<CallbackSecondSettingCompletionCallback> callback = null;
129 async.register(CallbackSettingCompletionCallback.class, callback);
130 } catch (NullPointerException e) {
131 return TRUE;
132 } catch (Exception e) {
133 return "Threw " + e.getClass().getName();
134 }
135 return FALSE;
136 }
137
138 @GET
139 @Path("exception")
140 public String throwExceptionOnAsyncResponse(
141 @QueryParam("stage") String stage) {
142 AsyncResponse async = takeAsyncResponse(stage);
143 boolean b = async.resume(new CallbackExceptionThrowingStringBean(
144 "throw exception"));
145 addResponse(async, stage);
146 return b ? TRUE : FALSE;
147 }
148
149 @GET
150 @Path("error")
151 public String getErrorValue() {
152 String name = CallbackSettingCompletionCallback.getLastThrowableName();
153 return name;
154 }
155
156 @GET
157 @Path("seconderror")
158 public String getSecondErrorValue() {
159 String name = CallbackSecondSettingCompletionCallback.getLastThrowableName();
160 return name;
161 }
162
163 @GET
164 @Path("reset")
165 public void resetErrorValue() {
166 CallbackSettingCompletionCallback.resetLastThrowableName();
167 CallbackSecondSettingCompletionCallback.resetLastThrowableName();
168 }
169 }
+0
-186
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/CallbackResourceBase.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.QueryParam;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.container.AsyncResponse;
8 import javax.ws.rs.container.Suspended;
9 import javax.ws.rs.core.Response;
10 import javax.ws.rs.core.Response.ResponseBuilder;
11 import javax.ws.rs.core.Response.Status;
12 import java.io.IOException;
13 import java.util.Date;
14 import java.util.concurrent.TimeUnit;
15
16 @Path("resource")
17 public class CallbackResourceBase {
18
19 public static final String RESUMED = "Response resumed";
20 public static final String ISE = "Illegal State Exception Thrown";
21 public static final String NOE = "No Exception Thrown";
22 public static final String FALSE = "A method returned false";
23 public static final String TRUE = "A method return true";
24
25 private static final JaxrsAsyncServletAsyncResponseBlockingQueue[] stage = {
26 new JaxrsAsyncServletAsyncResponseBlockingQueue(1),
27 new JaxrsAsyncServletAsyncResponseBlockingQueue(1),
28 new JaxrsAsyncServletAsyncResponseBlockingQueue(1)};
29
30 @GET
31 @Path("suspend")
32 public void suspend(@Suspended AsyncResponse asyncResponse) {
33 stage[0].add(asyncResponse);
34 }
35
36 @GET
37 @Path("clear")
38 public void clear() {
39 for (int i = 0; i != stage.length; i++) {
40 stage[i].clear();
41 }
42 }
43
44 @GET
45 @Path("cancelvoid")
46 public String cancel(@QueryParam("stage") String stage) {
47 AsyncResponse response = takeAsyncResponse(stage);
48 boolean ret = response.cancel();
49 // Invoking a cancel(...) method multiple times to cancel request
50 // processing has the same effect as canceling the request processing
51 // only once.
52 ret &= response.cancel();
53 addResponse(response, stage);
54 return ret ? TRUE : FALSE;
55 }
56
57 @POST
58 @Path("cancelretry")
59 public String cancelretry(@QueryParam("stage") String stage,
60 String sRetryAfter) {
61 AsyncResponse response = takeAsyncResponse(stage);
62 int retryAfter = Integer.parseInt(sRetryAfter);
63 boolean b = response.cancel(retryAfter);
64 // Invoking a cancel(...) method multiple times to cancel request
65 // processing has the same effect as canceling the request processing
66 // only once.
67 b &= response.cancel(retryAfter * 2);
68 addResponse(response, stage);
69 return b ? TRUE : FALSE;
70 }
71
72 @POST
73 @Path("canceldate")
74 public String cancelDate(@QueryParam("stage") String stage, String sRetryAfter) {
75 AsyncResponse response = takeAsyncResponse(stage);
76 long retryAfter = Long.parseLong(sRetryAfter);
77 boolean b = response.cancel(new Date(retryAfter));
78 b &= response.cancel(new Date(retryAfter + 20000));
79 addResponse(response, stage);
80 return b ? TRUE : FALSE;
81 }
82
83 @GET
84 @Path("iscanceled")
85 public String isCanceled(@QueryParam("stage") String stage) {
86 AsyncResponse response = takeAsyncResponse(stage);
87 boolean is = response.isCancelled();
88 addResponse(response, stage);
89 return is ? TRUE : FALSE;
90 }
91
92 @GET
93 @Path("isdone")
94 public String isDone(@QueryParam("stage") String stage) {
95 AsyncResponse response = takeAsyncResponse(stage);
96 boolean is = response.isDone();
97 addResponse(response, stage);
98 return is ? TRUE : FALSE;
99 }
100
101 @GET
102 @Path("issuspended")
103 public String isSuspended(@QueryParam("stage") String stage) {
104 AsyncResponse response = takeAsyncResponse(stage);
105 boolean is = response.isSuspended();
106 addResponse(response, stage);
107 return is ? TRUE : FALSE;
108 }
109
110 @POST
111 @Path("resume")
112 public String resume(@QueryParam("stage") String stage, String response) {
113 AsyncResponse async = takeAsyncResponse(stage);
114 boolean b = resume(async, response);
115 addResponse(async, stage);
116 return b ? TRUE : FALSE;
117 }
118
119 @GET
120 @Path("resumechecked")
121 public String resumeWithCheckedException(@QueryParam("stage") String stage) {
122 AsyncResponse async = takeAsyncResponse(stage);
123 boolean b = async.resume(new IOException(RESUMED));
124 addResponse(async, stage);
125 return b ? TRUE : FALSE;
126 }
127
128 @GET
129 @Path("resumeruntime")
130 public String resumeWithRuntimeException(@QueryParam("stage") String stage) {
131 AsyncResponse async = takeAsyncResponse(stage);
132 boolean b = async.resume(new RuntimeException(RESUMED));
133 addResponse(async, stage);
134 return b ? TRUE : FALSE;
135 }
136
137 @POST
138 @Path("settimeout")
139 public void setTimeOut(@QueryParam("stage") String stage, String milis) {
140 AsyncResponse async = takeAsyncResponse(stage);
141 async.setTimeout(Long.parseLong(milis), TimeUnit.MILLISECONDS);
142 addResponse(async, stage);
143 }
144
145 @POST
146 @Path("timeouthandler")
147 public void setTimeoutHandler(@QueryParam("stage") String stage, int handlerValue) {
148 CallbackTimeoutHandler handler = new CallbackTimeoutHandler(handlerValue);
149 AsyncResponse async = takeAsyncResponse(stage);
150 async.setTimeoutHandler(handler);
151 async.setTimeout(200L, TimeUnit.MILLISECONDS);
152 addResponse(async, stage);
153 }
154
155 protected static AsyncResponse takeAsyncResponse(String stageId) {
156 return takeAsyncResponse(Integer.parseInt(stageId));
157 }
158
159 protected static AsyncResponse takeAsyncResponse(int stageId) {
160 final ResponseBuilder error = createErrorResponseBuilder();
161 AsyncResponse asyncResponse = null;
162 try {
163 asyncResponse = stage[stageId].take();
164 } catch (InterruptedException e) {
165 throw new WebApplicationException(error.entity(
166 "ArrayBlockingQueue#take").build());
167 }
168 return asyncResponse;
169 }
170
171 protected static final void addResponse(AsyncResponse response, String stageId) {
172 int id = Integer.parseInt(stageId) + 1;
173 if (id != stage.length) {
174 stage[id].add(response);
175 }
176 }
177
178 protected static boolean resume(AsyncResponse takenResponse, Object response) {
179 return takenResponse.resume(response);
180 }
181
182 protected static ResponseBuilder createErrorResponseBuilder() {
183 return Response.status(Status.EXPECTATION_FAILED);
184 }
185 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/CallbackSecondSettingCompletionCallback.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.container.CompletionCallback;
3
4 public class CallbackSecondSettingCompletionCallback implements CompletionCallback {
5
6 private static String throwableName;
7 public static final String NULL = "NULL";
8 public static final String OUTOFORDER = "CallbackSecondSettingCompletionCallback is not second";
9 public static final String NONAME = "No name has been set yet";
10
11 @Override
12 public void onComplete(Throwable throwable) {
13 throwableName = throwable == null ? NULL : throwable.getClass()
14 .getName();
15 if (!CallbackSettingCompletionCallback.getLastThrowableName().equals(throwableName)) {
16 throwableName = throwableName + OUTOFORDER;
17 }
18 }
19
20 public static final String getLastThrowableName() {
21 return throwableName;
22 }
23
24 public static final void resetLastThrowableName() {
25 throwableName = NONAME;
26 }
27
28 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/CallbackSettingCompletionCallback.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.container.CompletionCallback;
3
4 public class CallbackSettingCompletionCallback implements CompletionCallback {
5
6 private static String throwableName;
7 public static final String NULL = "NULL";
8 public static final String NONAME = "No name has been set yet";
9
10 @Override
11 public void onComplete(Throwable throwable) {
12 throwableName = throwable == null ? NULL : throwable.getClass()
13 .getName();
14 }
15
16 public static final String getLastThrowableName() {
17 return throwableName;
18 }
19
20 public static final void resetLastThrowableName() {
21 throwableName = NONAME;
22 }
23
24 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/CallbackStringBean.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 public class CallbackStringBean {
3 private String header;
4
5 public String get() {
6 return header;
7 }
8
9 public void set(String header) {
10 this.header = header;
11 }
12
13 @Override
14 public String toString() {
15 return "CallbackStringBean. To get a value, use rather #get() method.";
16 }
17
18 public CallbackStringBean(final String header) {
19 super();
20 this.header = header;
21 }
22 }
+0
-71
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/CallbackStringBeanEntityProvider.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import javax.ws.rs.ext.MessageBodyReader;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import javax.ws.rs.ext.Provider;
8 import java.io.BufferedReader;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.io.OutputStream;
13 import java.io.Reader;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16
17 @Provider
18 public class CallbackStringBeanEntityProvider implements MessageBodyReader<CallbackStringBean>,
19 MessageBodyWriter<CallbackStringBean> {
20
21 @Override
22 public boolean isWriteable(Class<?> type, Type genericType,
23 Annotation[] annotations, MediaType mediaType) {
24 return CallbackStringBean.class.isAssignableFrom(type);
25 }
26
27 @Override
28 public long getSize(CallbackStringBean t, Class<?> type, Type genericType,
29 Annotation[] annotations, MediaType mediaType) {
30 return t.get().length();
31 }
32
33 @Override
34 public void writeTo(CallbackStringBean t, Class<?> type, Type genericType,
35 Annotation[] annotations, MediaType mediaType,
36 MultivaluedMap<String, Object> httpHeaders,
37 OutputStream entityStream) throws IOException,
38 WebApplicationException {
39 entityStream.write(t.get().getBytes());
40 }
41
42 @Override
43 public boolean isReadable(Class<?> type, Type genericType,
44 Annotation[] annotations, MediaType mediaType) {
45 return isWriteable(type, genericType, annotations, mediaType);
46 }
47
48 @Override
49 public CallbackStringBean readFrom(Class<CallbackStringBean> type, Type genericType,
50 Annotation[] annotations, MediaType mediaType,
51 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
52 throws IOException, WebApplicationException {
53 String stream = readFromStream(entityStream);
54 CallbackStringBean bean = new CallbackStringBean(stream);
55 return bean;
56 }
57
58 public static final String readFromStream(InputStream stream) throws IOException {
59 InputStreamReader isr = new InputStreamReader(stream);
60 return readFromReader(isr);
61 }
62
63 public static final String readFromReader(Reader reader) throws IOException {
64 BufferedReader br = new BufferedReader(reader);
65 String entity = br.readLine();
66 br.close();
67 return entity;
68 }
69
70 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/CallbackTimeoutHandler.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.container.AsyncResponse;
3 import javax.ws.rs.container.TimeoutHandler;
4 import java.util.concurrent.TimeUnit;
5
6 public class CallbackTimeoutHandler implements TimeoutHandler {
7
8 private int function = 0;
9
10 public CallbackTimeoutHandler(final int function) {
11 super();
12 this.function = function;
13 }
14
15 @Override
16 public void handleTimeout(AsyncResponse asyncResponse) {
17 switch (function) {
18 case 1:
19 asyncResponse.setTimeout(200, TimeUnit.MILLISECONDS);
20 break;
21 case 2:
22 asyncResponse.cancel();
23 break;
24 case 3:
25 asyncResponse.resume(CallbackResource.RESUMED);
26 break;
27 }
28 }
29
30 }
+0
-114
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/JaxrsAsyncResource.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.container.AsyncResponse;
8 import javax.ws.rs.container.Suspended;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.Response;
11 import java.io.PrintWriter;
12 import java.io.StringWriter;
13 import java.util.concurrent.TimeUnit;
14
15 @Path("/")
16 public class JaxrsAsyncResource {
17 @GET
18 @Produces("text/plain")
19 public void get(@Suspended final AsyncResponse response) {
20 response.setTimeout(10000, TimeUnit.MILLISECONDS);
21 Thread t = new Thread() {
22 private Logger logger = Logger.getLogger(JaxrsAsyncResource.class);
23
24 @Override
25 public void run() {
26 try {
27 logger.info("Get thread started.");
28 Thread.sleep(100);
29 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
30 response.resume(jaxrs);
31 } catch (Exception e) {
32 StringWriter errors = new StringWriter();
33 e.printStackTrace(new PrintWriter(errors));
34 logger.error(errors.toString());
35 }
36 }
37 };
38 t.start();
39 }
40
41 @GET
42 @Path("timeout")
43 @Produces("text/plain")
44 public void timeout(@Suspended final AsyncResponse response) {
45 response.setTimeout(100, TimeUnit.MILLISECONDS);
46 Thread t = new Thread() {
47 private Logger logger = Logger.getLogger(JaxrsAsyncResource.class);
48
49 @Override
50 public void run() {
51 try {
52 logger.info("Timeout thread started.");
53 Thread.sleep(1000);
54 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
55 response.resume(jaxrs);
56 } catch (Exception e) {
57 StringWriter errors = new StringWriter();
58 e.printStackTrace(new PrintWriter(errors));
59 logger.error(errors.toString());
60 }
61 }
62 };
63 t.start();
64 }
65
66 @GET
67 @Path("negative")
68 @Produces("text/plain")
69 public void negative(@Suspended final AsyncResponse response) {
70 response.setTimeout(-1, TimeUnit.MILLISECONDS);
71 Thread t = new Thread() {
72 private Logger logger = Logger.getLogger(JaxrsAsyncResource.class);
73 @Override
74 public void run() {
75 try {
76 logger.info("Started");
77 Thread.sleep(1000);
78 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
79 response.resume(jaxrs);
80 } catch (Exception e) {
81 StringWriter errors = new StringWriter();
82 e.printStackTrace(new PrintWriter(errors));
83 logger.error(errors.toString());
84 }
85 }
86 };
87 t.start();
88 }
89
90 @GET
91 @Path("zero")
92 @Produces("text/plain")
93 public void zero(@Suspended final AsyncResponse response) {
94 response.setTimeout(0, TimeUnit.MILLISECONDS);
95 Thread t = new Thread() {
96 private Logger logger = Logger.getLogger(JaxrsAsyncResource.class);
97 @Override
98 public void run() {
99 try {
100 logger.info("Started");
101 Thread.sleep(1000);
102 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
103 response.resume(jaxrs);
104 } catch (Exception e) {
105 StringWriter errors = new StringWriter();
106 e.printStackTrace(new PrintWriter(errors));
107 logger.error(errors.toString());
108 }
109 }
110 };
111 t.start();
112 }
113 }
+0
-32
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/JaxrsAsyncServletApp.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.core.Application;
3 import java.util.HashSet;
4 import java.util.Set;
5
6 /**
7 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
8 * @version $Revision: 1 $
9 */
10 public class JaxrsAsyncServletApp extends Application {
11 private Set<Object> singletons = new HashSet<Object>();
12 private Set<Class<?>> classes = new HashSet<Class<?>>();
13
14 public JaxrsAsyncServletApp() {
15 classes.add(JaxrsAsyncServletResource.class);
16 classes.add(JaxrsAsyncServletServiceUnavailableExceptionMapper.class);
17 classes.add(JaxrsAsyncServletPrintingErrorHandler.class);
18 singletons.add(new JaxrsAsyncServletJaxrsResource());
19 }
20
21 @Override
22 public Set<Class<?>> getClasses() {
23 return classes;
24 }
25
26 @Override
27 public Set<Object> getSingletons() {
28 return singletons;
29 }
30
31 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/JaxrsAsyncServletAsyncResponseBlockingQueue.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.container.AsyncResponse;
3 import java.util.concurrent.ArrayBlockingQueue;
4
5 public class JaxrsAsyncServletAsyncResponseBlockingQueue extends ArrayBlockingQueue<AsyncResponse> {
6
7 private static final long serialVersionUID = -2445906740359075621L;
8
9 public JaxrsAsyncServletAsyncResponseBlockingQueue(final int capacity) {
10 super(capacity);
11 }
12
13 }
+0
-161
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/JaxrsAsyncServletJaxrsResource.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2
3 import org.jboss.logging.Logger;
4
5 import javax.ws.rs.ForbiddenException;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.PUT;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.PathParam;
10 import javax.ws.rs.Produces;
11 import javax.ws.rs.container.AsyncResponse;
12 import javax.ws.rs.container.Suspended;
13 import javax.ws.rs.core.MediaType;
14 import javax.ws.rs.core.Response;
15 import java.io.PrintWriter;
16 import java.io.StringWriter;
17 import java.util.concurrent.CountDownLatch;
18 import java.util.concurrent.TimeUnit;
19
20 /**
21 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
22 * @version $Revision: 1 $
23 */
24 @Path("/jaxrs")
25 public class JaxrsAsyncServletJaxrsResource {
26 private Logger logger = Logger.getLogger(JaxrsAsyncServletJaxrsResource.class);
27 protected boolean cancelled;
28
29 @GET
30 @Path("resume/object")
31 @Produces("application/xml")
32 public void resumeObject(@Suspended final AsyncResponse response) {
33 response.resume(new JaxrsAsyncServletXmlData("bill"));
34 }
35
36 @GET
37 @Path("resume/object/thread")
38 @Produces("application/xml")
39 public void resumeObjectThread(@Suspended final AsyncResponse response) throws Exception {
40 Thread t = new Thread() {
41 @Override
42 public void run() {
43 response.resume(new JaxrsAsyncServletXmlData("bill"));
44 }
45 };
46 t.start();
47 }
48
49
50 @GET
51 @Path("injection-failure/{param}")
52 public void injectionFailure(@Suspended final AsyncResponse response, @PathParam("param") int id) {
53 throw new ForbiddenException("Should be unreachable");
54 }
55
56 @GET
57 @Path("method-failure")
58 public void injectionFailure(@Suspended final AsyncResponse response) {
59 throw new ForbiddenException("Should be unreachable");
60 }
61
62
63 @GET
64 @Path("cancelled")
65 public Response getCancelled() {
66 if (cancelled) {
67 return Response.noContent().build();
68 } else {
69 return Response.status(500).build();
70 }
71 }
72
73 @PUT
74 @Path("cancelled")
75 public void resetCancelled() {
76 cancelled = false;
77 }
78
79 @GET
80 @Produces("text/plain")
81 public void get(@Suspended final AsyncResponse response) throws Exception {
82 response.setTimeout(2000, TimeUnit.MILLISECONDS);
83 Thread t = new Thread() {
84 private Logger logger = Logger.getLogger(JaxrsAsyncServletJaxrsResource.class);
85 @Override
86 public void run() {
87 try {
88 logger.info("STARTED!!!!");
89 Thread.sleep(100);
90 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
91 response.resume(jaxrs);
92 } catch (Exception e) {
93 StringWriter errors = new StringWriter();
94 e.printStackTrace(new PrintWriter(errors));
95 logger.error(errors.toString());
96 }
97 }
98 };
99 t.start();
100 }
101
102 @GET
103 @Path("timeout")
104 @Produces("text/plain")
105 public void timeout(@Suspended final AsyncResponse response) {
106 response.setTimeout(10, TimeUnit.MILLISECONDS);
107 Thread t = new Thread() {
108 private Logger logger = Logger.getLogger(JaxrsAsyncServletJaxrsResource.class);
109 @Override
110 public void run() {
111 try {
112 logger.info("STARTED!!!!");
113 Thread.sleep(100000);
114 Response jaxrs = Response.ok("goodbye").type(MediaType.TEXT_PLAIN).build();
115 response.resume(jaxrs);
116 } catch (Exception e) {
117 StringWriter errors = new StringWriter();
118 e.printStackTrace(new PrintWriter(errors));
119 logger.error(errors.toString());
120 }
121 }
122 };
123 t.start();
124 }
125
126
127 @GET
128 @Path("cancel")
129 @Produces("text/plain")
130 public void cancel(@Suspended final AsyncResponse response) throws Exception {
131 response.setTimeout(10000, TimeUnit.MILLISECONDS);
132 final CountDownLatch sync = new CountDownLatch(1);
133 final CountDownLatch ready = new CountDownLatch(1);
134 Thread t = new Thread() {
135 private Logger logger = Logger.getLogger(JaxrsAsyncServletJaxrsResource.class);
136 @Override
137 public void run() {
138 try {
139 sync.countDown();
140 logger.info("cancel awaiting thread");
141 ready.await();
142 logger.info("cancel resuming");
143 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
144 cancelled = !response.resume(jaxrs);
145 } catch (Exception e) {
146 StringWriter errors = new StringWriter();
147 e.printStackTrace(new PrintWriter(errors));
148 logger.error(errors.toString());
149 }
150 }
151 };
152 t.start();
153
154 sync.await();
155 logger.info("Cancelling...");
156 response.cancel();
157 ready.countDown();
158 }
159
160 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/JaxrsAsyncServletPrintingErrorHandler.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.core.Response;
5 import javax.ws.rs.ext.ExceptionMapper;
6 import javax.ws.rs.ext.Provider;
7 import java.io.PrintWriter;
8 import java.io.StringWriter;
9 import java.io.Writer;
10
11 @Provider
12 public class JaxrsAsyncServletPrintingErrorHandler implements ExceptionMapper<Throwable> {
13 private Logger logger = Logger.getLogger(JaxrsAsyncServletApp.class);
14
15 @Override
16 public Response toResponse(Throwable throwable) {
17 StringWriter errors = new StringWriter();
18 throwable.printStackTrace(new PrintWriter(errors));
19 logger.error(errors.toString());
20
21 Writer result = new StringWriter();
22 PrintWriter printWriter = new PrintWriter(result);
23 throwable.printStackTrace(printWriter);
24 return Response.status(Response.Status.NOT_ACCEPTABLE).entity(result.toString())
25 .build();
26 }
27
28 }
+0
-189
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/JaxrsAsyncServletResource.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.QueryParam;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.container.AsyncResponse;
8 import javax.ws.rs.container.Suspended;
9 import javax.ws.rs.core.Response;
10 import javax.ws.rs.core.Response.ResponseBuilder;
11 import javax.ws.rs.core.Response.Status;
12 import java.io.IOException;
13 import java.util.Date;
14 import java.util.concurrent.TimeUnit;
15
16 @Path("resource")
17 public class JaxrsAsyncServletResource {
18
19 public static final String RESUMED = "Response resumed";
20 public static final String FALSE = "A method returned false";
21 public static final String TRUE = "A method return true";
22
23 private static final JaxrsAsyncServletAsyncResponseBlockingQueue[] stage = {
24 new JaxrsAsyncServletAsyncResponseBlockingQueue(1),
25 new JaxrsAsyncServletAsyncResponseBlockingQueue(1),
26 new JaxrsAsyncServletAsyncResponseBlockingQueue(1)};
27
28 @GET
29 @Path("suspend")
30 public void suspend(@Suspended AsyncResponse asyncResponse) {
31 stage[0].add(asyncResponse);
32 }
33
34 @GET
35 @Path("clear")
36 public void clear() {
37 for (int i = 0; i != stage.length; i++) {
38 stage[i].clear();
39 }
40 }
41
42 @GET
43 @Path("cancelvoid")
44 public String cancel(@QueryParam("stage") String stage) {
45 AsyncResponse response = takeAsyncResponse(stage);
46 boolean ret = response.cancel();
47 // Invoking a cancel(...) method multiple times to cancel request
48 // processing has the same effect as canceling the request processing
49 // only once.
50 ret &= response.cancel();
51 addResponse(response, stage);
52 return ret ? TRUE : FALSE;
53 }
54
55 @POST
56 @Path("cancelretry")
57 public String cancelretry(@QueryParam("stage") String stage,
58 String sRetryAfter) {
59 AsyncResponse response = takeAsyncResponse(stage);
60 int retryAfter = Integer.parseInt(sRetryAfter);
61 boolean b = response.cancel(retryAfter);
62 // Invoking a cancel(...) method multiple times to cancel request
63 // processing has the same effect as canceling the request processing
64 // only once.
65 b &= response.cancel(retryAfter * 2);
66 addResponse(response, stage);
67 return b ? TRUE : FALSE;
68 }
69
70 @POST
71 @Path("canceldate")
72 public String cancelDate(@QueryParam("stage") String stage, String sRetryAfter) {
73 AsyncResponse response = takeAsyncResponse(stage);
74 long retryAfter = Long.parseLong(sRetryAfter);
75 boolean b = response.cancel(new Date(retryAfter));
76 // Invoking a cancel(...) method multiple times to cancel request
77 // processing has the same effect as canceling the request processing
78 // only once.
79 b &= response.cancel(new Date(retryAfter + 20000));
80 addResponse(response, stage);
81 return b ? TRUE : FALSE;
82 }
83
84 @GET
85 @Path("iscanceled")
86 public String isCanceled(@QueryParam("stage") String stage) {
87 AsyncResponse response = takeAsyncResponse(stage);
88 boolean is = response.isCancelled();
89 addResponse(response, stage);
90 return is ? TRUE : FALSE;
91 }
92
93 @GET
94 @Path("isdone")
95 public String isDone(@QueryParam("stage") String stage) {
96 AsyncResponse response = takeAsyncResponse(stage);
97 boolean is = response.isDone();
98 addResponse(response, stage);
99 return is ? TRUE : FALSE;
100 }
101
102 @GET
103 @Path("issuspended")
104 public String isSuspended(@QueryParam("stage") String stage) {
105 AsyncResponse response = takeAsyncResponse(stage);
106 boolean is = response.isSuspended();
107 addResponse(response, stage);
108 return is ? TRUE : FALSE;
109 }
110
111 @POST
112 @Path("resume")
113 public String resume(@QueryParam("stage") String stage, String response) {
114 AsyncResponse async = takeAsyncResponse(stage);
115 boolean b = resume(async, response);
116 addResponse(async, stage);
117 return b ? TRUE : FALSE;
118 }
119
120 @GET
121 @Path("resumechecked")
122 public String resumeWithCheckedException(@QueryParam("stage") String stage) {
123 AsyncResponse async = takeAsyncResponse(stage);
124 boolean b = async.resume(new IOException(RESUMED));
125 addResponse(async, stage);
126 return b ? TRUE : FALSE;
127 }
128
129 @GET
130 @Path("resumeruntime")
131 public String resumeWithRuntimeException(@QueryParam("stage") String stage) {
132 AsyncResponse async = takeAsyncResponse(stage);
133 boolean b = async.resume(new RuntimeException(RESUMED));
134 addResponse(async, stage);
135 return b ? TRUE : FALSE;
136 }
137
138 @POST
139 @Path("settimeout")
140 public void setTimeOut(@QueryParam("stage") String stage, String milis) {
141 AsyncResponse async = takeAsyncResponse(stage);
142 async.setTimeout(Long.parseLong(milis), TimeUnit.MILLISECONDS);
143 addResponse(async, stage);
144 }
145
146 @POST
147 @Path("timeouthandler")
148 public void setTimeoutHandler(@QueryParam("stage") String stage, int handlerValue) {
149 JaxrsAsyncServletTimeoutHandler handler = new JaxrsAsyncServletTimeoutHandler(handlerValue);
150 AsyncResponse async = takeAsyncResponse(stage);
151 async.setTimeoutHandler(handler);
152 async.setTimeout(200L, TimeUnit.MILLISECONDS);
153 addResponse(async, stage);
154 }
155
156 // ////////////////////////////////////////////////////////////////////////
157
158 protected static AsyncResponse takeAsyncResponse(String stageId) {
159 return takeAsyncResponse(Integer.parseInt(stageId));
160 }
161
162 protected static AsyncResponse takeAsyncResponse(int stageId) {
163 final ResponseBuilder error = createErrorResponseBuilder();
164 AsyncResponse asyncResponse = null;
165 try {
166 asyncResponse = stage[stageId].take();
167 } catch (InterruptedException e) {
168 throw new WebApplicationException(error.entity(
169 "ArrayBlockingQueue#take").build());
170 }
171 return asyncResponse;
172 }
173
174 protected static final void addResponse(AsyncResponse response, String stageId) {
175 int id = Integer.parseInt(stageId) + 1;
176 if (id != stage.length) {
177 stage[id].add(response);
178 }
179 }
180
181 protected static boolean resume(AsyncResponse takenResponse, Object response) {
182 return takenResponse.resume(response);
183 }
184
185 protected static ResponseBuilder createErrorResponseBuilder() {
186 return Response.status(Status.EXPECTATION_FAILED);
187 }
188 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/JaxrsAsyncServletServiceUnavailableExceptionMapper.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2
3 import javax.ws.rs.ServiceUnavailableException;
4 import javax.ws.rs.core.Response;
5 import javax.ws.rs.core.Response.Status;
6 import javax.ws.rs.ext.ExceptionMapper;
7 import javax.ws.rs.ext.Provider;
8
9 @Provider
10 public class JaxrsAsyncServletServiceUnavailableExceptionMapper implements
11 ExceptionMapper<ServiceUnavailableException> {
12
13 @Override
14 public Response toResponse(ServiceUnavailableException exception) {
15 String entity = new StringBuilder()
16 .append(exception.getClass().getName()).append(";status=")
17 .append(exception.getResponse().getStatus()).toString();
18 return Response.status(Status.REQUEST_TIMEOUT).entity(entity).build();
19 }
20
21 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/JaxrsAsyncServletTimeoutHandler.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.ws.rs.container.AsyncResponse;
3 import javax.ws.rs.container.TimeoutHandler;
4 import java.util.concurrent.TimeUnit;
5
6 public class JaxrsAsyncServletTimeoutHandler implements TimeoutHandler {
7
8 private int function = 0;
9
10 public JaxrsAsyncServletTimeoutHandler(final int function) {
11 super();
12 this.function = function;
13 }
14
15 @Override
16 public void handleTimeout(AsyncResponse asyncResponse) {
17 switch (function) {
18 case 1:
19 asyncResponse.setTimeout(200, TimeUnit.MILLISECONDS);
20 break;
21 case 2:
22 asyncResponse.cancel();
23 break;
24 case 3:
25 asyncResponse.resume(JaxrsAsyncServletResource.RESUMED);
26 break;
27 }
28 }
29
30 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/JaxrsAsyncServletXmlData.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 /**
5 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
6 * @version $Revision: 1 $
7 */
8 @XmlRootElement(name = "data")
9 public class JaxrsAsyncServletXmlData {
10 protected String name;
11
12 public JaxrsAsyncServletXmlData(final String data) {
13 this.name = data;
14 }
15
16 public JaxrsAsyncServletXmlData() {
17 }
18
19 public String getName() {
20 return name;
21 }
22
23 public void setName(String name) {
24 this.name = name;
25 }
26
27 }
+0
-60
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/asynch/resource/LegacySuspendResource.java less more
0 package org.jboss.resteasy.test.asynch.resource;
1
2 import org.jboss.resteasy.annotations.Suspend;
3 import org.jboss.resteasy.logging.Logger;
4 import org.jboss.resteasy.spi.AsynchronousResponse;
5
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.Response;
11 import java.io.PrintWriter;
12 import java.io.StringWriter;
13
14 @Path("/")
15 public class LegacySuspendResource {
16 private static Logger logger = Logger.getLogger(LegacySuspendResource.class);
17
18 @GET
19 @Produces("text/plain")
20 public void get(@Suspend(8000) final AsynchronousResponse response) {
21 Thread t = new Thread() {
22 @Override
23 public void run() {
24 try {
25 Thread.sleep(100);
26 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
27 response.setResponse(jaxrs);
28 } catch (Exception e) {
29 StringWriter errors = new StringWriter();
30 e.printStackTrace(new PrintWriter(errors));
31 logger.error(errors.toString());
32 }
33 }
34 };
35 t.start();
36 }
37
38 @GET
39 @Path("timeout")
40 @Produces("text/plain")
41 public void timeout(@Suspend(100) final AsynchronousResponse response) {
42 Thread t = new Thread() {
43 @Override
44 public void run() {
45 try {
46 Thread.sleep(1000);
47 Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
48 response.setResponse(jaxrs);
49 } catch (Exception e) {
50 StringWriter errors = new StringWriter();
51 e.printStackTrace(new PrintWriter(errors));
52 logger.error(errors.toString());
53 }
54 }
55 };
56 t.start();
57 }
58
59 }
+0
-99
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/EventsTest.java less more
0 package org.jboss.resteasy.test.cdi.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.cdi.basic.resource.EventsBookReaderInterceptor;
6 import org.jboss.resteasy.test.cdi.basic.resource.EventsBookWriterInterceptor;
7 import org.jboss.resteasy.test.cdi.basic.resource.EJBBook;
8 import org.jboss.resteasy.test.cdi.basic.resource.EventResource;
9 import org.jboss.resteasy.test.cdi.basic.resource.EventsBookReader;
10 import org.jboss.resteasy.test.cdi.basic.resource.EventsBookWriter;
11 import org.jboss.resteasy.test.cdi.basic.resource.EventsRead;
12 import org.jboss.resteasy.test.cdi.basic.resource.EventsUnused;
13 import org.jboss.resteasy.test.cdi.basic.resource.EventsWrite;
14 import org.jboss.resteasy.test.cdi.basic.resource.EventsReadIntercept;
15 import org.jboss.resteasy.test.cdi.basic.resource.EventsWriteIntercept;
16 import org.jboss.resteasy.test.cdi.util.Constants;
17 import org.jboss.resteasy.test.cdi.util.UtilityProducer;
18 import org.jboss.resteasy.util.HttpResponseCodes;
19 import org.jboss.resteasy.utils.PortProviderUtil;
20 import org.jboss.resteasy.utils.TestUtil;
21 import org.jboss.shrinkwrap.api.Archive;
22 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
23 import org.jboss.shrinkwrap.api.spec.WebArchive;
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26
27 import javax.swing.text.Utilities;
28 import javax.ws.rs.client.Client;
29 import javax.ws.rs.client.ClientBuilder;
30 import javax.ws.rs.client.Entity;
31 import javax.ws.rs.client.WebTarget;
32 import javax.ws.rs.core.Response;
33
34 import static org.junit.Assert.assertEquals;
35
36
37 /**
38 * @tpSubChapter CDI
39 * @tpChapter Integration tests
40 * @tpTestCaseDetails Test integration of Events and RESTEasy.
41 * @tpSince RESTEasy 3.0.16
42 */
43 @RunWith(Arquillian.class)
44 @RunAsClient
45 public class EventsTest {
46
47 @Deployment
48 public static Archive<?> createTestArchive() {
49 WebArchive war = TestUtil.prepareArchive(EventsTest.class.getSimpleName())
50 .addClass(PortProviderUtil.class)
51 .addClasses(Constants.class, UtilityProducer.class, Utilities.class)
52 .addClasses(EJBBook.class, EventsBookReader.class, EventsBookWriter.class)
53 .addClasses(EventsBookReaderInterceptor.class, EventsBookWriterInterceptor.class)
54 .addClasses(EventResource.class)
55 .addClasses(EventsRead.class, EventsReadIntercept.class)
56 .addClasses(EventsUnused.class, EventsWrite.class, EventsWriteIntercept.class)
57 .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
58 return war;
59 }
60
61 private String generateURL(String path) {
62 return PortProviderUtil.generateURL(path, EventsTest.class.getSimpleName());
63 }
64
65 /**
66 * @tpTestDetails Test creating object on resource and retrieving this object again.
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void testEvents() throws Exception {
71 Client client = ClientBuilder.newClient();
72
73 // Create book.
74 WebTarget base = client.target(generateURL("/create/"));
75 EJBBook book = new EJBBook("RESTEasy: the Sequel");
76 Response response = base.request().post(Entity.entity(book, Constants.MEDIA_TYPE_TEST_XML_TYPE));
77 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
78 int id = response.readEntity(int.class);
79 assertEquals("Received wrong id of stored book", 0, id);
80 response.close();
81
82 // Retrieve book.
83 WebTarget base2 = client.target(generateURL("/book/" + id));
84 Response response2 = base2.request().accept(Constants.MEDIA_TYPE_TEST_XML).get();
85 assertEquals(HttpResponseCodes.SC_OK, response2.getStatus());
86 EJBBook result = response2.readEntity(EJBBook.class);
87 assertEquals("Received wrong Book", book, result);
88 response2.close();
89
90 // test events
91 WebTarget base3 = client.target(generateURL("/test/"));
92 Response response3 = base3.request().post(Entity.text(new String()));
93 assertEquals(HttpResponseCodes.SC_OK, response3.getStatus());
94 response3.close();
95
96 client.close();
97 }
98 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/BeanReaderWriterConfigBean.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 public class BeanReaderWriterConfigBean {
3 public String version() {
4 return "1.1";
5 }
6 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/BeanReaderWriterService.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.inject.Inject;
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8
9 @Path("/")
10 public class BeanReaderWriterService {
11 private static Logger logger = Logger.getLogger(BeanReaderWriterService.class);
12 @Inject
13 BeanReaderWriterConfigBean bean;
14
15 /**
16 * Tests to make sure that a CDI bean was injected and that the BeanReaderWriterXFormat provider overrides the default XML provider
17 */
18 @GET
19 @Produces("application/xml")
20 public BeanReaderWriterXFormat get() {
21 if (bean != null) {
22 logger.info("BeanReaderWriterConfigBean version: " + bean.version());
23 } else {
24 throw new RuntimeException("CDI Bean Injection didn't work for test!");
25 }
26 return new BeanReaderWriterXFormat("foo");
27 }
28 }
+0
-40
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/BeanReaderWriterXFormat.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.xml.bind.annotation.XmlAttribute;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement(name = "xformat")
6 public class BeanReaderWriterXFormat {
7 protected String id;
8 protected String bean;
9
10 public BeanReaderWriterXFormat() {
11 }
12
13 public BeanReaderWriterXFormat(final String id) {
14 this.id = id;
15 }
16
17 public BeanReaderWriterXFormat(final String id, final String bean) {
18 this.id = id;
19 this.bean = bean;
20 }
21
22 @XmlAttribute
23 public String getId() {
24 return id;
25 }
26
27 public void setId(String id) {
28 this.id = id;
29 }
30
31 @XmlAttribute
32 public String getBean() {
33 return bean;
34 }
35
36 public void setBean(String bean) {
37 this.bean = bean;
38 }
39 }
+0
-71
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/BeanReaderWriterXFormatProvider.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.util.ReadFromStream;
4
5 import javax.inject.Inject;
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.WebApplicationException;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.MultivaluedMap;
11 import javax.ws.rs.ext.MessageBodyReader;
12 import javax.ws.rs.ext.MessageBodyWriter;
13 import javax.ws.rs.ext.Provider;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.OutputStream;
17 import java.lang.annotation.Annotation;
18 import java.lang.reflect.Type;
19
20 /**
21 * Tests to make sure that a CDI bean was injected and that this provider overrides the default XML provider
22 */
23 @Provider
24 @Produces("application/xml")
25 @Consumes("application/xml")
26 public class BeanReaderWriterXFormatProvider implements MessageBodyReader<BeanReaderWriterXFormat>, MessageBodyWriter<BeanReaderWriterXFormat> {
27 private static Logger logger = Logger.getLogger(BeanReaderWriterXFormatProvider.class);
28 @Inject
29 BeanReaderWriterConfigBean bean;
30
31 @Override
32 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
33 return BeanReaderWriterXFormat.class.isAssignableFrom(type);
34 }
35
36 @Override
37 public BeanReaderWriterXFormat readFrom(Class<BeanReaderWriterXFormat> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
38 logger.info("********** readFrom ********");
39 if (bean != null) {
40 logger.info("BeanReaderWriterXFormatProvider: BeanReaderWriterConfigBean version: " + bean.version());
41 }
42 byte[] bytes = ReadFromStream.readFromStream(1024, entityStream);
43 String val = new String(bytes);
44 String[] split = val.split(" ");
45 return new BeanReaderWriterXFormat(split[0], split[1]);
46 }
47
48 @Override
49 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
50 return BeanReaderWriterXFormat.class.isAssignableFrom(type);
51 }
52
53 @Override
54 public long getSize(BeanReaderWriterXFormat xFormat, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
55 return -1;
56 }
57
58 @Override
59 public void writeTo(BeanReaderWriterXFormat xFormat, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
60 logger.info("********** writeTo ********");
61 String message = "";
62 if (bean != null) {
63 logger.info("BeanReaderWriterXFormatProvider: BeanReaderWriterConfigBean version: " + bean.version());
64 message += xFormat.getId() + " " + bean.version();
65 } else {
66 message += xFormat.getId() + " 0";
67 }
68 entityStream.write(message.getBytes());
69 }
70 }
+0
-66
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/CDILocatorResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2
3 import org.jboss.logging.Logger;
4
5 import javax.enterprise.context.ApplicationScoped;
6 import javax.inject.Inject;
7 import javax.ws.rs.GET;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.QueryParam;
10 import java.lang.reflect.Method;
11
12 @Path("/test")
13 @ApplicationScoped // Weld uses a proxy
14 public class CDILocatorResource {
15
16 private static Logger logger = Logger.getLogger(CDILocatorResource.class);
17
18 @Inject
19 FooResource fooResource;
20
21 @GET
22 public String get(@QueryParam("foo") java.util.List<Foo> foos) {
23 // Bug: It's not a List<Foo>, it's a List<String>
24 for (Foo foo : foos) {
25 return "OK";
26 }
27 return null;
28
29 }
30
31
32 @Path("lookup")
33 public FooResource lookup() throws Exception {
34 logger.info("classname: " + fooResource.getClass().getName());
35 for (Method m : fooResource.getClass().getMethods()) {
36 if (m.getName().equals("get")) {
37 logger.info(m);
38 logger.info("@GET? " + m.isAnnotationPresent(GET.class));
39 }
40 }
41 return fooResource;
42 }
43
44 @ApplicationScoped // Weld uses a proxy
45 public static class FooResource {
46
47 @GET
48 public String get(@QueryParam("foo") java.util.List<Foo> foos) {
49 // Bug: It's not a List<Foo>, it's a List<String>
50 for (Foo foo : foos) {
51 return "OK";
52 }
53 return null;
54 }
55
56 }
57
58 public static class Foo {
59 String value;
60
61 public Foo(final String value) {
62 this.value = value;
63 }
64 }
65 }
+0
-50
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsBookReader.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3 import org.jboss.resteasy.test.cdi.util.Constants;
4
5 import javax.inject.Inject;
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.WebApplicationException;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.MultivaluedMap;
10 import javax.ws.rs.ext.MessageBodyReader;
11 import javax.ws.rs.ext.Provider;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.util.logging.Logger;
17
18 @Provider
19 @Consumes(Constants.MEDIA_TYPE_TEST_XML)
20 public class DecoratorsBookReader implements MessageBodyReader<EJBBook> {
21 private static MessageBodyReader<EJBBook> delegate;
22
23 @Inject
24 private Logger log;
25
26 static {
27 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
28 delegate = factory.getMessageBodyReader(EJBBook.class, null, null, Constants.MEDIA_TYPE_TEST_XML_TYPE);
29 }
30
31 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
32 log.info("entering DecoratorsBookReader.isReadable()");
33 boolean b = EJBBook.class.equals(type);
34 log.info("leaving DecoratorsBookReader.isReadable()");
35 return b;
36 }
37
38 public EJBBook readFrom(Class<EJBBook> type, Type genericType,
39 Annotation[] annotations, MediaType mediaType,
40 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
41 throws IOException, WebApplicationException {
42 log.info("entering DecoratorsBookReader.readFrom()");
43 EJBBook book = EJBBook.class.cast(delegate.readFrom(EJBBook.class, genericType, annotations, mediaType, httpHeaders, entityStream));
44 log.info("DecoratorsBookReader.readFrom() read " + book);
45 log.info("leaving DecoratorsBookReader.readFrom()");
46 return book;
47 }
48 }
49
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsBookReaderDecorator.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.decorator.Decorator;
3 import javax.decorator.Delegate;
4 import javax.inject.Inject;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyReader;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.lang.annotation.Annotation;
12 import java.lang.reflect.Type;
13 import java.util.logging.Logger;
14
15 @Decorator
16 public abstract class DecoratorsBookReaderDecorator implements MessageBodyReader<EJBBook> {
17 @Inject
18 private Logger log;
19
20 @Inject
21 @Delegate
22 private MessageBodyReader<EJBBook> reader;
23
24 @Override
25 public EJBBook readFrom(Class<EJBBook> type, Type genericType,
26 Annotation[] annotations, MediaType mediaType,
27 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
28 throws IOException, WebApplicationException {
29 log.info("entering DecoratorsBookReaderDecorator.readFrom()");
30 DecoratorsVisitList.add(DecoratorsVisitList.READER_DECORATOR_ENTER);
31 EJBBook b = reader.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
32 DecoratorsVisitList.add(DecoratorsVisitList.READER_DECORATOR_LEAVE);
33 log.info("leaving DecoratorsBookReaderDecorator.readFrom()");
34 return b;
35 }
36 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsBookReaderInterceptor.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Inject;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.ext.Provider;
5 import javax.ws.rs.ext.ReaderInterceptor;
6 import javax.ws.rs.ext.ReaderInterceptorContext;
7 import java.io.IOException;
8 import java.util.logging.Logger;
9
10 @Provider
11 public class DecoratorsBookReaderInterceptor implements ReaderInterceptor {
12 @Inject
13 private Logger log;
14
15 @Override
16 public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
17 log.info("entering DecoratorsBookReaderInterceptor.aroundReadFrom()");
18 DecoratorsVisitList.add(DecoratorsVisitList.READER_INTERCEPTOR_ENTER);
19 Object result = context.proceed();
20 DecoratorsVisitList.add(DecoratorsVisitList.READER_INTERCEPTOR_LEAVE);
21 log.info("leaving DecoratorsBookReaderInterceptor.aroundReadFrom()");
22 return result;
23 }
24 }
25
+0
-30
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsBookReaderInterceptorDecorator.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.decorator.Decorator;
3 import javax.decorator.Delegate;
4 import javax.inject.Inject;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.ext.ReaderInterceptor;
7 import javax.ws.rs.ext.ReaderInterceptorContext;
8 import java.io.IOException;
9 import java.util.logging.Logger;
10
11 @Decorator
12 public abstract class DecoratorsBookReaderInterceptorDecorator implements ReaderInterceptor {
13 @Inject
14 private Logger log;
15
16 @Inject
17 @Delegate
18 private DecoratorsBookReaderInterceptor interceptor;
19
20 @Override
21 public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
22 log.info("entering DecoratorsBookReaderInterceptorDecorator.aroundReadFrom()");
23 DecoratorsVisitList.add(DecoratorsVisitList.READER_INTERCEPTOR_DECORATOR_ENTER);
24 Object o = interceptor.aroundReadFrom(context);
25 DecoratorsVisitList.add(DecoratorsVisitList.READER_INTERCEPTOR_DECORATOR_LEAVE);
26 log.info("leaving DecoratorsBookReaderInterceptorDecorator.aroundReadFrom()");
27 return o;
28 }
29 }
+0
-44
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsBookWriter.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3 import org.jboss.resteasy.test.cdi.util.Constants;
4
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyWriter;
10 import javax.ws.rs.ext.Provider;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.Type;
15
16 @Provider
17 @Produces(Constants.MEDIA_TYPE_TEST_XML)
18 public class DecoratorsBookWriter implements MessageBodyWriter<EJBBook> {
19 private static MessageBodyWriter<EJBBook> delegate;
20
21 static {
22 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
23 delegate = factory.getMessageBodyWriter(EJBBook.class, null, null, Constants.MEDIA_TYPE_TEST_XML_TYPE);
24 }
25
26 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
27 boolean b = EJBBook.class.equals(type);
28 return b;
29 }
30
31 public long getSize(EJBBook t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
32 return -1;
33 }
34
35 @Override
36 public void writeTo(EJBBook t, Class<?> type, Type genericType,
37 Annotation[] annotations, MediaType mediaType,
38 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
39 throws IOException, WebApplicationException {
40 delegate.writeTo(t, type, genericType, annotations, mediaType, httpHeaders, entityStream);
41 }
42 }
43
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsBookWriterDecorator.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.decorator.Decorator;
3 import javax.decorator.Delegate;
4 import javax.inject.Inject;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import java.io.IOException;
10 import java.io.OutputStream;
11 import java.lang.annotation.Annotation;
12 import java.lang.reflect.Type;
13 import java.util.logging.Logger;
14
15 @Decorator
16 public abstract class DecoratorsBookWriterDecorator implements MessageBodyWriter<EJBBook> {
17 @Inject
18 private Logger log;
19
20 @Inject
21 @Delegate
22 private MessageBodyWriter<EJBBook> writer;
23
24 @Override
25 public void writeTo(EJBBook t, Class<?> type, Type genericType,
26 Annotation[] annotations, MediaType mediaType,
27 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
28 throws IOException, WebApplicationException {
29 log.info("entering DecoratorsBookWriterDecorator.writeTo()");
30 DecoratorsVisitList.add(DecoratorsVisitList.WRITER_DECORATOR_ENTER);
31 writer.writeTo(t, type, genericType, annotations, mediaType, httpHeaders, entityStream);
32 DecoratorsVisitList.add(DecoratorsVisitList.WRITER_DECORATOR_LEAVE);
33 log.info("leaving DecoratorsBookWriterDecorator.writeTo()");
34 }
35 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsBookWriterInterceptor.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Inject;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.ext.Provider;
5 import javax.ws.rs.ext.WriterInterceptor;
6 import javax.ws.rs.ext.WriterInterceptorContext;
7 import java.io.IOException;
8 import java.util.logging.Logger;
9
10 @Provider
11 public class DecoratorsBookWriterInterceptor implements WriterInterceptor {
12 @Inject
13 private Logger log;
14
15 @Override
16 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
17 log.info("entering DecoratorsBookWriterInterceptor.aroundWriteTo()");
18 DecoratorsVisitList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_ENTER);
19 context.proceed();
20 DecoratorsVisitList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_LEAVE);
21 log.info("leaving DecoratorsBookWriterInterceptor.aroundWriteTo()");
22 }
23 }
24
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsBookWriterInterceptorDecorator.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.decorator.Decorator;
3 import javax.decorator.Delegate;
4 import javax.inject.Inject;
5 import javax.ws.rs.ext.WriterInterceptor;
6 import javax.ws.rs.ext.WriterInterceptorContext;
7 import java.util.logging.Logger;
8
9 @Decorator
10 public abstract class DecoratorsBookWriterInterceptorDecorator implements WriterInterceptor {
11 @Inject
12 private Logger log;
13
14 @Inject
15 @Delegate
16 private DecoratorsBookWriterInterceptor interceptor;
17
18 @Override
19 public void aroundWriteTo(WriterInterceptorContext context) throws java.io.IOException, javax.ws.rs.WebApplicationException {
20 log.info("entering DecoratorsBookWriterInterceptorDecorator.aroundWriteTo()");
21 DecoratorsVisitList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_DECORATOR_ENTER);
22 interceptor.aroundWriteTo(context);
23 DecoratorsVisitList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_DECORATOR_LEAVE);
24 log.info("leaving DecoratorsBookWriterInterceptorDecorator.aroundWriteTo()");
25 }
26 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsFilterBinding.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ws.rs.NameBinding;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.Target;
5
6 import static java.lang.annotation.ElementType.METHOD;
7 import static java.lang.annotation.ElementType.TYPE;
8 import static java.lang.annotation.RetentionPolicy.RUNTIME;
9
10 @NameBinding
11 @Target({TYPE, METHOD})
12 @Retention(value = RUNTIME)
13 public @interface DecoratorsFilterBinding {
14 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsRequestFilterDecorator.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.decorator.Decorator;
3 import javax.decorator.Delegate;
4 import javax.inject.Inject;
5 import javax.ws.rs.container.ContainerRequestContext;
6 import javax.ws.rs.container.ContainerRequestFilter;
7 import java.io.IOException;
8 import java.util.logging.Logger;
9
10 @Decorator
11 public abstract class DecoratorsRequestFilterDecorator implements ContainerRequestFilter {
12 @Inject
13 private Logger log;
14
15 @Inject
16 @Delegate
17 private DecoratorsTestRequestFilter filter;
18
19 @Override
20 public void filter(ContainerRequestContext requestContext) throws IOException {
21 log.info("entering DecoratorsRequestFilterDecorator.filter()");
22 DecoratorsVisitList.add(DecoratorsVisitList.REQUEST_FILTER_DECORATOR_ENTER);
23 filter.filter(requestContext);
24 DecoratorsVisitList.add(DecoratorsVisitList.REQUEST_FILTER_DECORATOR_LEAVE);
25 log.info("leaving DecoratorsRequestFilterDecorator.filter()");
26 }
27 }
+0
-144
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2
3 import org.jboss.resteasy.test.cdi.util.Constants;
4
5 import javax.enterprise.context.RequestScoped;
6 import javax.inject.Inject;
7 import javax.ws.rs.Consumes;
8 import javax.ws.rs.GET;
9 import javax.ws.rs.POST;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.PathParam;
12 import javax.ws.rs.Produces;
13 import javax.ws.rs.WebApplicationException;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.core.Response;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.Map;
19 import java.util.concurrent.atomic.AtomicInteger;
20 import java.util.logging.Logger;
21
22 @Path("/")
23 @RequestScoped
24 public class DecoratorsResource implements DecoratorsResourceIntf {
25 private static Map<Integer, EJBBook> collection = new HashMap<Integer, EJBBook>();
26 private static AtomicInteger counter = new AtomicInteger();
27
28 @Inject
29 private Logger log;
30
31 @Override
32 @POST
33 @Path("create")
34 @Consumes(Constants.MEDIA_TYPE_TEST_XML)
35 @Produces(MediaType.TEXT_PLAIN)
36 @DecoratorsFilterBinding
37 @DecoratorsResourceBinding
38 public Response createBook(EJBBook book) {
39 log.info("entering DecoratorsResource.createBook()");
40 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_ENTER);
41 int id = counter.getAndIncrement();
42 book.setId(id);
43 collection.put(id, book);
44 log.info("stored: " + id + "->" + book);
45 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_LEAVE);
46 log.info("leaving DecoratorsResource.createBook()");
47 return Response.ok(id).build();
48 }
49
50 @Override
51 @GET
52 @Path("book/{id:[0-9][0-9]*}")
53 @Produces(Constants.MEDIA_TYPE_TEST_XML)
54 @DecoratorsFilterBinding
55 @DecoratorsResourceBinding
56 public EJBBook lookupBookById(@PathParam("id") int id) {
57 log.info("entering DecoratorsResource.lookupBookById(" + id + ")");
58 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_ENTER);
59 log.info("books: " + collection);
60 EJBBook book = collection.get(id);
61 if (book == null) {
62 throw new WebApplicationException(Response.Status.NOT_FOUND);
63 }
64 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_LEAVE);
65 log.info("leaving DecoratorsResource.lookupBookById(" + id + ")");
66 return book;
67 }
68
69 @Override
70 @POST
71 @Path("test")
72 @Produces(MediaType.TEXT_PLAIN)
73 public Response test() {
74 log.info("entering DecoratorsResource.test()");
75 ArrayList<String> expectedList = new ArrayList<String>();
76
77 // Call to createBook()
78 expectedList.add(DecoratorsVisitList.REQUEST_FILTER_DECORATOR_ENTER);
79 expectedList.add(DecoratorsVisitList.REQUEST_FILTER_DECORATOR_LEAVE);
80 expectedList.add(DecoratorsVisitList.READER_INTERCEPTOR_DECORATOR_ENTER);
81 expectedList.add(DecoratorsVisitList.READER_INTERCEPTOR_ENTER);
82 expectedList.add(DecoratorsVisitList.READER_DECORATOR_ENTER);
83 expectedList.add(DecoratorsVisitList.READER_DECORATOR_LEAVE);
84 expectedList.add(DecoratorsVisitList.READER_INTERCEPTOR_LEAVE);
85 expectedList.add(DecoratorsVisitList.READER_INTERCEPTOR_DECORATOR_LEAVE);
86 expectedList.add(DecoratorsVisitList.RESOURCE_INTERCEPTOR_ENTER);
87 expectedList.add(DecoratorsVisitList.RESOURCE_DECORATOR_ENTER);
88 expectedList.add(DecoratorsVisitList.RESOURCE_ENTER);
89 expectedList.add(DecoratorsVisitList.RESOURCE_LEAVE);
90 expectedList.add(DecoratorsVisitList.RESOURCE_DECORATOR_LEAVE);
91 expectedList.add(DecoratorsVisitList.RESOURCE_INTERCEPTOR_LEAVE);
92 expectedList.add(DecoratorsVisitList.RESPONSE_FILTER_DECORATOR_ENTER);
93 expectedList.add(DecoratorsVisitList.RESPONSE_FILTER_DECORATOR_LEAVE);
94 expectedList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_DECORATOR_ENTER);
95 expectedList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_ENTER);
96 expectedList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_LEAVE);
97 expectedList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_DECORATOR_LEAVE);
98
99 // Call to lookupBookById()
100 expectedList.add(DecoratorsVisitList.REQUEST_FILTER_DECORATOR_ENTER);
101 expectedList.add(DecoratorsVisitList.REQUEST_FILTER_DECORATOR_LEAVE);
102 expectedList.add(DecoratorsVisitList.RESOURCE_INTERCEPTOR_ENTER);
103 expectedList.add(DecoratorsVisitList.RESOURCE_DECORATOR_ENTER);
104 expectedList.add(DecoratorsVisitList.RESOURCE_ENTER);
105 expectedList.add(DecoratorsVisitList.RESOURCE_LEAVE);
106 expectedList.add(DecoratorsVisitList.RESOURCE_DECORATOR_LEAVE);
107 expectedList.add(DecoratorsVisitList.RESOURCE_INTERCEPTOR_LEAVE);
108 expectedList.add(DecoratorsVisitList.RESPONSE_FILTER_DECORATOR_ENTER);
109 expectedList.add(DecoratorsVisitList.RESPONSE_FILTER_DECORATOR_LEAVE);
110 expectedList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_DECORATOR_ENTER);
111 expectedList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_ENTER);
112 expectedList.add(DecoratorsVisitList.WRITER_DECORATOR_ENTER);
113 expectedList.add(DecoratorsVisitList.WRITER_DECORATOR_LEAVE);
114 expectedList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_LEAVE);
115 expectedList.add(DecoratorsVisitList.WRITER_INTERCEPTOR_DECORATOR_LEAVE);
116
117 ArrayList<String> visitList = DecoratorsVisitList.getList();
118 boolean status = expectedList.size() == visitList.size();
119 if (!status) {
120 log.info("expectedList.size() [" + expectedList.size() + "] != visitList.size() [" + visitList.size() + "]");
121 } else {
122 for (int i = 0; i < expectedList.size(); i++) {
123 if (!expectedList.get(i).equals(visitList.get(i))) {
124 status = false;
125 log.info("visitList.get(" + i + ") incorrect: should be: " + expectedList.get(i) + ", is: " + visitList.get(i));
126 break;
127 }
128 }
129 }
130 if (!status) {
131 log.info("\rexpectedList: ");
132 for (int i = 0; i < expectedList.size(); i++) {
133 log.info(i + ": " + expectedList.get(i).toString());
134 }
135 log.info("\rvisitList:");
136 for (int i = 0; i < visitList.size(); i++) {
137 log.info(i + ": " + visitList.get(i).toString());
138 }
139 }
140 log.info("leaving DecoratorsResource.test()");
141 return status ? Response.ok().build() : Response.serverError().build();
142 }
143 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsResourceBinding.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.interceptor.InterceptorBinding;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.Target;
5
6 import static java.lang.annotation.ElementType.METHOD;
7 import static java.lang.annotation.ElementType.TYPE;
8 import static java.lang.annotation.RetentionPolicy.RUNTIME;
9
10 @InterceptorBinding
11 @Target({TYPE, METHOD})
12 @Retention(RUNTIME)
13 public @interface DecoratorsResourceBinding {
14 }
15
+0
-40
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsResourceDecorator.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.decorator.Decorator;
3 import javax.decorator.Delegate;
4 import javax.inject.Inject;
5 import javax.ws.rs.core.Response;
6 import java.util.logging.Logger;
7
8 @Decorator
9 public abstract class DecoratorsResourceDecorator implements DecoratorsResourceIntf {
10 @Inject
11 private Logger log;
12
13 @Inject
14 @Delegate
15 private DecoratorsResource resource;
16
17 @Override
18 public Response createBook(EJBBook book) {
19 log.info("entering DecoratorsResourceDecorator.createBook()");
20 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_DECORATOR_ENTER);
21 Response response = resource.createBook(book);
22 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_DECORATOR_LEAVE);
23 log.info("leaving DecoratorsResourceDecorator.createBook()");
24 return response;
25 }
26
27 @Override
28 public EJBBook lookupBookById(int id) {
29 log.info("entering DecoratorsResourceDecorator.lookupBookById()");
30 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_DECORATOR_ENTER);
31 EJBBook book = resource.lookupBookById(id);
32 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_DECORATOR_LEAVE);
33 log.info("leaving DecoratorsResourceDecorator.lookupBookById()");
34 return book;
35 }
36
37 @Override
38 public abstract Response test();
39 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsResourceInterceptor.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Inject;
3 import javax.interceptor.AroundInvoke;
4 import javax.interceptor.Interceptor;
5 import javax.interceptor.InvocationContext;
6 import java.util.logging.Logger;
7
8 @Interceptor
9 @DecoratorsResourceBinding
10 public class DecoratorsResourceInterceptor {
11 @Inject
12 private Logger log;
13
14 @AroundInvoke
15 public Object intercept(InvocationContext ctx) throws Exception {
16 log.info("entering DecoratorsResourceInterceptor.intercept()");
17 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_INTERCEPTOR_ENTER);
18 Object result = ctx.proceed();
19 DecoratorsVisitList.add(DecoratorsVisitList.RESOURCE_INTERCEPTOR_LEAVE);
20 log.info("leaving DecoratorsResourceInterceptor.intercept()");
21 return result;
22 }
23 }
24
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsResourceIntf.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2
3 import org.jboss.resteasy.test.cdi.util.Constants;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.PathParam;
10 import javax.ws.rs.Produces;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.Response;
13
14 public interface DecoratorsResourceIntf {
15 @POST
16 @Path("create")
17 @Consumes(Constants.MEDIA_TYPE_TEST_XML)
18 @Produces(MediaType.TEXT_PLAIN)
19 @DecoratorsFilterBinding
20 @DecoratorsResourceBinding
21 Response createBook(EJBBook book);
22
23 @GET
24 @Path("book/{id:[0-9][0-9]*}")
25 @Produces(Constants.MEDIA_TYPE_TEST_XML)
26 @DecoratorsFilterBinding
27 @DecoratorsResourceBinding
28 EJBBook lookupBookById(@PathParam("id") int id);
29
30 @POST
31 @Path("test")
32 @Produces(MediaType.TEXT_PLAIN)
33 Response test();
34
35 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsResponseFilter.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Inject;
3 import javax.ws.rs.container.ContainerRequestContext;
4 import javax.ws.rs.container.ContainerResponseContext;
5 import javax.ws.rs.container.ContainerResponseFilter;
6 import javax.ws.rs.ext.Provider;
7 import java.io.IOException;
8 import java.util.logging.Logger;
9
10 @Provider
11 @DecoratorsFilterBinding
12 public class DecoratorsResponseFilter implements ContainerResponseFilter {
13 @Inject
14 private Logger log;
15
16 @Override
17 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
18 log.info("executing DecoratorsResponseFilter.filter()");
19 }
20 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsResponseFilterDecorator.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.decorator.Decorator;
3 import javax.decorator.Delegate;
4 import javax.inject.Inject;
5 import javax.ws.rs.container.ContainerRequestContext;
6 import javax.ws.rs.container.ContainerResponseContext;
7 import javax.ws.rs.container.ContainerResponseFilter;
8 import java.io.IOException;
9 import java.util.logging.Logger;
10
11 @Decorator
12 public abstract class DecoratorsResponseFilterDecorator implements ContainerResponseFilter {
13 @Inject
14 private Logger log;
15
16 @Inject
17 @Delegate
18 private DecoratorsResponseFilter filter;
19
20 @Override
21 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
22 log.info("entering DecoratorsRequestFilterDecorator.filter()");
23 DecoratorsVisitList.add(DecoratorsVisitList.RESPONSE_FILTER_DECORATOR_ENTER);
24 filter.filter(requestContext, responseContext);
25 DecoratorsVisitList.add(DecoratorsVisitList.RESPONSE_FILTER_DECORATOR_LEAVE);
26 log.info("leaving DecoratorsRequestFilterDecorator.filter()");
27 }
28 }
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsTestRequestFilter.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Inject;
3 import javax.ws.rs.container.ContainerRequestContext;
4 import javax.ws.rs.container.ContainerRequestFilter;
5 import javax.ws.rs.ext.Provider;
6 import java.io.IOException;
7 import java.util.logging.Logger;
8
9 @Provider
10 @DecoratorsFilterBinding
11 public class DecoratorsTestRequestFilter implements ContainerRequestFilter {
12 @Inject
13 private Logger log;
14
15 @Override
16 public void filter(ContainerRequestContext requestContext) throws IOException {
17 log.info("executing DecoratorsTestRequestFilter.filter()");
18 }
19 }
+0
-42
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/DecoratorsVisitList.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import java.util.ArrayList;
3
4 public class DecoratorsVisitList {
5 public static final String REQUEST_FILTER_DECORATOR_ENTER = "requestFilterDecoratorEnter";
6 public static final String REQUEST_FILTER_DECORATOR_LEAVE = "requestFilterDecoratorLeave";
7 public static final String RESPONSE_FILTER_DECORATOR_ENTER = "responseFilterDecoratorEnter";
8 public static final String RESPONSE_FILTER_DECORATOR_LEAVE = "responseFilterDecoratorLeave";
9
10 public static final String READER_INTERCEPTOR_DECORATOR_ENTER = "readerInterceptorDecoratorEnter";
11 public static final String READER_INTERCEPTOR_DECORATOR_LEAVE = "readerInterceptorDecoratorLeave";
12 public static final String READER_INTERCEPTOR_ENTER = "readerInterceptorEnter";
13 public static final String READER_INTERCEPTOR_LEAVE = "readerInterceptorLeave";
14 public static final String READER_DECORATOR_ENTER = "readerDecoratorEnter";
15 public static final String READER_DECORATOR_LEAVE = "readerDecoratorLeave";
16
17 public static final String WRITER_INTERCEPTOR_DECORATOR_ENTER = "writerInterceptorDecoratorEnter";
18 public static final String WRITER_INTERCEPTOR_DECORATOR_LEAVE = "writerInterceptorDecoratorLeave";
19 public static final String WRITER_INTERCEPTOR_ENTER = "writerInterceptorEnter";
20 public static final String WRITER_INTERCEPTOR_LEAVE = "writerInterceptorLeave";
21 public static final String WRITER_DECORATOR_ENTER = "writerDecoratorEnter";
22 public static final String WRITER_DECORATOR_LEAVE = "writerDecoratorLeave";
23
24 public static final String RESOURCE_INTERCEPTOR_ENTER = "resourceInterceptorEnter";
25 public static final String RESOURCE_INTERCEPTOR_LEAVE = "resourceInterceptorLeave";
26 public static final String RESOURCE_DECORATOR_ENTER = "resourceDecoratorEnter";
27 public static final String RESOURCE_DECORATOR_LEAVE = "resourceDecoratorLeave";
28 public static final String RESOURCE_ENTER = "resourceEnter";
29 public static final String RESOURCE_LEAVE = "resourceLeave";
30
31 private static ArrayList<String> visitList = new ArrayList<String>();
32
33 public static void add(String o) {
34 visitList.add(o);
35 }
36
37 public static ArrayList<String> getList() {
38 return new ArrayList<String>(visitList);
39 }
40 }
41
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBApplication.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Singleton;
3 import javax.enterprise.context.ApplicationScoped;
4 import javax.ws.rs.core.Application;
5 import java.util.HashSet;
6 import java.util.Set;
7
8 @Singleton
9 @ApplicationScoped
10 public class EJBApplication extends Application {
11 @Override
12 public Set<Class<?>> getClasses() {
13 HashSet<Class<?>> classes = new HashSet<Class<?>>();
14 classes.add(EJBBookReaderImpl.class);
15 classes.add(EJBBookWriterImpl.class);
16 classes.add(EJBBookResource.class);
17 return classes;
18 }
19 }
20
+0
-80
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBBook.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.persistence.Entity;
3 import javax.persistence.Id;
4 import javax.validation.constraints.NotNull;
5 import javax.validation.constraints.Size;
6 import javax.xml.bind.annotation.XmlAccessType;
7 import javax.xml.bind.annotation.XmlAccessorType;
8 import javax.xml.bind.annotation.XmlElement;
9 import javax.xml.bind.annotation.XmlRootElement;
10 import java.io.Serializable;
11
12 /**
13 * Book is
14 * 1) a JAXB class, suitable for transport over the network, and
15 * 2) an @Entity class, suitable for JPA storage
16 *
17 * It implements Serializable so that it can be returned from a JAX-RS resource
18 * in its role as EJB.
19 */
20 @Entity
21 @XmlRootElement(name = "book")
22 @XmlAccessorType(XmlAccessType.FIELD)
23 public class EJBBook implements Serializable {
24 private static final long serialVersionUID = 1L;
25
26 @XmlElement
27 private int id;
28
29 @XmlElement
30 @NotNull
31 @Size(min = 1, max = 25)
32 private String name;
33
34 public EJBBook() {
35 }
36
37 public EJBBook(final String name) {
38 this.name = name;
39 }
40
41 public EJBBook(final int id, final String name) {
42 this.id = id;
43 this.name = name;
44 }
45
46 @Id
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55
56 public String getName() {
57 return name;
58 }
59
60 public void setName(String name) {
61 this.name = name;
62 }
63
64 public String toString() {
65 return "Book[" + id + "," + name + "]";
66 }
67
68 public boolean equals(Object o) {
69 if (o == null || !(o instanceof EJBBook)) {
70 return false;
71 }
72 return name.equals(((EJBBook) o).name);
73 }
74
75 @Override
76 public int hashCode() {
77 return super.hashCode();
78 }
79 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBBookReader.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.test.cdi.util.Constants;
3
4 import javax.ejb.Local;
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.ext.MessageBodyReader;
7 import javax.ws.rs.ext.Provider;
8
9 @Local
10 @Provider
11 @Consumes(Constants.MEDIA_TYPE_TEST_XML)
12 public interface EJBBookReader extends MessageBodyReader<EJBBook> {
13 int getUses();
14
15 void reset();
16 }
+0
-71
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBBookReaderImpl.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4 import org.jboss.resteasy.test.cdi.util.Constants;
5
6 import javax.ejb.Stateful;
7 import javax.persistence.Entity;
8 import javax.ws.rs.Consumes;
9 import javax.ws.rs.WebApplicationException;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.MultivaluedMap;
12 import javax.ws.rs.ext.MessageBodyReader;
13 import javax.ws.rs.ext.Provider;
14 import javax.xml.bind.annotation.XmlAccessType;
15 import javax.xml.bind.annotation.XmlAccessorType;
16 import javax.xml.bind.annotation.XmlRootElement;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.lang.annotation.Annotation;
20 import java.lang.reflect.Type;
21
22 @Stateful
23 @Provider
24 @Consumes(Constants.MEDIA_TYPE_TEST_XML)
25 public class EJBBookReaderImpl implements EJBBookReader, MessageBodyReader<EJBBook> {
26
27 private static Logger log = Logger.getLogger(EJBBookReaderImpl.class);
28
29 @SuppressWarnings("rawtypes")
30 private static MessageBodyReader delegate;
31
32 private static int uses;
33
34 @Entity
35 @XmlRootElement(name = "nonbook")
36 @XmlAccessorType(XmlAccessType.FIELD)
37 public class NonBook {
38 }
39
40 static {
41 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
42 delegate = factory.getMessageBodyReader(NonBook.class, null, null, MediaType.APPLICATION_XML_TYPE);
43 log.info("reader delegate: " + delegate); // Should be JAXBXmlRootElementProvider.
44 }
45
46 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
47 return EJBBook.class.equals(type);
48 }
49
50 @SuppressWarnings("unchecked")
51 public EJBBook readFrom(Class<EJBBook> type, Type genericType,
52 Annotation[] annotations, MediaType mediaType,
53 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
54 throws IOException, WebApplicationException {
55 log.info("entering EJBBookReader.readFrom()");
56 uses++;
57 return EJBBook.class.cast(delegate.readFrom(EJBBook.class, genericType, annotations, mediaType, httpHeaders, entityStream));
58 }
59
60 @Override
61 public int getUses() {
62 return uses;
63 }
64
65 @Override
66 public void reset() {
67 uses = 0;
68 }
69 }
70
+0
-135
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBBookResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.test.cdi.util.Constants;
3 import org.jboss.resteasy.test.cdi.util.Counter;
4 import org.jboss.resteasy.test.cdi.util.CounterBinding;
5 import org.jboss.resteasy.test.cdi.util.Utilities;
6
7 import javax.ejb.EJB;
8 import javax.ejb.Stateless;
9 import javax.enterprise.context.Dependent;
10 import javax.inject.Inject;
11 import javax.ws.rs.Consumes;
12 import javax.ws.rs.GET;
13 import javax.ws.rs.POST;
14 import javax.ws.rs.Path;
15 import javax.ws.rs.PathParam;
16 import javax.ws.rs.Produces;
17 import javax.ws.rs.WebApplicationException;
18 import javax.ws.rs.core.MediaType;
19 import javax.ws.rs.core.Response;
20 import java.util.HashMap;
21 import java.util.logging.Logger;
22
23 @Stateless
24 @Dependent
25 @Path("/")
26 public class EJBBookResource implements EJBLocalResource, EJBRemoteResource {
27 private static HashMap<Integer, EJBBook> books = new HashMap<>();
28
29 @Inject
30 private Logger log;
31 @Inject
32 private Utilities utilities;
33 @Inject
34 @CounterBinding
35 private Counter counter;
36
37 @Inject
38 private EJBBookReader readerCDI; // EJBBookReaderImpl implements @Local interface EJBBookReader
39 @EJB
40 private EJBBookReader readerEJB;
41 @Inject
42 private EJBBookWriterImpl writerCDI; // EJBBookWriterImpl has a no-interface view
43 @EJB
44 private EJBBookWriterImpl writerEJB;
45
46 @GET
47 @Override
48 @Path("verifyScopes")
49 @Produces(MediaType.TEXT_PLAIN)
50 public int verifyScopes() {
51 log.info("entering verifyScopes()");
52 log.info("EJBBookReader scope: " + utilities.getScope(EJBBookReader.class));
53 log.info("EJBBookReaderImpl scope: " + utilities.getScope(EJBBookReaderImpl.class));
54 log.info("EJBBookWriterImpl scope: " + utilities.getScope(EJBBookWriterImpl.class));
55 log.info("EJBLocalResource scope: " + utilities.getScope(EJBLocalResource.class));
56 log.info("EJBRemoteResource scope: " + utilities.getScope(EJBRemoteResource.class));
57 log.info("EJBBookResource scope: " + utilities.getScope(EJBBookResource.class));
58
59 boolean result = true;
60 result &= utilities.isApplicationScoped(EJBBookReader.class);
61 result &= utilities.isApplicationScoped(EJBBookWriterImpl.class);
62 result &= utilities.isDependentScoped(EJBLocalResource.class);
63 return result ? 200 : 500;
64 }
65
66 @GET
67 @Override
68 @Path("verifyInjection")
69 @Produces(MediaType.TEXT_PLAIN)
70 public int verifyInjection() {
71 log.info("entering verifyInjection()");
72 log.info("readerCDI: " + readerCDI);
73 log.info("readerEJB: " + readerEJB);
74 log.info("writerCDI: " + writerCDI);
75 log.info("writerEJB: " + writerEJB);
76
77 boolean result = true;
78 result &= readerCDI != null;
79 result &= readerEJB != null;
80 result &= writerCDI != null;
81 result &= writerEJB != null;
82 return result ? 200 : 500;
83 }
84
85 @POST
86 @Path("create")
87 @Consumes(Constants.MEDIA_TYPE_TEST_XML)
88 @Produces(MediaType.TEXT_PLAIN)
89 public int createBook(EJBBook book) {
90 log.info("entering createBook()");
91 int id = counter.getNext();
92 book.setId(id);
93 books.put(id, book);
94 log.info("stored: " + id + "->" + book);
95 return id;
96 }
97
98 @GET
99 @Path("book/{id:[0-9][0-9]*}")
100 @Produces(Constants.MEDIA_TYPE_TEST_XML)
101 public EJBBook lookupBookById(@PathParam("id") int id) {
102 log.info("entering lookupBookById(" + id + ")");
103 log.info("books: " + books);
104 EJBBook book = books.get(id);
105 if (book == null) {
106 throw new WebApplicationException(Response.Status.NOT_FOUND);
107 }
108 return book;
109 }
110
111 @GET
112 @Path("uses/{count}")
113 @Produces(MediaType.TEXT_PLAIN)
114 public int testUse(@PathParam("count") int count) {
115 log.info("entering testUse()");
116 log.info("readerEJB uses: " + readerEJB.getUses());
117 log.info("writerEJB uses: " + writerEJB.getUses());
118 log.info("readerCDI uses: " + readerCDI.getUses());
119 log.info("writerCDI uses: " + writerCDI.getUses());
120 int readerUses = readerCDI.getUses();
121 int writerUses = writerCDI.getUses();
122 readerCDI.reset();
123 writerCDI.reset();
124 return (readerUses == count && writerUses == count) ? 200 : 500;
125 }
126
127 @GET
128 @Path("reset")
129 public void reset() {
130 log.info("entering reset()");
131 counter.reset();
132 }
133 }
134
+0
-82
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBBookWriterImpl.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4 import org.jboss.resteasy.test.cdi.util.Constants;
5
6 import javax.ejb.LocalBean;
7 import javax.ejb.Stateful;
8 import javax.persistence.Entity;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.WebApplicationException;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.MultivaluedMap;
13 import javax.ws.rs.ext.MessageBodyWriter;
14 import javax.ws.rs.ext.Provider;
15 import javax.xml.bind.annotation.XmlAccessType;
16 import javax.xml.bind.annotation.XmlAccessorType;
17 import javax.xml.bind.annotation.XmlRootElement;
18 import java.io.IOException;
19 import java.io.OutputStream;
20 import java.lang.annotation.Annotation;
21 import java.lang.reflect.Type;
22
23 @Stateful
24 @LocalBean
25 @Provider
26 @Produces(Constants.MEDIA_TYPE_TEST_XML)
27 public class EJBBookWriterImpl implements MessageBodyWriter<EJBBook> {
28
29 private static Logger logger = Logger.getLogger(EJBBookWriterImpl.class);
30
31 @SuppressWarnings("rawtypes")
32 private static MessageBodyWriter delegate;
33 private static int uses;
34
35 @Entity
36 @XmlRootElement(name = "nonbook")
37 @XmlAccessorType(XmlAccessType.FIELD)
38 public class NonBook {
39 }
40
41 /*
42 * It seems that EJBBookWriterImpl is treated somewhat differently than EJBBookReaderImpl, perhaps
43 * because EJBBookWriterImpl has a no-interface view. In any case, EJBBookReaderImpl is able to
44 * get an instance of ResteasyProviderFactory in a static block, but EJBBookWriterImpl isn't.
45 */
46 static void getDelegate() {
47 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
48 delegate = factory.getMessageBodyWriter(NonBook.class, null, null, MediaType.APPLICATION_XML_TYPE);
49 logger.info("writer delegate: " + delegate); // Should be JAXBXmlRootElementProvider.
50 }
51
52 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
53 return EJBBook.class.equals(type);
54 }
55
56 public long getSize(EJBBook t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
57 return -1;
58 }
59
60 @SuppressWarnings("unchecked")
61 @Override
62 public void writeTo(EJBBook t, Class<?> type, Type genericType,
63 Annotation[] annotations, MediaType mediaType,
64 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
65 throws IOException, WebApplicationException {
66 if (delegate == null) {
67 getDelegate();
68 }
69 delegate.writeTo(t, type, genericType, annotations, mediaType, httpHeaders, entityStream);
70 uses++;
71 }
72
73 public int getUses() {
74 return uses;
75 }
76
77 public void reset() {
78 uses = 0;
79 }
80 }
81
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBEventsObserver.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Local;
3 import javax.enterprise.event.Observes;
4 import java.util.ArrayList;
5
6 @Local
7 public interface EJBEventsObserver {
8 void process(@Observes @EventsProcess String event);
9
10 void processRead(@Observes @EventsProcess @EventsRead(context = "resource") String event);
11
12 void processWrite(@Observes @EventsProcess @EventsWrite(context = "resource") String event);
13
14 ArrayList<Object> getEventList();
15 }
+0
-40
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBEventsObserverImpl.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Stateful;
3 import javax.enterprise.event.Event;
4 import javax.enterprise.event.Observes;
5 import javax.inject.Inject;
6 import java.util.ArrayList;
7 import java.util.logging.Logger;
8
9 @Stateful
10 public class EJBEventsObserverImpl implements EJBEventsObserver {
11 @Inject
12 @EventsRead(context = "reader")
13 Event<String> readEvent;
14
15 @Inject
16 private Logger log;
17
18 private ArrayList<Object> eventList = new ArrayList<Object>();
19
20 public void process(@Observes @EventsProcess String event) {
21 eventList.add(event);
22 log.info("EJBEventsObserverImpl.process() got " + event);
23 }
24
25 public void processRead(@Observes @EventsProcess @EventsRead(context = "resource") String event) {
26 eventList.add(event);
27 log.info("EJBEventsObserverImpl.processRead() got " + event);
28 }
29
30 public void processWrite(@Observes @EventsProcess @EventsWrite(context = "resource") String event) {
31 eventList.add(event);
32 log.info("EJBEventsObserverImpl.processWrite() got " + event);
33 }
34
35 public ArrayList<Object> getEventList() {
36 return new ArrayList<Object>(eventList);
37 }
38 }
39
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBEventsProcessRead.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Qualifier;
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.Inherited;
5 import java.lang.annotation.Retention;
6 import java.lang.annotation.Target;
7
8 import static java.lang.annotation.ElementType.FIELD;
9 import static java.lang.annotation.ElementType.PARAMETER;
10 import static java.lang.annotation.RetentionPolicy.RUNTIME;
11
12 @Qualifier
13 @Target({FIELD, PARAMETER})
14 @Retention(RUNTIME)
15 @Documented
16 @Inherited
17 public @interface EJBEventsProcessRead {
18 }
19
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBEventsProcessReadWrite.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Qualifier;
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.Inherited;
5 import java.lang.annotation.Retention;
6 import java.lang.annotation.Target;
7
8 import static java.lang.annotation.ElementType.FIELD;
9 import static java.lang.annotation.ElementType.PARAMETER;
10 import static java.lang.annotation.RetentionPolicy.RUNTIME;
11
12 @Qualifier
13 @Target({FIELD, PARAMETER})
14 @Retention(RUNTIME)
15 @Documented
16 @Inherited
17 public @interface EJBEventsProcessReadWrite {
18 }
19
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBEventsSource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Local;
3 import javax.ws.rs.PathParam;
4
5 @Local
6 public interface EJBEventsSource {
7 int createBook(EJBBook book);
8
9 EJBBook lookupBookById(@PathParam("id") int id);
10
11 boolean test();
12 }
13
+0
-78
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBEventsSourceImpl.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Stateless;
3 import javax.enterprise.event.Event;
4 import javax.inject.Inject;
5 import javax.ws.rs.PathParam;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.Response;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.Map;
11 import java.util.concurrent.atomic.AtomicInteger;
12 import java.util.logging.Logger;
13
14 @Stateless
15 public class EJBEventsSourceImpl implements EJBEventsSource {
16 private static Map<Integer, EJBBook> collection = new HashMap<Integer, EJBBook>();
17 private static AtomicInteger counter = new AtomicInteger();
18
19 @Inject
20 @EventsProcess
21 Event<String> processEvent;
22
23 @Inject
24 @EventsRead(context = "resource")
25 @EventsProcess
26 Event<String> readProcessEvent;
27
28 @Inject
29 @EventsWrite(context = "resource")
30 @EventsProcess
31 Event<String> writeProcessEvent;
32
33 @Inject
34 EJBEventsObserver eventObserver;
35
36 @Inject
37 private Logger log;
38
39 public boolean test() {
40 log.info("entering EJBEventsSourceImpl.test()");
41 ArrayList<Object> eventList = eventObserver.getEventList();
42 for (int i = 0; i < eventList.size(); i++) {
43 log.info(eventList.get(i).toString());
44 }
45 log.info("leaving EJBEventsSourceImpl.test()");
46 return true;
47 }
48
49 public int createBook(EJBBook book) {
50 log.info("entering EJBEventsSourceImpl.createBook()");
51 log.info("EJBEventsSourceImpl firing processEvent");
52 processEvent.fire("processEvent");
53 int id = counter.getAndIncrement();
54 book.setId(id);
55 collection.put(id, book);
56 log.info("stored: " + id + "->" + book);
57 log.info("EJBEventsSourceImpl firing readProcessEvent");
58 readProcessEvent.fire("readProcessEvent");
59 log.info("leaving EJBEventsSourceImpl.createBook()");
60 return id;
61 }
62
63 public EJBBook lookupBookById(@PathParam("id") int id) {
64 log.info("entering EJBEventsSourceImpl.lookupBookById(" + id + ")");
65 log.info("books: " + collection);
66 log.info("EJBEventsSourceImpl firing processEvent");
67 processEvent.fire("processEvent");
68 EJBBook book = collection.get(id);
69 log.info("EJBEventsSourceImpl firing writeProcessEvent");
70 writeProcessEvent.fire("writeProcessEvent");
71 if (book == null) {
72 throw new WebApplicationException(Response.Status.NOT_FOUND);
73 }
74 log.info("leaving EJBEventsSourceImpl.lookupBookById(" + id + ")");
75 return book;
76 }
77 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBLocalResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Local;
3 import javax.ws.rs.Path;
4
5 @Local
6 @Path("/")
7 public interface EJBLocalResource extends EJBResourceParent {
8 }
9
+0
-8
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBRemoteResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Remote;
3
4 @Remote
5 public interface EJBRemoteResource extends EJBResourceParent {
6 }
7
+0
-41
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EJBResourceParent.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2
3 import org.jboss.resteasy.test.cdi.util.Constants;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.PathParam;
10 import javax.ws.rs.Produces;
11
12 @Path("/")
13 public interface EJBResourceParent {
14 @GET
15 @Path("verifyScopes")
16 int verifyScopes();
17
18 @GET
19 @Path("verifyInjection")
20 int verifyInjection();
21
22 @POST
23 @Path("create")
24 @Consumes(Constants.MEDIA_TYPE_TEST_XML)
25 int createBook(EJBBook book);
26
27 @GET
28 @Path("book/{id:[0-9][0-9]*}")
29 @Produces(Constants.MEDIA_TYPE_TEST_XML)
30 EJBBook lookupBookById(@PathParam("id") int id);
31
32 @GET
33 @Path("uses/{count}")
34 int testUse(@PathParam("count") int count);
35
36 @GET
37 @Path("reset")
38 void reset();
39 }
40
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EjbExceptionUnwrapFooException.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 public class EjbExceptionUnwrapFooException extends RuntimeException {
3 private static final long serialVersionUID = 3316574183792636233L;
4 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EjbExceptionUnwrapFooExceptionMapper.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class EjbExceptionUnwrapFooExceptionMapper implements ExceptionMapper<EjbExceptionUnwrapFooException> {
8 public Response toResponse(EjbExceptionUnwrapFooException exception) {
9 return Response.status(409).build();
10 }
11
12 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EjbExceptionUnwrapFooResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Local;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6
7 @Local
8 @Path("/exception")
9 @Produces("text/plain")
10 public interface EjbExceptionUnwrapFooResource {
11 @GET
12 void testException();
13 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EjbExceptionUnwrapFooResourceBean.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Stateless;
3
4 @Stateless
5 public class EjbExceptionUnwrapFooResourceBean implements EjbExceptionUnwrapFooResource {
6 public void testException() {
7 throw new EjbExceptionUnwrapFooException();
8 }
9 }
+0
-9
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EjbExceptionUnwrapLocatingResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("/")
5 public interface EjbExceptionUnwrapLocatingResource {
6 @Path("locating")
7 EjbExceptionUnwrapSimpleResource getLocating();
8 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EjbExceptionUnwrapLocatingResourceBean.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.EJB;
3 import javax.ejb.Stateless;
4
5 @Stateless
6 public class EjbExceptionUnwrapLocatingResourceBean implements EjbExceptionUnwrapLocatingResource {
7 @EJB
8 EjbExceptionUnwrapSimpleResource simple;
9
10 public EjbExceptionUnwrapSimpleResource getLocating() {
11 return simple;
12 }
13 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EjbExceptionUnwrapSimpleResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.MatrixParam;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/")
12 public interface EjbExceptionUnwrapSimpleResource {
13 @GET
14 @Path("basic")
15 @Produces("text/plain")
16 String getBasic();
17
18 @PUT
19 @Path("basic")
20 @Consumes("text/plain")
21 void putBasic(String body);
22
23 @GET
24 @Path("queryParam")
25 @Produces("text/plain")
26 String getQueryParam(@QueryParam("param") String param);
27
28 @GET
29 @Path("matrixParam")
30 @Produces("text/plain")
31 String getMatrixParam(@MatrixParam("param") String param);
32
33 @GET
34 @Path("uriParam/{param}")
35 @Produces("text/plain")
36 int getUriParam(@PathParam("param") int param);
37 }
+0
-32
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EjbExceptionUnwrapSimpleResourceBean.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ejb.Stateless;
5
6 @Stateless
7 public class EjbExceptionUnwrapSimpleResourceBean implements EjbExceptionUnwrapSimpleResource {
8 private static Logger logger = Logger.getLogger(EjbExceptionUnwrapSimpleResourceBean.class);
9
10 public String getBasic() {
11 logger.info("getBasic()");
12 return "basic";
13 }
14
15 public void putBasic(String body) {
16 logger.info(body);
17 }
18
19 public String getQueryParam(String param) {
20 return param;
21 }
22
23 public String getMatrixParam(String param) {
24 return param;
25 }
26
27 public int getUriParam(int param) {
28 return param;
29 }
30
31 }
+0
-130
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.test.cdi.util.Constants;
3
4 import javax.enterprise.context.RequestScoped;
5 import javax.enterprise.event.Event;
6 import javax.inject.Inject;
7 import javax.ws.rs.Consumes;
8 import javax.ws.rs.GET;
9 import javax.ws.rs.POST;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.PathParam;
12 import javax.ws.rs.Produces;
13 import javax.ws.rs.WebApplicationException;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.core.Response;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.Map;
19 import java.util.concurrent.atomic.AtomicInteger;
20 import java.util.logging.Logger;
21
22 @Path("/")
23 @RequestScoped
24 public class EventResource {
25 private static Map<Integer, EJBBook> collection = new HashMap<Integer, EJBBook>();
26 private static AtomicInteger counter = new AtomicInteger();
27
28 @Inject
29 @EventsProcess
30 Event<String> processEvent;
31
32 @Inject
33 @EventsRead(context = "resource")
34 @EventsProcess
35 Event<String> readProcessEvent;
36
37 @Inject
38 @EventsWrite(context = "resource")
39 @EventsProcess
40 Event<String> writeProcessEvent;
41
42 @Inject
43 EventsBookReader bookReader;
44
45 @Inject
46 private Logger log;
47
48 @POST
49 @Path("test")
50 @Produces(MediaType.TEXT_PLAIN)
51 public Response test() {
52 log.info("entering EventResource.test()");
53 log.info("event list:");
54 ArrayList<Object> eventList = bookReader.getEventList();
55 for (int i = 0; i < eventList.size(); i++) {
56 log.info(eventList.get(i).toString());
57 }
58
59 ArrayList<String> expectedEvents = new ArrayList<>();
60 expectedEvents.add("readInterceptEvent");
61 expectedEvents.add("readInterceptEvent");
62 expectedEvents.add("readEvent");
63 expectedEvents.add("readEvent");
64 expectedEvents.add("processEvent");
65 expectedEvents.add("readProcessEvent");
66 expectedEvents.add("readProcessEvent");
67 expectedEvents.add("writeInterceptEvent");
68 expectedEvents.add("writeInterceptEvent");
69 expectedEvents.add("processEvent");
70 expectedEvents.add("writeProcessEvent");
71 expectedEvents.add("writeProcessEvent");
72 expectedEvents.add("writeInterceptEvent");
73 expectedEvents.add("writeInterceptEvent");
74 expectedEvents.add("writeEvent");
75 expectedEvents.add("writeEvent");
76
77 boolean status = true;
78 if (!(eventList.size() == expectedEvents.size())) {
79 status = false;
80 log.info(String.format("EventList should have %d events, not %d", expectedEvents.size(), eventList.size()));
81 }
82
83 for (int i = 0; i < Math.min(expectedEvents.size(), eventList.size()); i++) {
84 if (!expectedEvents.get(i).equals(eventList.get(i))) {
85 status = false;
86 log.info(String.format("%d. position: %s is found, %s is expected", i, eventList.get(i), expectedEvents.get(i)));
87 }
88 }
89
90 log.info("leaving EventResource.test()");
91 return status ? Response.ok().build() : Response.serverError().build();
92 }
93
94 @POST
95 @Path("create")
96 @Consumes(Constants.MEDIA_TYPE_TEST_XML)
97 @Produces(MediaType.TEXT_PLAIN)
98 public Response createBook(EJBBook book) {
99 log.info("entering EventResource.createBook()");
100 log.info("EventResource firing processEvent");
101 processEvent.fire("processEvent");
102 int id = counter.getAndIncrement();
103 book.setId(id);
104 collection.put(id, book);
105 log.info("stored: " + id + "->" + book);
106 log.info("EventResource firing readProcessEvent");
107 readProcessEvent.fire("readProcessEvent");
108 log.info("leaving EventResource.createBook()");
109 return Response.ok(id).build();
110 }
111
112 @GET
113 @Path("book/{id:[0-9][0-9]*}")
114 @Produces(Constants.MEDIA_TYPE_TEST_XML)
115 public EJBBook lookupBookById(@PathParam("id") int id) {
116 log.info("entering EventResource.lookupBookById(" + id + ")");
117 log.info("books: " + collection);
118 log.info("EventResource firing processEvent");
119 processEvent.fire("processEvent");
120 EJBBook book = collection.get(id);
121 log.info("EventResource firing writeProcessEvent");
122 writeProcessEvent.fire("writeProcessEvent");
123 if (book == null) {
124 throw new WebApplicationException(Response.Status.NOT_FOUND);
125 }
126 log.info("leaving EventResource.lookupBookById(" + id + ")");
127 return book;
128 }
129 }
+0
-107
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsBookReader.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4 import org.jboss.resteasy.test.cdi.util.Constants;
5
6 import javax.enterprise.event.Event;
7 import javax.enterprise.event.Observes;
8 import javax.inject.Inject;
9 import javax.ws.rs.Consumes;
10 import javax.ws.rs.WebApplicationException;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.MultivaluedMap;
13 import javax.ws.rs.ext.MessageBodyReader;
14 import javax.ws.rs.ext.Provider;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.lang.annotation.Annotation;
18 import java.lang.reflect.Type;
19 import java.util.ArrayList;
20
21 @Provider
22 @Consumes(Constants.MEDIA_TYPE_TEST_XML)
23 public class EventsBookReader implements MessageBodyReader<EJBBook> {
24 private static Logger log = Logger.getLogger(EventsBookReader.class);
25
26 private static MessageBodyReader<EJBBook> delegate;
27
28 @Inject
29 @EventsRead(context = "reader")
30 Event<String> readEvent;
31
32 private ArrayList<Object> eventList = new ArrayList<Object>();
33
34 static {
35 log.info("In BookReader static {}");
36 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
37 delegate = factory.getMessageBodyReader(EJBBook.class, null, null, Constants.MEDIA_TYPE_TEST_XML_TYPE);
38 log.info("In BookReader static {}");
39 }
40
41 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
42 log.info("entering BookReader.isReadable()");
43 boolean b = EJBBook.class.equals(type);
44 log.info("leaving BookReader.isReadable()");
45 return b;
46 }
47
48 public EJBBook readFrom(Class<EJBBook> type, Type genericType,
49 Annotation[] annotations, MediaType mediaType,
50 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
51 throws IOException, WebApplicationException {
52 log.info("entering BookReader.readFrom()");
53 EJBBook book = EJBBook.class.cast(delegate.readFrom(EJBBook.class, genericType, annotations, mediaType, httpHeaders, entityStream));
54 log.info("BookReader firing readEvent");
55 readEvent.fire("readEvent");
56 log.info("BookReader.readFrom() read " + book);
57 log.info("leaving BookReader.readFrom()");
58 return book;
59 }
60
61 public void readIntercept(@Observes @EventsReadIntercept String event) {
62 eventList.add(event);
63 log.info("BookReader.readIntercept() got " + event);
64 }
65
66 public void read(@Observes @EventsRead(context = "reader") String event) {
67 eventList.add(event);
68 log.info("BookReader.read() got " + event);
69 }
70
71 public void writeIntercept(@Observes @EventsWriteIntercept String event) {
72 eventList.add(event);
73 log.info("BookReader.writeIntercept() got " + event);
74 }
75
76 public void write(@Observes @EventsWrite(context = "writer") String event) {
77 eventList.add(event);
78 log.info("BookReader.write() got " + event);
79 }
80
81 public void process(@Observes @EventsProcess String event) {
82 eventList.add(event);
83 log.info("BookReader.process() got " + event);
84 }
85
86 public void processRead(@Observes @EventsProcess @EventsRead(context = "resource") String event) {
87 eventList.add(event);
88 log.info("BookReader.processRead() got " + event);
89 }
90
91 public void processWrite(@Observes @EventsProcess @EventsWrite(context = "resource") String event) {
92 eventList.add(event);
93 log.info("BookReader.processWrite() got " + event);
94 }
95
96 public void unused(@Observes @EventsRead(context = "unused") @EventsWrite(context = "unused") EventsUnused event) {
97 eventList.add(event);
98 log.info("BookReader.unused() got " + event);
99 throw new RuntimeException("BookReader.unused() got " + event);
100 }
101
102 public ArrayList<Object> getEventList() {
103 return new ArrayList<Object>(eventList);
104 }
105 }
106
+0
-35
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsBookReaderInterceptor.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3
4 import javax.enterprise.event.Event;
5 import javax.inject.Inject;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.ext.Provider;
8 import javax.ws.rs.ext.ReaderInterceptor;
9 import javax.ws.rs.ext.ReaderInterceptorContext;
10 import java.io.IOException;
11 import java.util.logging.Logger;
12
13 @Provider
14 @ServerInterceptor
15 public class EventsBookReaderInterceptor implements ReaderInterceptor {
16 @Inject
17 @EventsReadIntercept
18 Event<String> readInterceptEvent;
19
20 @Inject
21 private Logger log;
22
23 @Override
24 public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
25 log.info("*** Intercepting call in EventsBookReaderInterceptor.read()");
26 log.info("EventsBookReaderInterceptor firing readInterceptEvent");
27 readInterceptEvent.fire("readInterceptEvent");
28 Object result = context.proceed();
29 log.info("*** Back from intercepting call in EventsBookReaderInterceptor.read()");
30 return result;
31 }
32
33 }
34
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsBookWriter.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3 import org.jboss.resteasy.test.cdi.util.Constants;
4
5 import javax.enterprise.event.Event;
6 import javax.inject.Inject;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.WebApplicationException;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.MultivaluedMap;
11 import javax.ws.rs.ext.MessageBodyWriter;
12 import javax.ws.rs.ext.Provider;
13 import java.io.IOException;
14 import java.io.OutputStream;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17 import java.util.logging.Logger;
18
19 @Provider
20 @Produces(Constants.MEDIA_TYPE_TEST_XML)
21 public class EventsBookWriter implements MessageBodyWriter<EJBBook> {
22 private static MessageBodyWriter<EJBBook> delegate;
23
24 @Inject
25 @EventsWrite(context = "writer")
26 Event<String> writeEvent;
27
28 @Inject
29 private Logger log;
30
31 static {
32 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
33 delegate = factory.getMessageBodyWriter(EJBBook.class, null, null, Constants.MEDIA_TYPE_TEST_XML_TYPE);
34 }
35
36 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
37 log.info("entering BookWriter.isWriteable()");
38 boolean b = EJBBook.class.equals(type);
39 log.info("leaving BookWriter.isWriteable()");
40 return b;
41 }
42
43 public long getSize(EJBBook t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
44 log.info("entering BookWriter.getSize()");
45 log.info("leaving BookWriter.getSize()");
46 return -1;
47 }
48
49 @Override
50 public void writeTo(EJBBook t, Class<?> type, Type genericType,
51 Annotation[] annotations, MediaType mediaType,
52 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
53 throws IOException, WebApplicationException {
54 log.info("entering BookWriter.writeTo()");
55 log.info("BookWriter.writeTo() writing " + t);
56 delegate.writeTo(t, type, genericType, annotations, mediaType, httpHeaders, entityStream);
57 log.info("BookWriter firing writeEvent");
58 writeEvent.fire("writeEvent");
59 log.info("leaving BookWriter.writeTo()");
60 }
61 }
62
+0
-34
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsBookWriterInterceptor.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3
4 import javax.enterprise.event.Event;
5 import javax.inject.Inject;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.ext.Provider;
8 import javax.ws.rs.ext.WriterInterceptor;
9 import javax.ws.rs.ext.WriterInterceptorContext;
10 import java.io.IOException;
11 import java.util.logging.Logger;
12
13 @Provider
14 @ServerInterceptor
15 public class EventsBookWriterInterceptor implements WriterInterceptor {
16 @Inject
17 @EventsWriteIntercept
18 Event<String> writeInterceptEvent;
19
20 @Inject
21 private Logger log;
22
23 @Override
24 public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
25 log.info("*** Intercepting call in EventsBookWriterInterceptor.write()");
26 log.info("EventsBookWriterInterceptor firing writeInterceptEvent");
27 writeInterceptEvent.fire("writeInterceptEvent");
28 context.proceed();
29 log.info("*** Back from intercepting call in EventsBookWriterInterceptor.write()");
30 }
31
32 }
33
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsProcess.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Qualifier;
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.Inherited;
5 import java.lang.annotation.Retention;
6 import java.lang.annotation.Target;
7
8 import static java.lang.annotation.ElementType.FIELD;
9 import static java.lang.annotation.ElementType.PARAMETER;
10 import static java.lang.annotation.RetentionPolicy.RUNTIME;
11
12 @Qualifier
13 @Target({FIELD, PARAMETER})
14 @Retention(RUNTIME)
15 @Documented
16 @Inherited
17 public @interface EventsProcess {
18 }
19
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsRead.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Qualifier;
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.Inherited;
5 import java.lang.annotation.Retention;
6 import java.lang.annotation.Target;
7
8 import static java.lang.annotation.ElementType.FIELD;
9 import static java.lang.annotation.ElementType.PARAMETER;
10 import static java.lang.annotation.RetentionPolicy.RUNTIME;
11
12 @Qualifier
13 @Target({FIELD, PARAMETER})
14 @Retention(RUNTIME)
15 @Documented
16 @Inherited
17 public @interface EventsRead {
18 String context();
19 }
20
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsReadIntercept.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Qualifier;
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.Inherited;
5 import java.lang.annotation.Retention;
6 import java.lang.annotation.Target;
7
8 import static java.lang.annotation.ElementType.FIELD;
9 import static java.lang.annotation.ElementType.PARAMETER;
10 import static java.lang.annotation.RetentionPolicy.RUNTIME;
11
12 @Qualifier
13 @Target({FIELD, PARAMETER})
14 @Retention(RUNTIME)
15 @Documented
16 @Inherited
17 public @interface EventsReadIntercept {
18 }
19
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsUnused.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Qualifier;
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.Inherited;
5 import java.lang.annotation.Retention;
6 import java.lang.annotation.Target;
7
8 import static java.lang.annotation.ElementType.FIELD;
9 import static java.lang.annotation.ElementType.PARAMETER;
10 import static java.lang.annotation.RetentionPolicy.RUNTIME;
11
12 @Qualifier
13 @Target({FIELD, PARAMETER})
14 @Retention(RUNTIME)
15 @Documented
16 @Inherited
17 public @interface EventsUnused {
18 }
19
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsWrite.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Qualifier;
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.Inherited;
5 import java.lang.annotation.Retention;
6 import java.lang.annotation.Target;
7
8 import static java.lang.annotation.ElementType.FIELD;
9 import static java.lang.annotation.ElementType.PARAMETER;
10 import static java.lang.annotation.RetentionPolicy.RUNTIME;
11
12 @Qualifier
13 @Target({FIELD, PARAMETER})
14 @Retention(RUNTIME)
15 @Documented
16 @Inherited
17 public @interface EventsWrite {
18 String context();
19 }
20
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/EventsWriteIntercept.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.inject.Qualifier;
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.Inherited;
5 import java.lang.annotation.Retention;
6 import java.lang.annotation.Target;
7
8 import static java.lang.annotation.ElementType.FIELD;
9 import static java.lang.annotation.ElementType.PARAMETER;
10 import static java.lang.annotation.RetentionPolicy.RUNTIME;
11
12 @Qualifier
13 @Target({FIELD, PARAMETER})
14 @Retention(RUNTIME)
15 @Documented
16 @Inherited
17 public @interface EventsWriteIntercept {
18 }
19
+0
-87
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/OutOfBandResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import java.util.concurrent.CountDownLatch;
3
4 import javax.annotation.Resource;
5 import javax.ejb.Schedule;
6 import javax.ejb.SessionContext;
7 import javax.ejb.Stateless;
8 import javax.ejb.Timeout;
9 import javax.ejb.Timer;
10 import javax.ejb.TimerService;
11 import javax.interceptor.AroundTimeout;
12 import javax.interceptor.InvocationContext;
13 import javax.ws.rs.GET;
14 import javax.ws.rs.Path;
15 import javax.ws.rs.core.Response;
16
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 @Path("timer")
21 @Stateless
22 public class OutOfBandResource implements OutOfBandResourceIntf {
23 private static final Logger log = LoggerFactory.getLogger(OutOfBandResource.class);
24 private static final String TIMER_INFO = "timerInfo";
25 private static CountDownLatch latch = new CountDownLatch(1);
26 private static boolean timerExpired;
27 private static boolean timerInterceptorInvoked;
28
29 @Resource
30 private SessionContext ctx;
31 @Resource
32 private TimerService timerService;
33
34 @Override
35 @GET
36 @Path("schedule")
37 public Response scheduleTimer() {
38 timerService = ctx.getTimerService();
39 if (timerService != null) {
40 timerService.createTimer(1000, TIMER_INFO);
41 log.info("timer scheduled");
42 return Response.ok().build();
43 } else {
44 return Response.serverError().build();
45 }
46 }
47
48 @Schedule(second = "1")
49 public void automaticTimeout(Timer timer) {
50 log.info("entering automaticTimeout()");
51 timerExpired = true;
52 latch.countDown();
53 }
54
55 @Override
56 @GET
57 @Path("test")
58 public Response testTimer() throws InterruptedException {
59 log.info("entering testTimer()");
60 latch.await();
61 if (!timerInterceptorInvoked) {
62 return Response.serverError().entity("timerInterceptorInvoked == false").build();
63 }
64 if (!timerExpired) {
65 return Response.serverError().entity("timerExpired == false").build();
66 }
67 return Response.ok().build();
68 }
69
70 @Override
71 @Timeout
72 public void timeout(Timer timer) {
73 log.info("entering timeout()");
74 if (TIMER_INFO.equals(timer.getInfo())) {
75 timerExpired = true;
76 latch.countDown();
77 }
78 }
79
80 @AroundTimeout
81 public Object aroundTimeout(InvocationContext ctx) throws Exception {
82 timerInterceptorInvoked = true;
83 log.info("aroundTimeout() invoked");
84 return ctx.proceed();
85 }
86 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/OutOfBandResourceIntf.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Local;
3 import javax.ejb.Timeout;
4 import javax.ejb.Timer;
5 import javax.ws.rs.core.Response;
6
7 @Local
8 public interface OutOfBandResourceIntf {
9 Response scheduleTimer();
10
11 Response testTimer() throws InterruptedException;
12
13 @Timeout
14 void timeout(Timer timer);
15 }
+0
-8
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/SingletonLocalIF.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ws.rs.GET;
3
4 public interface SingletonLocalIF {
5 @GET
6 String get();
7 }
+0
-56
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/SingletonRootResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2
3 import javax.annotation.PostConstruct;
4 import javax.ejb.EJB;
5 import javax.ejb.EJBException;
6 import javax.ejb.Singleton;
7 import javax.ws.rs.GET;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.WebApplicationException;
10 import javax.ws.rs.core.Application;
11 import javax.ws.rs.core.Context;
12 import javax.ws.rs.core.Response;
13
14 @Singleton
15 @Path("root")
16 public class SingletonRootResource {
17 @EJB
18 SingletonSubResource sub;
19
20 @EJB
21 SingletonLocalIF rl;
22
23
24 @Path("sub")
25 public SingletonSubResource getSub() {
26 return sub;
27 }
28
29 @Path("intfsub")
30 public SingletonLocalIF getLocalSub() {
31 return rl;
32 }
33
34
35 @Context
36 private Application injectedApplication;
37 private boolean isJaxrsInjectedPriorToPostConstruct = false;
38
39 @PostConstruct
40 public void postConstruct() {
41 isJaxrsInjectedPriorToPostConstruct = injectedApplication != null;
42 }
43
44 @Path("injected")
45 @GET
46 public String injected() {
47 return String.valueOf(isJaxrsInjectedPriorToPostConstruct);
48 }
49
50 @Path("exception")
51 @GET
52 public String throwException() {
53 throw new EJBException(new WebApplicationException(Response.Status.CREATED));
54 }
55 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/SingletonSubResource.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Singleton;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.Produces;
5
6 @Singleton
7 public class SingletonSubResource {
8 @GET
9 @Produces("text/plain")
10 public String hello() {
11 return "hello";
12 }
13 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/basic/resource/SingletonTestBean.java less more
0 package org.jboss.resteasy.test.cdi.basic.resource;
1
2 import javax.ejb.Local;
3 import javax.ejb.Stateless;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.core.Context;
6 import javax.ws.rs.core.UriInfo;
7
8 @Stateless(name = "SingletonTestBean")
9 @Local({SingletonLocalIF.class})
10 public class SingletonTestBean implements SingletonLocalIF {
11
12 public SingletonTestBean() {
13 }
14
15 public void remove() {
16 }
17
18 @Context
19 private UriInfo ui;
20
21 @Override
22 @GET
23 public String get() {
24 return "GET: " + ui.getRequestUri().toASCIIString() +
25 " Hello From Singleton Local EJB Sub";
26 }
27 }
+0
-87
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/BeanExtensionTest.java less more
0 package org.jboss.resteasy.test.cdi.extensions;
1
2
3 import static org.junit.Assert.assertEquals;
4
5 import javax.enterprise.inject.spi.Extension;
6 import javax.ws.rs.client.Client;
7 import javax.ws.rs.client.ClientBuilder;
8 import javax.ws.rs.client.Entity;
9 import javax.ws.rs.client.WebTarget;
10 import javax.ws.rs.core.Response;
11
12 import org.apache.logging.log4j.Logger;
13 import org.apache.logging.log4j.LogManager;
14 import org.jboss.arquillian.container.test.api.Deployment;
15 import org.jboss.arquillian.container.test.api.RunAsClient;
16 import org.jboss.arquillian.junit.Arquillian;
17 import org.jboss.resteasy.test.cdi.extensions.resource.CDIExtensionsBoston;
18 import org.jboss.resteasy.test.cdi.extensions.resource.CDIExtensionsBostonBean;
19 import org.jboss.resteasy.test.cdi.extensions.resource.CDIExtensionsBostonBeanExtension;
20 import org.jboss.resteasy.test.cdi.extensions.resource.CDIExtensionsBostonHolder;
21 import org.jboss.resteasy.test.cdi.extensions.resource.CDIExtensionsBostonlLeaf;
22 import org.jboss.resteasy.test.cdi.extensions.resource.CDIExtensionsTestReader;
23 import org.jboss.resteasy.test.cdi.extensions.resource.CDIExtensionsResource;
24 import org.jboss.resteasy.test.cdi.util.Utilities;
25 import org.jboss.resteasy.test.cdi.util.UtilityProducer;
26 import org.jboss.resteasy.util.HttpResponseCodes;
27 import org.jboss.resteasy.utils.PortProviderUtil;
28 import org.jboss.resteasy.utils.TestUtil;
29 import org.jboss.shrinkwrap.api.Archive;
30 import org.jboss.shrinkwrap.api.ShrinkWrap;
31 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
32 import org.jboss.shrinkwrap.api.spec.JavaArchive;
33 import org.jboss.shrinkwrap.api.spec.WebArchive;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36
37 /**
38 * @tpSubChapter CDI
39 * @tpChapter Integration tests
40 * @tpTestCaseDetails Test CDI extensions for bean.
41 * BostonBeanExtension implements a CDI extension, it creates a BostonBean for each of the two classes,
42 * BostonHolder and BostonLeaf, that are annotated with @Boston, and it registers them with the CDI runtime.
43 * @tpSince RESTEasy 3.0.16
44 */
45 @RunWith(Arquillian.class)
46 @RunAsClient
47 public class BeanExtensionTest {
48 protected static final Logger log = LogManager.getLogger(BeanExtensionTest.class.getName());
49
50 @SuppressWarnings(value = "unchecked")
51 @Deployment
52 public static Archive<?> createTestArchive() {
53 WebArchive war = TestUtil.prepareArchive(BeanExtensionTest.class.getSimpleName());
54 war.addClasses(UtilityProducer.class, Utilities.class)
55 .addClasses(CDIExtensionsBostonBeanExtension.class, CDIExtensionsBoston.class, CDIExtensionsBostonBean.class)
56 .addClasses(CDIExtensionsResource.class, CDIExtensionsTestReader.class)
57 .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
58 .addAsServiceProvider(Extension.class, CDIExtensionsBostonBeanExtension.class);
59
60 JavaArchive jar = ShrinkWrap.create(JavaArchive.class).addClasses(CDIExtensionsBostonHolder.class, CDIExtensionsBostonlLeaf.class);
61 war.addAsLibrary(jar);
62
63 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
64 }
65
66 /**
67 * @tpTestDetails Client get request. Resource check extension bean on server.
68 * @tpPassCrit Response status should not contain error.
69 * @tpSince RESTEasy 3.0.16
70 */
71 @Test
72 public void testBostonBeans() throws Exception {
73 log.info("starting testBostonBeans()");
74
75 Client client = ClientBuilder.newClient();
76 WebTarget base = client.target(PortProviderUtil.generateURL("/extension/boston/", BeanExtensionTest.class.getSimpleName()));
77 Response response = base.request().post(Entity.text(new String()));
78
79 log.info("Response status: " + response.getStatus());
80
81 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
82
83 response.close();
84 client.close();
85 }
86 }
+0
-90
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/ScopeExtensionTest.java less more
0 package org.jboss.resteasy.test.cdi.extensions;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.test.cdi.extensions.resource.ScopeExtensionResource;
5 import org.jboss.resteasy.test.cdi.extensions.resource.ScopeExtensionObsolescent;
6 import org.jboss.resteasy.test.cdi.extensions.resource.ScopeExtensionObsolescentAfterThreeUses;
7 import org.jboss.resteasy.test.cdi.extensions.resource.ScopeExtensionObsolescentAfterTwoUses;
8 import org.jboss.resteasy.test.cdi.extensions.resource.ScopeExtensionPlannedObsolescenceContext;
9 import org.jboss.resteasy.test.cdi.extensions.resource.ScopeExtensionPlannedObsolescenceExtension;
10 import org.jboss.resteasy.test.cdi.extensions.resource.ScopeExtensionPlannedObsolescenceScope;
11 import org.jboss.resteasy.test.cdi.util.Utilities;
12 import org.jboss.resteasy.test.cdi.util.UtilityProducer;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
18 import org.jboss.shrinkwrap.api.spec.WebArchive;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.enterprise.inject.spi.Extension;
23 import javax.inject.Inject;
24 import javax.ws.rs.client.Client;
25 import javax.ws.rs.client.ClientBuilder;
26 import javax.ws.rs.client.Entity;
27 import javax.ws.rs.client.WebTarget;
28 import javax.ws.rs.core.Response;
29 import java.util.logging.Logger;
30
31 import static org.junit.Assert.assertEquals;
32
33 /**
34 * @tpSubChapter CDI
35 * @tpChapter Integration tests
36 * @tpTestCaseDetails CDIScopeExtensionTest tests that Resteasy interacts well with beans in
37 * a user defined scope.
38 * @tpSince RESTEasy 3.0.16
39 */
40 @RunWith(Arquillian.class)
41 public class ScopeExtensionTest {
42 @Inject
43 Logger log;
44
45 static Client client;
46
47 @Deployment
48 public static Archive<?> createTestArchive() {
49 WebArchive war = TestUtil.prepareArchive(ScopeExtensionTest.class.getSimpleName());
50 war.addClasses(UtilityProducer.class, Utilities.class, PortProviderUtil.class)
51 .addClasses(ScopeExtensionPlannedObsolescenceExtension.class, ScopeExtensionPlannedObsolescenceScope.class)
52 .addClasses(ScopeExtensionPlannedObsolescenceContext.class, ScopeExtensionResource.class)
53 .addClasses(ScopeExtensionObsolescent.class, ScopeExtensionObsolescentAfterTwoUses.class, ScopeExtensionObsolescentAfterThreeUses.class)
54 .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
55 .addAsServiceProvider(Extension.class, ScopeExtensionPlannedObsolescenceExtension.class);
56 return war;
57 }
58
59 private String generateURL(String path) {
60 return PortProviderUtil.generateURL(path, ScopeExtensionTest.class.getSimpleName());
61 }
62
63 /**
64 * @tpTestDetails Beans in scope test.
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testObsolescentScope() throws Exception {
69 client = ClientBuilder.newClient();
70
71 log.info("starting testScope()");
72 WebTarget base = client.target(generateURL("/extension/setup/"));
73 Response response = base.request().post(Entity.text(new String()));
74 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
75 response.close();
76
77 base = client.target(generateURL("/extension/test1/"));
78 response = base.request().post(Entity.text(new String()));
79 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
80 response.close();
81
82 base = client.target(generateURL("/extension/test2/"));
83 response = base.request().post(Entity.text(new String()));
84 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
85 response.close();
86
87 client.close();
88 }
89 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/CDIExtensionsBoston.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import static java.lang.annotation.ElementType.FIELD;
3 import static java.lang.annotation.ElementType.METHOD;
4 import static java.lang.annotation.ElementType.TYPE;
5 import static java.lang.annotation.RetentionPolicy.RUNTIME;
6
7 import java.lang.annotation.Documented;
8 import java.lang.annotation.Inherited;
9 import java.lang.annotation.Retention;
10 import java.lang.annotation.Target;
11
12 import javax.inject.Qualifier;
13
14 import static java.lang.annotation.ElementType.PARAMETER;
15
16 @Qualifier
17 @Target({TYPE, METHOD, FIELD, PARAMETER})
18 @Retention(RUNTIME)
19 @Documented
20 @Inherited
21 public @interface CDIExtensionsBoston {
22 }
23
+0
-157
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/CDIExtensionsBostonBean.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.test.cdi.util.Utilities;
4
5 import java.lang.annotation.Annotation;
6 import java.lang.reflect.Type;
7 import java.util.HashSet;
8 import java.util.Iterator;
9 import java.util.Set;
10
11 import javax.enterprise.context.ApplicationScoped;
12 import javax.enterprise.context.RequestScoped;
13 import javax.enterprise.context.spi.CreationalContext;
14 import javax.enterprise.inject.spi.Bean;
15 import javax.enterprise.inject.spi.InjectionPoint;
16 import javax.enterprise.inject.spi.InjectionTarget;
17 import javax.ws.rs.Path;
18 import javax.ws.rs.ext.Provider;
19
20 /**
21 * A BostonBean is just like other beans, only much, much better.
22 *
23 * BostonBeans are handled by the CDI extension BostonBeanExtension, and are implemented by classes
24 * annotated with @Boston.
25 */
26 public class CDIExtensionsBostonBean<T> implements Bean<T> {
27 private static Logger log = Logger.getLogger(CDIExtensionsBostonBean.class);
28
29 private Class<T> clazz;
30 private String className;
31 private InjectionTarget<T> injectionTarget;
32
33 private Set<Type> types;
34 private Set<Annotation> qualifiers;
35 private Class<? extends Annotation> scope;
36 private Set<InjectionPoint> injectionPoints;
37
38 public CDIExtensionsBostonBean(final Class<T> clazz, final InjectionTarget<T> injectionTarget) {
39 this.clazz = clazz;
40 this.className = clazz.getSimpleName();
41 this.injectionTarget = injectionTarget;
42 types = Utilities.getTypeClosure(clazz);
43 qualifiers = Utilities.getQualifiers(clazz);
44 injectionPoints = injectionTarget.getInjectionPoints();
45 scope = Utilities.getScopeAnnotation(clazz);
46 if (scope == null) {
47 if (Utilities.isAnnotationPresent(clazz, Path.class)) {
48 scope = RequestScoped.class;
49 } else if (Utilities.isAnnotationPresent(clazz, Provider.class)) {
50 scope = ApplicationScoped.class;
51 } else {
52 scope = RequestScoped.class;
53 }
54 }
55 }
56
57 @Override
58 public T create(CreationalContext<T> creationalContext) {
59 log.info("BostonBean[" + className + "].create()");
60 T instance = injectionTarget.produce(creationalContext);
61 log.info("BostonBean[" + className + "].create() raw instance: " + instance);
62 injectionTarget.inject(instance, creationalContext);
63 injectionTarget.postConstruct(instance);
64 log.info("BostonBean[" + className + "].create(): cooked instance: " + instance);
65 return instance;
66 }
67
68 @Override
69 public void destroy(T instance, CreationalContext<T> creationalContext) {
70 log.info("BostonBean[" + className + "].destroy()");
71 creationalContext.release();
72 }
73
74 @Override
75 public Set<Type> getTypes() {
76 log.info("BostonBean[" + className + "].getTypes()");
77 return types;
78 }
79
80 @Override
81 public Set<Annotation> getQualifiers() {
82 log.info("BostonBean[" + className + "].getQualifiers()");
83 return qualifiers;
84 }
85
86 @Override
87 public Class<? extends Annotation> getScope() {
88 log.info("BostonBean[" + className + "].getScope()");
89 return scope;
90 }
91
92 @Override
93 public String getName() {
94 log.info("BostonBean[" + className + "].getName()");
95 return null;
96 }
97
98 @Override
99 public Set<Class<? extends Annotation>> getStereotypes() {
100 log.info("BostonBean[" + className + "].getStereotypes()");
101 return new HashSet<Class<? extends Annotation>>();
102 }
103
104 @Override
105 public Class<?> getBeanClass() {
106 log.info("BostonBean[" + className + "].getBeanClass()");
107 return clazz;
108 }
109
110 @Override
111 public boolean isAlternative() {
112 log.info("BostonBean[" + className + "].isAlternative()");
113 return false;
114 }
115
116 @Override
117 public boolean isNullable() {
118 log.info("BostonBean[" + className + "].isNullable()");
119 return false;
120 }
121
122 @Override
123 public Set<InjectionPoint> getInjectionPoints() {
124 log.info("BostonBean[" + className + "].getInjectionPoints()");
125 return injectionPoints;
126 }
127
128 @Override
129 public String toString() {
130 StringBuilder sb = new StringBuilder("BostonBean[").append(clazz).append('\r').
131 append(" scope: ").append(scope).append('\r').
132 append(" types: ");
133 Iterator<Type> it1 = types.iterator();
134 while (it1.hasNext()) {
135 sb.append(it1.next()).append('\r').
136 append(" ");
137 }
138 sb.append('\r').
139 append(" qualifiers: ");
140 Iterator<Annotation> it2 = qualifiers.iterator();
141 while (it2.hasNext()) {
142 sb.append(it2.next()).append('\r').
143 append(" ");
144 }
145 sb.append('\r').
146 append(" injection points: ");
147 Iterator<InjectionPoint> it3 = getInjectionPoints().iterator();
148 while (it3.hasNext()) {
149 sb.append(it3.next()).append('\r').
150 append(" ");
151 }
152 sb.append('\r').
153 append("]");
154 return sb.toString();
155 }
156 }
+0
-30
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/CDIExtensionsBostonBeanExtension.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.enterprise.event.Observes;
5 import javax.enterprise.inject.spi.AfterBeanDiscovery;
6 import javax.enterprise.inject.spi.BeanManager;
7 import javax.enterprise.inject.spi.Extension;
8
9 /**
10 * BostonBeanExtension implements a CDI extension.
11 * In particular, it creates a BostonBean for each of the two classes,
12 * BostonHolder and BostonLeaf, that are annotated with @Boston, and it
13 * registers them with the CDI runtime.
14 */
15 public class CDIExtensionsBostonBeanExtension implements Extension {
16 private static Logger log = Logger.getLogger(CDIExtensionsBostonBeanExtension.class);
17
18 @SuppressWarnings({"rawtypes", "unchecked"})
19 void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager bm) {
20 log.info("AfterBeanDiscovery");
21 CDIExtensionsBostonBean<?> rb = new CDIExtensionsBostonBean(CDIExtensionsBostonHolder.class, bm.createInjectionTarget(bm.createAnnotatedType(CDIExtensionsBostonHolder.class)));
22 abd.addBean(rb);
23 log.info("registered " + rb.toString());
24
25 rb = new CDIExtensionsBostonBean(CDIExtensionsBostonlLeaf.class, bm.createInjectionTarget(bm.createAnnotatedType(CDIExtensionsBostonlLeaf.class)));
26 abd.addBean(rb);
27 log.info("registered " + rb.toString());
28 }
29 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/CDIExtensionsBostonHolder.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import javax.inject.Inject;
3
4 @CDIExtensionsBoston
5 public class CDIExtensionsBostonHolder {
6 @Inject public CDIExtensionsTestReader reader;
7
8 @Inject @CDIExtensionsBoston
9 public CDIExtensionsBostonlLeaf leaf;
10
11 public CDIExtensionsTestReader getReader() {
12 return reader;
13 }
14
15 public CDIExtensionsBostonlLeaf getLeaf() {
16 return leaf;
17 }
18
19 public String toString() {
20 return String.format("%nthis: %s%nreader: %s%nleaf: %s", System.identityHashCode(this), reader, leaf);
21 }
22 }
+0
-6
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/CDIExtensionsBostonlLeaf.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 @CDIExtensionsBoston
3 public class CDIExtensionsBostonlLeaf {
4 }
5
+0
-32
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/CDIExtensionsResource.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.test.cdi.util.Utilities;
4
5 import javax.enterprise.context.RequestScoped;
6 import javax.inject.Inject;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.core.Response;
10
11 @Path("/extension")
12 @RequestScoped
13 public class CDIExtensionsResource {
14 private static Logger log = Logger.getLogger(CDIExtensionsResource.class);
15
16 @Inject
17 @CDIExtensionsBoston
18 CDIExtensionsBostonHolder holder;
19
20 @POST
21 @Path("boston")
22 public Response setup() {
23 log.info("Injected object for response (holder): " + holder);
24 boolean response = true;
25 response &= Utilities.isBoston(holder.getClass());
26 response &= holder.getLeaf() != null;
27 response &= holder.getReader() != null;
28 return response ? Response.ok().build() : Response.serverError().build();
29 }
30
31 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/CDIExtensionsTestReader.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.Type;
6
7 import javax.ws.rs.Consumes;
8 import javax.ws.rs.WebApplicationException;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.MultivaluedMap;
11 import javax.ws.rs.ext.MessageBodyReader;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @Consumes("application/test+xml")
16 public class CDIExtensionsTestReader implements MessageBodyReader<Object> {
17 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
18 return false;
19 }
20
21 public Object readFrom(Class<Object> type, Type genericType,
22 Annotation[] annotations, MediaType mediaType,
23 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
24 throws IOException, WebApplicationException {
25 return null;
26 }
27 }
28
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/ScopeExtensionObsolescent.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 public interface ScopeExtensionObsolescent {
3
4 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/ScopeExtensionObsolescentAfterThreeUses.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import javax.inject.Inject;
3
4 @ScopeExtensionPlannedObsolescenceScope(3)
5 public class ScopeExtensionObsolescentAfterThreeUses implements ScopeExtensionObsolescent {
6 @Inject
7 private int secret;
8
9 public int getSecret() {
10 return secret;
11 }
12
13 public String toString() {
14 return "ObsolescenceObject[" + System.identityHashCode(this) + "," + secret + "]";
15 }
16 }
17
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/ScopeExtensionObsolescentAfterTwoUses.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import javax.inject.Inject;
3
4 @ScopeExtensionPlannedObsolescenceScope(2)
5 public class ScopeExtensionObsolescentAfterTwoUses implements ScopeExtensionObsolescent {
6 @Inject
7 private int secret;
8
9 public int getSecret() {
10 return secret;
11 }
12
13 public String toString() {
14 return "ObsolescenceObject[" + System.identityHashCode(this) + "," + secret + "]";
15 }
16 }
17
+0
-91
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/ScopeExtensionPlannedObsolescenceContext.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import javax.enterprise.context.spi.Context;
3 import javax.enterprise.context.spi.Contextual;
4 import javax.enterprise.context.spi.CreationalContext;
5 import java.lang.annotation.Annotation;
6 import java.util.HashMap;
7
8 public class ScopeExtensionPlannedObsolescenceContext implements Context {
9 private HashMap<Contextual<?>, Wrapper<?>> map = new HashMap<Contextual<?>, Wrapper<?>>();
10
11 @Override
12 public Class<? extends Annotation> getScope() {
13 return ScopeExtensionPlannedObsolescenceScope.class;
14 }
15
16 @Override
17 public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
18 @SuppressWarnings("unchecked")
19 Wrapper<T> w = (Wrapper<T>) map.get(contextual);
20 if (w != null) {
21 T o = w.object;
22 Class<?> c = o.getClass();
23 ScopeExtensionPlannedObsolescenceScope scope = c.getAnnotation(ScopeExtensionPlannedObsolescenceScope.class);
24 if (scope == null) {
25 throw new RuntimeException("Error");
26 }
27 if (++w.counter > scope.value()) {
28 contextual.destroy(o, creationalContext);
29 creationalContext.release();
30 o = contextual.create(creationalContext);
31 map.put(contextual, new Wrapper<T>(creationalContext, o));
32 }
33 return o;
34 } else {
35 T o = contextual.create(creationalContext);
36 map.put(contextual, new Wrapper<T>(creationalContext, o));
37 return o;
38 }
39 }
40
41 /**
42 * Technically, this version of get() should not create a new object, but,
43 * for purposes of the test, we destroy and recreate an object when it is
44 * obsolete.
45 */
46 @Override
47 public <T> T get(Contextual<T> contextual) {
48 @SuppressWarnings("unchecked")
49 Wrapper<T> w = (Wrapper<T>) map.get(contextual);
50 if (w == null) {
51 return null;
52 }
53
54 T o = w.object;
55 Class<?> c = o.getClass();
56 ScopeExtensionPlannedObsolescenceScope scope = c.getAnnotation(ScopeExtensionPlannedObsolescenceScope.class);
57 if (scope == null) {
58 throw new RuntimeException("Error");
59 }
60 CreationalContext<T> creationalContext = w.creationalContext;
61 if (++w.counter > scope.value()) {
62 contextual.destroy(o, creationalContext);
63 creationalContext.release();
64 map.remove(contextual);
65 // o = contextual.create(creationalContext);
66 // map.put(contextual, new Wrapper<T>(creationalContext, o));
67 o = null;
68 }
69 return o;
70 }
71
72 @Override
73 public boolean isActive() {
74 // TODO How should this be determined?
75 return true;
76 }
77
78 static class Wrapper<T> {
79 int counter;
80 CreationalContext<T> creationalContext;
81 T object;
82
83 Wrapper(final CreationalContext<T> creationalContext, final T object) {
84 this.creationalContext = creationalContext;
85 this.object = object;
86 counter = 1;
87 }
88 }
89 }
90
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/ScopeExtensionPlannedObsolescenceExtension.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import javax.enterprise.event.Observes;
3 import javax.enterprise.inject.spi.AfterBeanDiscovery;
4 import javax.enterprise.inject.spi.BeforeBeanDiscovery;
5 import javax.enterprise.inject.spi.Extension;
6
7 public class ScopeExtensionPlannedObsolescenceExtension implements Extension {
8 void beforeBeanDiscovery(@Observes BeforeBeanDiscovery event) {
9 event.addScope(ScopeExtensionPlannedObsolescenceScope.class, true, false);
10 }
11
12 void afterBeanDiscovery(@Observes AfterBeanDiscovery event) {
13 event.addContext(new ScopeExtensionPlannedObsolescenceContext());
14 }
15 }
16
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/ScopeExtensionPlannedObsolescenceScope.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2 import javax.enterprise.context.NormalScope;
3 import java.lang.annotation.Documented;
4 import java.lang.annotation.Inherited;
5 import java.lang.annotation.Retention;
6 import java.lang.annotation.Target;
7
8 import static java.lang.annotation.ElementType.FIELD;
9 import static java.lang.annotation.ElementType.METHOD;
10 import static java.lang.annotation.ElementType.TYPE;
11 import static java.lang.annotation.RetentionPolicy.RUNTIME;
12
13 @Target({TYPE, METHOD, FIELD})
14 @Retention(RUNTIME)
15 @Documented
16 @NormalScope
17 @Inherited
18 public @interface ScopeExtensionPlannedObsolescenceScope {
19 int value() default 1;
20 }
21
+0
-90
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/extensions/resource/ScopeExtensionResource.java less more
0 package org.jboss.resteasy.test.cdi.extensions.resource;
1
2
3 import org.jboss.resteasy.test.cdi.util.Utilities;
4
5 import javax.enterprise.context.RequestScoped;
6 import javax.inject.Inject;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.core.Response;
10 import java.util.logging.Logger;
11
12 @Path("/extension")
13 @RequestScoped
14 public class ScopeExtensionResource {
15 private static int lastSecret2;
16 private static int lastSecret3;
17
18 @Inject
19 private Logger log;
20 @Inject
21 private Utilities utilities;
22 @Inject
23 private ScopeExtensionObsolescentAfterTwoUses oo2;
24 @Inject
25 private ScopeExtensionObsolescentAfterThreeUses oo3;
26
27 @POST
28 @Path("setup")
29 public Response setup() {
30 log.info("ObsolescentObject scope: " + utilities.testScope(ScopeExtensionObsolescentAfterTwoUses.class, ScopeExtensionPlannedObsolescenceScope.class));
31 if (utilities.testScope(ScopeExtensionObsolescentAfterTwoUses.class, ScopeExtensionPlannedObsolescenceScope.class)) {
32 lastSecret2 = oo2.getSecret();
33 lastSecret3 = oo3.getSecret();
34 log.info("current secret2: " + lastSecret2);
35 log.info("current secret3: " + lastSecret3);
36 return Response.ok().build();
37 } else {
38 return Response.serverError().build();
39 }
40 }
41
42 @POST
43 @Path("test1")
44 public Response test1() {
45 int currentSecret2 = oo2.getSecret();
46 int currentSecret3 = oo3.getSecret();
47 log.info("last secret2: " + lastSecret2);
48 log.info("last secret3: " + lastSecret3);
49 log.info("current secret2: " + currentSecret2);
50 log.info("current secret3: " + currentSecret3);
51 if (currentSecret2 == lastSecret2 && currentSecret3 == lastSecret3) {
52 lastSecret2 = currentSecret2;
53 lastSecret3 = currentSecret3;
54 return Response.ok().build();
55 } else {
56 return Response.serverError().build();
57 }
58 }
59
60 @POST
61 @Path("test2")
62 public Response test2() {
63 int currentSecret2 = oo2.getSecret();
64 int currentSecret3 = oo3.getSecret();
65 log.info("last secret2: " + lastSecret2);
66 log.info("last secret3: " + lastSecret3);
67 log.info("current secret2: " + currentSecret2);
68 log.info("current secret3: " + currentSecret3);
69 if (currentSecret2 != lastSecret2 && currentSecret3 == lastSecret3) {
70 lastSecret3 = currentSecret3;
71 return Response.ok().build();
72 } else {
73 return Response.serverError().build();
74 }
75 }
76
77 @POST
78 @Path("test3")
79 public Response test3() {
80 int currentSecret3 = oo3.getSecret();
81 log.info("last secret3: " + lastSecret3);
82 log.info("current secret3: " + currentSecret3);
83 if (currentSecret3 != lastSecret3) {
84 return Response.ok().build();
85 } else {
86 return Response.serverError().build();
87 }
88 }
89 }
+0
-9
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/util/Constants.java less more
0 package org.jboss.resteasy.test.cdi.util;
1
2 import javax.ws.rs.core.MediaType;
3
4 public class Constants {
5 public static final String MEDIA_TYPE_TEST_XML = "application/test+xml";
6 public static final MediaType MEDIA_TYPE_TEST_XML_TYPE = MediaType.valueOf(MEDIA_TYPE_TEST_XML);
7 }
8
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/util/Counter.java less more
0 package org.jboss.resteasy.test.cdi.util;
1
2 import org.jboss.logging.Logger;
3
4 import java.util.concurrent.atomic.AtomicInteger;
5
6 import javax.ejb.Singleton;
7 import javax.enterprise.context.ApplicationScoped;
8
9 @Singleton
10 @CounterBinding
11 @ApplicationScoped
12 public class Counter {
13 private static Logger logger = Logger.getLogger(Counter.class);
14
15 public static final int INITIAL_VALUE = 17;
16 private static AtomicInteger counter = new AtomicInteger(INITIAL_VALUE);
17
18 public int getNext() {
19 logger.info("In Counter: counter: " + counter);
20 return counter.getAndIncrement();
21 }
22
23 public void reset() {
24 counter.set(INITIAL_VALUE);
25 }
26 }
27
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/util/CounterBinding.java less more
0 package org.jboss.resteasy.test.cdi.util;
1
2 import static java.lang.annotation.ElementType.FIELD;
3 import static java.lang.annotation.ElementType.METHOD;
4 import static java.lang.annotation.ElementType.PARAMETER;
5 import static java.lang.annotation.ElementType.TYPE;
6 import static java.lang.annotation.RetentionPolicy.RUNTIME;
7
8 import java.lang.annotation.Retention;
9 import java.lang.annotation.Target;
10
11 import javax.inject.Qualifier;
12
13 @Qualifier
14 @Retention(RUNTIME)
15 @Target({METHOD, FIELD, PARAMETER, TYPE})
16 public @interface CounterBinding {
17 }
+0
-176
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/util/Utilities.java less more
0 package org.jboss.resteasy.test.cdi.util;
1
2
3 import org.jboss.resteasy.test.cdi.extensions.resource.CDIExtensionsBoston;
4
5 import java.lang.annotation.Annotation;
6 import java.lang.reflect.Type;
7 import java.util.Arrays;
8 import java.util.HashSet;
9 import java.util.Iterator;
10 import java.util.Set;
11
12 import javax.ejb.Singleton;
13 import javax.enterprise.context.ApplicationScoped;
14 import javax.enterprise.context.Dependent;
15 import javax.enterprise.context.NormalScope;
16 import javax.enterprise.context.RequestScoped;
17 import javax.enterprise.context.SessionScoped;
18 import javax.enterprise.inject.spi.Bean;
19 import javax.enterprise.inject.spi.BeanManager;
20 import javax.inject.Inject;
21 import javax.inject.Qualifier;
22
23 @Singleton
24 public class Utilities {
25 @Inject
26 private BeanManager beanManager;
27
28 public static Class<? extends Annotation> getScopeAnnotation(Class<?> c) {
29
30 return getScopeAnnotation(c.getAnnotations());
31 }
32
33 public static Class<? extends Annotation> getScopeAnnotation(Annotation[] annotations) {
34 for (int i = 0; i < annotations.length; i++) {
35 Class<? extends Annotation> annotationType = annotations[i].annotationType();
36 Annotation[] typeAnnotations = annotationType.getAnnotations();
37 for (int j = 0; j < typeAnnotations.length; j++) {
38 if (NormalScope.class.equals(typeAnnotations[j].annotationType())) {
39 return annotationType;
40 }
41 }
42 }
43 return null;
44 }
45
46 public static Class<? extends Annotation> getScopeAnnotation(Set<Annotation> annotations) {
47 for (Annotation annotation : annotations) {
48 Class<? extends Annotation> annotationType = annotation.annotationType();
49 Annotation[] typeAnnotations = annotationType.getAnnotations();
50 for (int j = 0; j < typeAnnotations.length; j++) {
51 if (NormalScope.class.equals(typeAnnotations[j].annotationType())) {
52 return annotationType;
53 }
54 }
55 }
56 return null;
57 }
58
59 public static Set<Annotation> getQualifiers(Class<?> clazz) {
60 return getQualifiers(clazz.getAnnotations());
61 }
62
63 public static Set<Annotation> getQualifiers(Annotation[] annotations) {
64 HashSet<Annotation> result = new HashSet<Annotation>();
65 for (int i = 0; i < annotations.length; i++) {
66 Class<?> annotationType = annotations[i].annotationType();
67 Annotation[] typeAnnotations = annotationType.getAnnotations();
68 for (int j = 0; j < typeAnnotations.length; j++) {
69 if (Qualifier.class.equals(typeAnnotations[j].annotationType())) {
70 result.add(annotations[i]);
71 break;
72 }
73 }
74 }
75 return result;
76 }
77
78 public static boolean hasQualifier(Class<?> clazz, Class<?> qualifier) {
79 Annotation[] annotations = clazz.getAnnotations();
80 for (int i = 0; i < annotations.length; i++) {
81 if (qualifier.equals(annotations[i].annotationType())) {
82 return true;
83 }
84 }
85 return false;
86 }
87
88 public static boolean hasQualifier(Set<Annotation> annotations, Class<?> qualifier) {
89 for (Annotation annotation : annotations) {
90 if (qualifier.equals(annotation.annotationType())) {
91 return true;
92 }
93 }
94 return false;
95 }
96
97 public static boolean isBoston(Class<?> clazz) {
98 return hasQualifier(clazz, CDIExtensionsBoston.class);
99 }
100
101 public static Set<Type> getTypeClosure(Class<?> clazz) {
102 HashSet<Type> set = new HashSet<Type>();
103 accumulateTypes(set, clazz);
104 return set;
105 }
106
107 static void accumulateTypes(Set<Type> set, Class<?> clazz) {
108 set.add(clazz);
109 if (clazz.getSuperclass() != null) {
110 accumulateTypes(set, clazz.getSuperclass());
111 }
112 for (Class<?> c : clazz.getInterfaces()) {
113 accumulateTypes(set, c);
114 }
115 }
116
117 public static Set<Annotation> getAnnotationSet(Class<?> clazz) {
118 return new HashSet<Annotation>(Arrays.asList(clazz.getAnnotations()));
119 }
120
121 public static boolean isAnnotationPresent(Class<?> clazz, Class<? extends Annotation> annotationType) {
122 for (Annotation annotation : clazz.getAnnotations()) {
123 if (annotation.annotationType().equals(annotationType)) {
124 return true;
125 }
126 }
127 return false;
128 }
129
130 @SuppressWarnings("unchecked")
131 public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> annotationType) {
132 for (Annotation annotation : clazz.getAnnotations()) {
133 if (annotation.annotationType().equals(annotationType)) {
134 return (T) annotation;
135 }
136 }
137 return null;
138 }
139
140 public boolean isApplicationScoped(Class<?> c) {
141 return testScope(c, ApplicationScoped.class);
142 }
143
144 public boolean isDependentScoped(Class<?> c) {
145 return testScope(c, Dependent.class);
146 }
147
148 public boolean isRequestScoped(Class<?> c) {
149 return testScope(c, RequestScoped.class);
150 }
151
152 public boolean isSessionScoped(Class<?> c) {
153 return testScope(c, SessionScoped.class);
154 }
155
156 public boolean testScope(Class<?> c, Class<?> scopeClass) {
157 Class<? extends Annotation> annotation = getScope(c);
158 if (annotation == null) {
159 return false;
160 }
161 return annotation.isAssignableFrom(scopeClass);
162 }
163
164 public Class<? extends Annotation> getScope(Class<?> c) {
165 Set<Bean<?>> beans = beanManager.getBeans(c);
166 if (beans != null && !beans.isEmpty()) {
167 Iterator<Bean<?>> it = beans.iterator();
168 if (it.hasNext()) {
169 Bean<?> bean = beans.iterator().next();
170 return bean.getScope();
171 }
172 }
173 return null;
174 }
175 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/cdi/util/UtilityProducer.java less more
0 package org.jboss.resteasy.test.cdi.util;
1
2 import java.util.Random;
3 import java.util.logging.Logger;
4
5 import javax.enterprise.inject.Produces;
6 import javax.enterprise.inject.spi.InjectionPoint;
7
8 public class UtilityProducer {
9 private static Random random = new Random();
10
11 @Produces
12 public Logger produceLog(InjectionPoint injectionPoint) {
13 return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
14 }
15
16 @Produces
17 public int randomInt() {
18 return random.nextInt();
19 }
20 }
+0
-542
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/AsyncInvokeTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.client.resource.AsyncInvokeResource;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.TestUtil;
8 import org.jboss.shrinkwrap.api.Archive;
9 import org.jboss.shrinkwrap.api.spec.WebArchive;
10 import org.junit.Test;
11 import org.junit.Before;
12 import org.junit.After;
13 import org.junit.Assert;
14 import org.junit.runner.RunWith;
15
16 import javax.ws.rs.HttpMethod;
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.client.Entity;
20 import javax.ws.rs.client.InvocationCallback;
21 import javax.ws.rs.core.Response;
22 import java.lang.annotation.ElementType;
23 import java.lang.annotation.Retention;
24 import java.lang.annotation.RetentionPolicy;
25 import java.util.concurrent.Future;
26
27 /**
28 * @tpSubChapter Resteasy-client
29 * @tpChapter Client tests
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class AsyncInvokeTest extends ClientTestBase{
35
36 @java.lang.annotation.Target({ElementType.METHOD})
37 @Retention(RetentionPolicy.RUNTIME)
38 @HttpMethod("PATCH")
39 public @interface PATCH {
40 }
41
42 static Client client;
43
44 @Deployment
45 public static Archive<?> deploy() {
46 WebArchive war = TestUtil.prepareArchive(AsyncInvokeTest.class.getSimpleName());
47 war.addClass(AsyncInvokeTest.class);
48 war.addClass(ClientTestBase.class);
49 return TestUtil.finishContainerPrepare(war, null, AsyncInvokeResource.class);
50 }
51
52 @Before
53 public void init() {
54 client = ClientBuilder.newClient();
55 }
56
57 @After
58 public void after() throws Exception {
59 client.close();
60 }
61
62 /**
63 * @tpTestDetails Client sends async GET requests. First request expects Response object in return,
64 * the second expects String object in return
65 * @tpPassCrit Successful response is returned
66 * @tpSince RESTEasy 3.0.16
67 */
68 @Test
69 public void AsyncGetTest() throws Exception {
70 {
71 Future<Response> future = client.target(generateURL("/test")).request().async().get();
72 Response res = future.get();
73 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
74 String entity = res.readEntity(String.class);
75 Assert.assertEquals("get", entity);
76 }
77
78 {
79 Future<String> future = client.target(generateURL("/test")).request().async().get(String.class);
80 String entity = future.get();
81 Assert.assertEquals("get", entity);
82 }
83 }
84
85 /**
86 * @tpTestDetails Client sends async DELETE requests. First request expects Response object in return,
87 * the second expects String object in return
88 * @tpPassCrit Successful response is returned
89 * @tpSince RESTEasy 3.0.16
90 */
91 @Test
92 public void AsyncDeleteTest() throws Exception {
93
94 {
95 Future<Response> future = client.target(generateURL("/test")).request().async().delete();
96 Response res = future.get();
97 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
98 String entity = res.readEntity(String.class);
99 Assert.assertEquals("delete", entity);
100 }
101
102 {
103 Future<String> future = client.target(generateURL("/test")).request().async().delete(String.class);
104 String entity = future.get();
105 Assert.assertEquals("delete", entity);
106 }
107 }
108
109 /**
110 * @tpTestDetails Client sends async PUT requests. First request expects Response object in return,
111 * the second expects String object in return
112 * @tpPassCrit Successful response is returned
113 * @tpSince RESTEasy 3.0.16
114 */
115 @Test
116 public void AsyncPutTest() throws Exception {
117 {
118 Future<Response> future = client.target(generateURL("/test")).request().async().put(Entity.text("hello"));
119 Response res = future.get();
120 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
121 String entity = res.readEntity(String.class);
122 Assert.assertEquals("put hello", entity);
123 }
124
125 {
126 Future<String> future = client.target(generateURL("/test")).request().async().put(Entity.text("hello"), String.class);
127 String entity = future.get();
128 Assert.assertEquals("put hello", entity);
129 }
130 }
131
132 /**
133 * @tpTestDetails Client sends async POST requests. First request expects Response object in return,
134 * the second expects String object in return
135 * @tpPassCrit Successful response is returned
136 * @tpSince RESTEasy 3.0.16
137 */
138 @Test
139 public void AsyncPostTest() throws Exception {
140 {
141 Future<Response> future = client.target(generateURL("/test")).request().async().post(Entity.text("hello"));
142 Response res = future.get();
143 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
144 String entity = res.readEntity(String.class);
145 Assert.assertEquals("post hello", entity);
146
147 }
148
149 {
150 Future<String> future = client.target(generateURL("/test")).request().async().post(Entity.text("hello"), String.class);
151 String entity = future.get();
152 Assert.assertEquals("post hello", entity);
153
154 }
155 }
156
157 /**
158 * @tpTestDetails Client sends async custom PATCH requests. First request expects Response object in return,
159 * the second expects String object in return
160 * @tpPassCrit Successful response is returned
161 * @tpSince RESTEasy 3.0.16
162 */
163 @Test
164 public void AsyncCustomMethodTest() throws Exception {
165 {
166 Future<Response> future = client.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"));
167 Response res = future.get();
168 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
169 String entity = res.readEntity(String.class);
170 Assert.assertEquals("patch hello", entity);
171 }
172
173 {
174 Future<String> future = client.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"), String.class);
175 String entity = future.get();
176 Assert.assertEquals("patch hello", entity);
177 }
178 }
179
180 static boolean ok;
181
182 /**
183 * @tpTestDetails Client sends async GET requests using Asynchronous InvocationCallback. First request expects Response object in return,
184 * the second expects String object in return
185 * @tpPassCrit Successful response is returned
186 * @tpSince RESTEasy 3.0.16
187 */
188 @Test
189 public void AsyncCallbackGetTest() throws Exception {
190 {
191 ok = false;
192 Future<Response> future = client.target(generateURL("/test")).request().async().get(new InvocationCallback<Response>() {
193 @Override
194 public void completed(Response response) {
195 String entity = response.readEntity(String.class);
196 Assert.assertEquals("get", entity);
197 ok = true;
198 }
199
200 @Override
201 public void failed(Throwable error) {
202 }
203 });
204 Response res = future.get();
205 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
206 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
207
208 }
209
210 {
211 ok = false;
212 Future<String> future = client.target(generateURL("/test")).request().async().get(new InvocationCallback<String>() {
213 @Override
214 public void completed(String entity) {
215 Assert.assertEquals("get", entity);
216 ok = true;
217 }
218
219 @Override
220 public void failed(Throwable error) {
221 }
222 });
223 String entity = future.get();
224 Assert.assertEquals("get", entity);
225 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
226 }
227 }
228
229 /**
230 * @tpTestDetails Client sends async DELETE requests using Asynchronous InvocationCallback. First request expects Response object in return,
231 * the second expects String object in return
232 * @tpPassCrit Successful response is returned
233 * @tpSince RESTEasy 3.0.16
234 */
235 @Test
236 public void AsyncCallbackDeleteTest() throws Exception {
237
238 {
239 ok = false;
240 Future<Response> future = client.target(generateURL("/test")).request().async().delete(new InvocationCallback<Response>() {
241 @Override
242 public void completed(Response response) {
243 String entity = response.readEntity(String.class);
244 Assert.assertEquals("delete", entity);
245 ok = true;
246 }
247
248 @Override
249 public void failed(Throwable error) {
250 }
251 });
252 Response res = future.get();
253 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
254 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
255 }
256
257 {
258 ok = false;
259 Future<String> future = client.target(generateURL("/test")).request().async().delete(new InvocationCallback<String>() {
260 @Override
261 public void completed(String s) {
262 Assert.assertEquals("delete", s);
263 ok = true;
264 }
265
266 @Override
267 public void failed(Throwable error) {
268 }
269 });
270 String entity = future.get();
271 Assert.assertEquals("delete", entity);
272 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
273 }
274 }
275
276
277 /**
278 * @tpTestDetails Client sends async PUT requests using Asynchronous InvocationCallback. First request expects Response object in return,
279 * the second expects String object in return
280 * @tpPassCrit Successful response is returned
281 * @tpSince RESTEasy 3.0.16
282 */
283 @Test
284 public void AsyncCallbackPutTest() throws Exception {
285 {
286 ok = false;
287 Future<Response> future = client.target(generateURL("/test")).request().async().put(Entity.text("hello"), new InvocationCallback<Response>() {
288 @Override
289 public void completed(Response response) {
290 String entity = response.readEntity(String.class);
291 Assert.assertEquals("put hello", entity);
292 ok = true;
293 }
294
295 @Override
296 public void failed(Throwable error) {
297 }
298 });
299 Response res = future.get();
300 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
301 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
302
303 }
304 {
305 ok = false;
306 Future<String> future = client.target(generateURL("/test")).request().async().put(Entity.text("hello"), new InvocationCallback<String>() {
307 @Override
308 public void completed(String s) {
309 Assert.assertEquals("put hello", s);
310 ok = true;
311 }
312
313 @Override
314 public void failed(Throwable error) {
315 }
316 });
317 String entity = future.get();
318 Assert.assertEquals("put hello", entity);
319 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
320
321 }
322 }
323
324 /**
325 * @tpTestDetails Client sends async POST requests using Asynchronous InvocationCallback. First request expects Response object in return,
326 * the second expects String object in return
327 * @tpPassCrit Successful response is returned
328 * @tpSince RESTEasy 3.0.16
329 */
330 @Test
331 public void AsyncCallbackPostTest() throws Exception {
332 {
333 ok = false;
334 Future<Response> future = client.target(generateURL("/test")).request().async().post(Entity.text("hello"), new InvocationCallback<Response>() {
335 @Override
336 public void completed(Response response) {
337 String entity = response.readEntity(String.class);
338 Assert.assertEquals("post hello", entity);
339 ok = true;
340 }
341
342 @Override
343 public void failed(Throwable error) {
344 }
345 });
346 Response res = future.get();
347 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
348 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
349
350 }
351 {
352 ok = false;
353 Future<String> future = client.target(generateURL("/test")).request().async().post(Entity.text("hello"), new InvocationCallback<String>() {
354 @Override
355 public void completed(String s) {
356 Assert.assertEquals("post hello", s);
357 ok = true;
358 }
359
360 @Override
361 public void failed(Throwable error) {
362 }
363 });
364 String entity = future.get();
365 Assert.assertEquals("post hello", entity);
366 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
367
368 }
369 }
370
371 /**
372 * @tpTestDetails Client sends async custom PATCH requests using Asynchronous InvocationCallback. First request expects Response object in return,
373 * the second expects String object in return
374 * @tpPassCrit Successful response is returned
375 * @tpSince RESTEasy 3.0.16
376 */
377 @Test
378 public void AsyncCallbackCustomMethodTest() throws Exception {
379 {
380 ok = false;
381 Future<Response> future = client.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"), new InvocationCallback<Response>() {
382 @Override
383 public void completed(Response response) {
384 String entity = response.readEntity(String.class);
385 Assert.assertEquals("patch hello", entity);
386 ok = true;
387 }
388
389 @Override
390 public void failed(Throwable error) {
391 }
392 });
393 Response res = future.get();
394 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
395 Assert.assertTrue("Asynchronous invocation didn't use custom implemented Invocation callback", ok);
396
397 }
398 {
399 ok = false;
400 Future<String> future = client.target(generateURL("/test")).request().async().method("PATCH", Entity.text("hello"), new InvocationCallback<String>() {
401 @Override
402 public void completed(String s) {
403 Assert.assertEquals("patch hello", s);
404 ok = true;
405 }
406
407 @Override
408 public void failed(Throwable error) {
409 }
410 });
411 String entity = future.get();
412 Assert.assertEquals("patch hello", entity);
413 Assert.assertTrue( "Asynchronous invocation didn't use custom implemented Invocation callback", ok);
414
415 }
416 }
417
418
419 /**
420 * @tpTestDetails Client sends async GET requests using submit() method to send request as asynchronous
421 * (opposite of invoke() method). First request expects Response object in return,
422 * the second expects String object in return
423 * @tpPassCrit Successful response is returned
424 * @tpSince RESTEasy 3.0.16
425 */
426 @Test
427 public void SubmitGetTest() throws Exception {
428
429 {
430 Future<Response> future = client.target(generateURL("/test")).request().buildGet().submit();
431 Response res = future.get();
432 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
433 String entity = res.readEntity(String.class);
434 Assert.assertEquals("get", entity);
435 }
436
437 {
438 Future<String> future = client.target(generateURL("/test")).request().buildGet().submit(String.class);
439 String entity = future.get();
440 Assert.assertEquals("get", entity);
441 }
442 }
443
444 /**
445 * @tpTestDetails Client sends async DELETE requests using submit() method to send request as asynchronous
446 * (opposite of invoke() method). First request expects Response object in return,
447 * the second expects String object in return
448 * @tpPassCrit Successful response is returned
449 * @tpSince RESTEasy 3.0.16
450 */
451 @Test
452 public void SubmitDeleteTest() throws Exception {
453 {
454 Future<Response> future = client.target(generateURL("/test")).request().buildDelete().submit();
455 Response res = future.get();
456 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
457 String entity = res.readEntity(String.class);
458 Assert.assertEquals("delete", entity);
459 }
460
461 {
462 Future<String> future = client.target(generateURL("/test")).request().buildDelete().submit(String.class);
463 String entity = future.get();
464 Assert.assertEquals("delete", entity);
465 }
466 }
467
468 /**
469 * @tpTestDetails Client sends async PUT requests using submit() method to send request as asynchronous
470 * (opposite of invoke() method). First request expects Response object in return,
471 * the second expects String object in return
472 * @tpPassCrit Successful response is returned
473 * @tpSince RESTEasy 3.0.16
474 */
475 @Test
476 public void SubmitPutTest() throws Exception {
477 {
478 Future<Response> future = client.target(generateURL("/test")).request().buildPut(Entity.text("hello")).submit();
479 Response res = future.get();
480 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
481 String entity = res.readEntity(String.class);
482 Assert.assertEquals("put hello", entity);
483 }
484
485 {
486 Future<String> future = client.target(generateURL("/test")).request().buildPut(Entity.text("hello")).submit(String.class);
487 String entity = future.get();
488 Assert.assertEquals("put hello", entity);
489 }
490 }
491
492
493 /**
494 * @tpTestDetails Client sends async POST requests using submit() method to send request as asynchronous
495 * (opposite of invoke() method). First request expects Response object in return,
496 * the second expects String object in return
497 * @tpPassCrit Successful response is returned
498 * @tpSince RESTEasy 3.0.16
499 */
500 @Test
501 public void SubmitPostTest() throws Exception {
502 {
503 Future<Response> future = client.target(generateURL("/test")).request().buildPost(Entity.text("hello")).submit();
504 Response res = future.get();
505 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
506 String entity = res.readEntity(String.class);
507 Assert.assertEquals("post hello", entity);
508 }
509
510 {
511 Future<String> future = client.target(generateURL("/test")).request().buildPost(Entity.text("hello")).submit(String.class);
512 String entity = future.get();
513 Assert.assertEquals("post hello", entity);
514 }
515 }
516
517
518 /**
519 * @tpTestDetails Client sends async custom PATCH requests using submit() method to send request as asynchronous
520 * (opposite of invoke() method). First request expects Response object in return,
521 * the second expects String object in return
522 * @tpPassCrit Successful response is returned
523 * @tpSince RESTEasy 3.0.16
524 */
525 @Test
526 public void SubmitCustomMethodTest() throws Exception {
527 {
528 Future<Response> future = client.target(generateURL("/test")).request().build("PATCH", Entity.text("hello")).submit();
529 Response res = future.get();
530 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
531 String entity = res.readEntity(String.class);
532 Assert.assertEquals("patch hello", entity);
533 }
534
535 {
536 Future<String> future = client.target(generateURL("/test")).request().build("PATCH", Entity.text("hello")).submit(String.class);
537 String entity = future.get();
538 Assert.assertEquals("patch hello", entity);
539 }
540 }
541 }
+0
-88
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientBuilderTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.category.NotForForwardCompatibility;
5 import org.jboss.resteasy.utils.TestUtil;
6 import org.jboss.shrinkwrap.api.Archive;
7 import org.jboss.shrinkwrap.api.spec.WebArchive;
8 import org.junit.Assert;
9 import org.junit.Test;
10 import org.junit.experimental.categories.Category;
11 import org.junit.runner.RunWith;
12
13 import javax.ws.rs.client.Client;
14 import javax.ws.rs.client.ClientBuilder;
15 import javax.ws.rs.core.Feature;
16 import javax.ws.rs.core.FeatureContext;
17
18 /**
19 * @tpSubChapter Resteasy-client
20 * @tpChapter Unit tests
21 * @tpSince RESTEasy 3.0.17
22 */
23 @RunWith(Arquillian.class)
24 public class ClientBuilderTest {
25
26 @SuppressWarnings(value = "unchecked")
27 @Deployment
28 public static Archive<?> deploy() {
29 WebArchive war = TestUtil.prepareArchive(ClientBuilderTest.class.getSimpleName());
30 war.addClass(TestUtil.class);
31 war.addClass(NotForForwardCompatibility.class);
32 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
33 }
34
35
36 public static class FeatureReturningFalse implements Feature {
37 @Override
38 public boolean configure(FeatureContext context) {
39 // false returning feature is not to be registered
40 return false;
41 }
42 }
43
44 private int getWarningCount() {
45 return TestUtil.getWarningCount("RESTEASY002155", true);
46 }
47
48 /**
49 * @tpTestDetails Register class twice to the client
50 * @tpPassCrit Warning will be raised that second class registration is ignored
51 * @tpSince RESTEasy 3.0.17
52 */
53 @Test
54 public void testDoubleClassRegistration() {
55 int initCount = getWarningCount();
56 Client client = ClientBuilder.newClient();
57 int count = client.getConfiguration().getClasses().size();
58 client.register(FeatureReturningFalse.class).register(FeatureReturningFalse.class);
59
60 Assert.assertEquals("RESTEASY002155 log not found", 1, getWarningCount() - initCount);
61 Assert.assertEquals(count + 1, client.getConfiguration().getClasses().size());
62 client.close();
63 }
64
65 /**
66 * @tpTestDetails Register provider instance twice to the client
67 * @tpPassCrit Warning will be raised that second provider instance registration is ignored
68 * @tpSince RESTEasy 3.0.17
69 */
70 @Test
71 @Category({NotForForwardCompatibility.class})
72 public void testDoubleRegistration() {
73 int countRESTEASY002160 = TestUtil.getWarningCount("RESTEASY002160", true);
74 int countRESTEASY002155 = TestUtil.getWarningCount("RESTEASY002155", true);
75 Client client = ClientBuilder.newClient();
76 int count = client.getConfiguration().getInstances().size();
77 Object reg = new FeatureReturningFalse();
78
79 client.register(reg).register(reg);
80 client.register(FeatureReturningFalse.class).register(FeatureReturningFalse.class);
81 Assert.assertEquals("Expect 1 warnining messages of Provider instance is already registered", 1, TestUtil.getWarningCount("RESTEASY002160", true) - countRESTEASY002160);
82 Assert.assertEquals("Expect 1 warnining messages of Provider class is already registered", 2, TestUtil.getWarningCount("RESTEASY002155", true) - countRESTEASY002155);
83 Assert.assertEquals(count + 1, client.getConfiguration().getInstances().size());
84
85 client.close();
86 }
87 }
+0
-89
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientDynamicFeaturesTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.spi.ResteasyProviderFactory;
5 import org.jboss.resteasy.test.client.resource.ClientDynamicFeaturesClientFeature1;
6 import org.jboss.resteasy.test.client.resource.ClientDynamicFeaturesClientFeature2;
7 import org.jboss.resteasy.test.client.resource.ClientDynamicFeaturesDualFeature1;
8 import org.jboss.resteasy.test.client.resource.ClientDynamicFeaturesDualFeature2;
9 import org.jboss.resteasy.test.client.resource.ClientDynamicFeaturesServerFeature1;
10 import org.jboss.resteasy.test.client.resource.ClientDynamicFeaturesServerFeature2;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Assert;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.container.DynamicFeature;
19 import java.util.Iterator;
20 import java.util.Set;
21
22 /**
23 * @tpSubChapter Resteasy-client
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Regression test for RESTEASY-1083
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 public class ClientDynamicFeaturesTest {
30 private static final String CLIENT_FEATURE_ERROR_MSG = "Wrong count of client features";
31 private static final String SERVER_FEATURE_ERROR_MSG = "Wrong count of server features";
32
33 /**
34 * Test needs to be run on deployment.
35 * @return
36 */
37 @Deployment
38 public static Archive<?> deploy() {
39 WebArchive war = TestUtil.prepareArchive(ClientDynamicFeaturesTest.class.getSimpleName());
40 war.addClasses(ClientDynamicFeaturesClientFeature1.class,
41 ClientDynamicFeaturesClientFeature2.class,
42 ClientDynamicFeaturesDualFeature2.class,
43 ClientDynamicFeaturesDualFeature1.class,
44 ClientDynamicFeaturesServerFeature2.class,
45 ClientDynamicFeaturesServerFeature1.class);
46 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
47 }
48
49 /**
50 * @tpTestDetails Check dynamic feature counts.
51 * @tpSince RESTEasy 3.0.16
52 */
53 @Test
54 public void testDynamicFeatures() throws Exception {
55 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
56 factory.registerProvider(ClientDynamicFeaturesClientFeature1.class, 0, false, null);
57 factory.registerProvider(ClientDynamicFeaturesServerFeature1.class, 0, false, null);
58 factory.registerProvider(ClientDynamicFeaturesDualFeature1.class, 0, false, null);
59 ClientDynamicFeaturesClientFeature2 clientFeature = new ClientDynamicFeaturesClientFeature2();
60 ClientDynamicFeaturesServerFeature2 serverFeature = new ClientDynamicFeaturesServerFeature2();
61 ClientDynamicFeaturesDualFeature2 feature = new ClientDynamicFeaturesDualFeature2();
62 factory.registerProviderInstance(clientFeature, null, 0, false);
63 factory.registerProviderInstance(serverFeature, null, 0, false);
64 factory.registerProviderInstance(feature, null, 0, false);
65 Set<DynamicFeature> clientFeatureSet = factory.getClientDynamicFeatures();
66 Set<DynamicFeature> serverFeatureSet = factory.getServerDynamicFeatures();
67
68 Assert.assertEquals(CLIENT_FEATURE_ERROR_MSG, 1, countFeatures(clientFeatureSet, "ClientDynamicFeaturesClientFeature1"));
69 Assert.assertEquals(CLIENT_FEATURE_ERROR_MSG, 1, countFeatures(clientFeatureSet, "ClientDynamicFeaturesClientFeature2"));
70 Assert.assertEquals(CLIENT_FEATURE_ERROR_MSG, 1, countFeatures(clientFeatureSet, "ClientDynamicFeaturesDualFeature1"));
71 Assert.assertEquals(CLIENT_FEATURE_ERROR_MSG, 1, countFeatures(clientFeatureSet, "ClientDynamicFeaturesDualFeature2"));
72 Assert.assertEquals(SERVER_FEATURE_ERROR_MSG, 1, countFeatures(serverFeatureSet, "ClientDynamicFeaturesServerFeature1"));
73 Assert.assertEquals(SERVER_FEATURE_ERROR_MSG, 1, countFeatures(serverFeatureSet, "ClientDynamicFeaturesServerFeature2"));
74 Assert.assertEquals(SERVER_FEATURE_ERROR_MSG, 1, countFeatures(serverFeatureSet, "ClientDynamicFeaturesDualFeature1"));
75 Assert.assertEquals(SERVER_FEATURE_ERROR_MSG, 1, countFeatures(serverFeatureSet, "ClientDynamicFeaturesDualFeature2"));
76 }
77
78 private int countFeatures(Set<DynamicFeature> featureSet, String feature) {
79 int count = 0;
80 for (Iterator<DynamicFeature> it = featureSet.iterator(); it.hasNext(); ) {
81 Class<?> clazz = it.next().getClass();
82 if (clazz.getName().contains(feature)) {
83 count++;
84 }
85 }
86 return count;
87 }
88 }
+0
-150
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientExceptionsTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.client.resource.ClientExceptionsCustomClientRequestFilter;
6 import org.jboss.resteasy.test.client.resource.ClientExceptionsData;
7 import org.jboss.resteasy.test.client.resource.ClientExceptionsIOExceptionReaderInterceptor;
8 import org.jboss.resteasy.test.client.resource.ClientExceptionsResource;
9 import org.jboss.resteasy.test.client.resource.ClientExceptionsCustomClientResponseFilter;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.After;
14 import org.junit.Before;
15 import org.junit.Rule;
16 import org.junit.Test;
17 import org.junit.rules.ExpectedException;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.ProcessingException;
21 import javax.ws.rs.client.Client;
22 import javax.ws.rs.client.ClientBuilder;
23 import javax.ws.rs.client.WebTarget;
24 import javax.ws.rs.client.ResponseProcessingException;
25 import javax.ws.rs.client.Entity;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @author <a href="mailto:kanovotn@redhat.com">Katerina Novotna</a>
30 * @tpSubChapter Resteasy-client
31 * @tpChapter Integration tests
32 * @tpTestCaseDetails Test if client throws exceptions as described in JAXRS-2.0 specification:
33 * "When a provider method throws an exception, the JAX-RS client runtime will map it to an instance of
34 * ProcessingException if thrown while processing a request, and to a ResponseProcessingException
35 * if thrown while processing a response."
36 * @tpSince RESTEasy 3.0.16
37 */
38 @RunWith(Arquillian.class)
39 @RunAsClient
40 public class ClientExceptionsTest extends ClientTestBase{
41
42 @Rule
43 public ExpectedException thrown = ExpectedException.none();
44
45 static Client client;
46
47 @Deployment
48 public static Archive<?> deploy() {
49 WebArchive war = TestUtil.prepareArchive(ClientExceptionsTest.class.getSimpleName());
50 war.addClass(ClientExceptionsData.class);
51 return TestUtil.finishContainerPrepare(war, null, ClientExceptionsResource.class);
52 }
53
54 @Before
55 public void before() {
56 client = ClientBuilder.newClient();
57 }
58
59 @After
60 public void close() {
61 client.close();
62 }
63
64 /**
65 * @tpTestDetails Send a request for entity which requires special MessageBodyReader which is not available.
66 * The exception is raised before sending request to the server
67 * @tpPassCrit ProcessingException is raised
68 * @tpSince RESTEasy 3.0.16
69 */
70 @Test
71 public void noMessageBodyReaderExistsTest() {
72 WebTarget base = client.target(generateURL("/") + "senddata");
73
74 thrown.expect(ProcessingException.class);
75 base.request().post(Entity.xml(new ClientExceptionsData("test", "test")));
76
77 }
78
79 /**
80 * @tpTestDetails Send a request and try to read Response for entity which requires special MessageBodyReader,
81 * which is not available. The response contains entity of type Data.
82 * The exception is raised when trying to read response from the server.
83 * @tpPassCrit ProcessingException is raised
84 * @tpSince RESTEasy 3.0.16
85 */
86 @Test
87 public void noMessageBodyReaderExistsReadEntityTest() throws Exception {
88 WebTarget base = client.target(generateURL("/") + "data");
89
90 Response response = base.request().accept("application/xml").get();
91 thrown.expect(ProcessingException.class);
92 response.readEntity(ClientExceptionsData.class);
93 }
94
95 /**
96 * @tpTestDetails Send a request and try to read Response for entity which requires special MessageBodyReader,
97 * which is not available. The response contains header with CONTENT_LENGTH zero and no Data entity.
98 * @tpPassCrit ProcessingException is raised
99 * @tpSince RESTEasy 3.0.16
100 */
101 @Test
102 public void responseWithContentLengthZero() {
103 WebTarget base = client.target(generateURL("/") + "empty");
104
105 Response response = base.request().accept("application/xml").get();
106 thrown.expect(ProcessingException.class);
107 response.readEntity(ClientExceptionsData.class);
108 }
109
110 /**
111 * @tpTestDetails WebTarget registers ReaderInterceptor and sends entity to a server. Then tries to read
112 * the response, but get interrupted by exception happening in ReaderInterceptor.
113 * @tpPassCrit ProcessingException is raised
114 * @tpSince RESTEasy 3.0.16
115 */
116 @Test
117 public void interceptorThrowsExceptionTest() {
118 WebTarget base = client.target(generateURL("/") + "post");
119 Response response = base.register(ClientExceptionsIOExceptionReaderInterceptor.class).request("text/plain").post(Entity.text("data"));
120
121 thrown.expect(ProcessingException.class);
122 response.readEntity(ClientExceptionsData.class);
123 }
124
125 /**
126 * @tpTestDetails WebTarget registers ClientResponseFilter and sends request to a server. The processing of the response gets
127 * interrupted in the ClientResponseFilter and processing ends with ResponseProcessingException.
128 * @tpPassCrit ResponseProcessingException is raised
129 * @tpSince RESTEasy 3.0.16
130 */
131 @Test(expected = ResponseProcessingException.class)
132 public void responseFilterThrowsExceptionTest() {
133 WebTarget base = client.target(generateURL("/") + "get");
134 base.register(ClientExceptionsCustomClientResponseFilter.class).request("text/plain").get();
135
136 }
137
138 /**
139 * @tpTestDetails WebTarget registers ClientRequestFilter and sends request to a server. The processing of the request gets
140 * interrupted in the ClientRequestFilter and processing ends with ProcessingException.
141 * @tpPassCrit ProcessingException is raised
142 * @tpSince RESTEasy 3.0.16
143 */
144 @Test(expected = ProcessingException.class)
145 public void requestFilterThrowsException() {
146 WebTarget base = client.target(generateURL("/") + "get");
147 base.register(ClientExceptionsCustomClientRequestFilter.class).request("text/plain").get();
148 }
149 }
+0
-147
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientExecutorShutdownTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.apache.http.HttpResponse;
3 import org.apache.http.client.HttpClient;
4 import org.apache.http.client.methods.HttpPost;
5 import org.apache.http.impl.client.HttpClientBuilder;
6 import org.jboss.arquillian.container.test.api.Deployment;
7 import org.jboss.arquillian.container.test.api.RunAsClient;
8 import org.jboss.arquillian.junit.Arquillian;
9 import org.jboss.logging.Logger;
10 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
11 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
12 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
13 import org.jboss.resteasy.test.client.resource.ClientExecutorShutdownTestResource;
14 import org.jboss.resteasy.util.HttpResponseCodes;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Assert;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.POST;
23 import javax.ws.rs.Path;
24 import javax.ws.rs.core.Response;
25
26 import static org.junit.Assert.fail;
27
28 /**
29 * @tpSubChapter Resteasy-client
30 * @tpChapter Client tests
31 * @tpSince RESTEasy 3.0.16
32 * @tpTestCaseDetails https://issues.jboss.org/browse/RESTEASY-621
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class ClientExecutorShutdownTest extends ClientTestBase{
37 private static Logger log = Logger.getLogger(ClientExecutorShutdownTest.class);
38
39 @Path("/test")
40 public interface TestService {
41 @POST
42 Response post();
43 }
44
45 @Deployment
46 public static Archive<?> deploy() {
47 WebArchive war = TestUtil.prepareArchive(ClientExecutorShutdownTest.class.getSimpleName());
48 war.addClass(ClientExecutorShutdownTest.class);
49 war.addClass(ClientTestBase.class);
50 return TestUtil.finishContainerPrepare(war, null, ClientExecutorShutdownTestResource.class);
51 }
52
53 /**
54 * @tpTestDetails Verify that if ApacheHttpClient4Executor creates its own HttpClient,
55 * then ApacheHttpClient4Executor.finalize() will close the HttpClient's
56 * org.apache.http.conn.ClientConnectionManager.
57 * @tpPassCrit ApacheHttpClient4Executor.finalize() will close the connection
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testApacheHttpClient4ExecutorNonSharedHttpClientFinalize() throws Throwable {
62 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine();
63 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
64 Response response = client.target(generateURL("/test")).request().post(null);
65 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
66 engine.finalize();
67 HttpClient httpClient = engine.getHttpClient();
68 HttpPost post = new HttpPost(generateURL("/test"));
69 try {
70 httpClient.execute(post);
71 fail("Expected IllegalStateException");
72 } catch (IllegalStateException e) {
73 log.info("Got expected IllegalStateException");
74 }
75 }
76
77 /**
78 * @tpTestDetails Verify that if ApacheHttpClient4Executor creates its own HttpClient,
79 * then ApacheHttpClient4Executor.close() will close the HttpClient's
80 * org.apache.http.conn.ClientConnectionManager.
81 * @tpPassCrit ApacheHttpClient4Executor.close() will close the connection
82 * @tpSince RESTEasy 3.0.16
83 */
84 @Test
85 public void testApacheHttpClient4ExecutorNonSharedHttpClientClose() throws Throwable {
86 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine();
87 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
88 Response response = client.target(generateURL("/test")).request().post(null);
89 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
90 engine.close();
91 HttpClient httpClient = engine.getHttpClient();
92 HttpPost post = new HttpPost(generateURL("/test"));
93 try {
94 httpClient.execute(post);
95 fail("Expected IllegalStateException");
96 } catch (IllegalStateException e) {
97 log.info("Got expected IllegalStateException");
98 }
99 }
100
101 /**
102 * @tpTestDetails Verify that if ApacheHttpClient4Executor receives an HttpClient through
103 * a constructor, then ApacheHttpClient4Executor.finalize() will not close the
104 * HttpClient's org.apache.http.conn.ClientConnectionManager.
105 * @tpPassCrit ApacheHttpClient4Executor.finalize() will not close the connection
106 * @tpSince RESTEasy 3.0.16
107 */
108 @Test
109 public void testApacheHttpClient4ExecutorSharedHttpClientFinalize() throws Throwable {
110 HttpClient httpClient = HttpClientBuilder.create().build();
111 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
112 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
113 Response response = client.target(generateURL("/test")).request().post(null);
114 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
115 engine.finalize();
116 Assert.assertEquals("Original httpclient and engine httpclient are not the same instance",
117 httpClient, engine.getHttpClient());
118 HttpPost post = new HttpPost(generateURL("/test"));
119 HttpResponse httpResponse = httpClient.execute(post);
120 Assert.assertEquals("The httpclient was closed and it shouldn't", HttpResponseCodes.SC_NO_CONTENT,
121 httpResponse.getStatusLine().getStatusCode());
122 }
123
124 /**
125 * @tpTestDetails Verify that if ApacheHttpClient4Executor receives an HttpClient through
126 * a constructor, then ApacheHttpClient4Executor.close() will not close the
127 * HttpClient's org.apache.http.conn.ClientConnectionManager.
128 * @tpPassCrit ApacheHttpClient4Executor.close() will not close the connection
129 * @tpSince RESTEasy 3.0.16
130 */
131 @Test
132 public void testApacheHttpClient4ExecutorSharedHttpClientClose() throws Throwable {
133 HttpClient httpClient = HttpClientBuilder.create().build();
134 ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
135 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
136 Response response = client.target(generateURL("/test")).request().post(null);
137 Assert.assertEquals("Original httpclient and engine httpclient are not the same instance",
138 HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
139 engine.close();
140 Assert.assertEquals(httpClient, engine.getHttpClient());
141 HttpPost post = new HttpPost(generateURL("/test"));
142 HttpResponse httpResponse = httpClient.execute(post);
143 Assert.assertEquals("The httpclient was closed and it shouldn't", HttpResponseCodes.SC_NO_CONTENT,
144 httpResponse.getStatusLine().getStatusCode());
145 }
146 }
+0
-105
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientFormParamTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.client.resource.ClientFormResource;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.After;
13 import org.junit.Assert;
14 import org.junit.Before;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.Consumes;
19 import javax.ws.rs.FormParam;
20 import javax.ws.rs.POST;
21 import javax.ws.rs.Path;
22 import javax.ws.rs.Produces;
23 import javax.ws.rs.client.Entity;
24 import javax.ws.rs.core.Form;
25 import javax.ws.rs.core.MediaType;
26
27 /**
28 * @tpSubChapter Resteasy-client
29 * @tpChapter Client tests
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class ClientFormParamTest extends ClientTestBase{
35
36 static ResteasyClient client;
37
38 @Path("/form")
39 public interface ClientFormResourceInterface {
40 @POST
41 String put(@FormParam("value") String value);
42
43 @POST
44 @Path("object")
45 @Produces(MediaType.APPLICATION_FORM_URLENCODED)
46 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
47 Form post(Form form);
48 }
49
50 @Deployment
51 public static Archive<?> deploy() {
52 WebArchive war = TestUtil.prepareArchive(ClientFormParamTest.class.getSimpleName());
53 war.addClass(ClientFormParamTest.class);
54 war.addClass(ClientTestBase.class);
55 return TestUtil.finishContainerPrepare(war, null, ClientFormResource.class);
56 }
57
58 @Before
59 public void init() {
60 client = new ResteasyClientBuilder().build();
61 }
62
63 @After
64 public void after() throws Exception {
65 client.close();
66 }
67
68 /**
69 * @tpTestDetails Client sends POST request with Form entity with one parameter.
70 * @tpPassCrit The resulting Form entity contains the original parameter
71 * @tpSince RESTEasy 3.0.16
72 */
73 @Test
74 public void testClientFormOneParameter() throws Exception {
75
76 final ClientFormResourceInterface proxy = ProxyBuilder.builder(ClientFormResourceInterface.class,
77 client.target(generateURL(""))).build();
78 String result = proxy.put("value");
79 Assert.assertEquals("The result doesn't match the expected one", result, "value");
80 result = client.target(generateURL("/form")).request().post(Entity.form(new Form().param("value", "value")),
81 String.class);
82 Assert.assertEquals("The result doesn't match the expected on, when using Form parameter", result, "value");
83 }
84
85 /**
86 * @tpTestDetails Client sends POST request with Form entity with two parameters.
87 * @tpPassCrit The resulting Form entity contains both original parameters
88 * @tpSince RESTEasy 3.0.16
89 */
90 @Test
91 public void testClientFormTwoParameters() throws Exception {
92 final ClientFormResourceInterface proxy = ProxyBuilder.builder(ClientFormResourceInterface.class,
93 client.target(generateURL(""))).build();
94 Form form = new Form().param("bill", "burke").param("foo", "bar");
95 Form resultForm = proxy.post(form);
96 Assert.assertEquals("The form map size on the response doesn't match the original", resultForm.asMap().size(),
97 form.asMap().size());
98 Assert.assertEquals("The resulting form doesn't contain the value for 'bill'",
99 resultForm.asMap().getFirst("bill"), "burke");
100 Assert.assertEquals("The resulting form doesn't contain the value for 'foo'", resultForm.asMap()
101 .getFirst("foo"), "bar");
102 }
103
104 }
+0
-130
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientInvocationBuilderTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import java.util.concurrent.ExecutionException;
3 import java.util.concurrent.Future;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.client.AsyncInvoker;
9 import javax.ws.rs.client.Entity;
10 import javax.ws.rs.client.Invocation.Builder;
11 import javax.ws.rs.core.MediaType;
12
13 import org.jboss.arquillian.container.test.api.Deployment;
14 import org.jboss.arquillian.container.test.api.RunAsClient;
15 import org.jboss.arquillian.junit.Arquillian;
16 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
17 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
18 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
19 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
20 import org.jboss.resteasy.utils.TestUtil;
21 import org.jboss.shrinkwrap.api.Archive;
22 import org.jboss.shrinkwrap.api.spec.WebArchive;
23 import org.junit.Assert;
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class ClientInvocationBuilderTest extends ClientTestBase{
30
31 @Path("/")
32 public static class ClientInvocationBuilderResource {
33 @POST
34 @Produces("text/plain")
35 public String post(String s) {
36 return s;
37 }
38
39 @GET
40 @Produces("text/plain")
41 public String get() {
42 String s = "default";
43 return s;
44 }
45 }
46
47 @Deployment
48 public static Archive<?> deploy() {
49 WebArchive war = TestUtil.prepareArchive(ClientInvocationBuilderTest.class.getSimpleName());
50 war.addClass(ClientInvocationBuilderTest.class);
51 war.addClass(ClientTestBase.class);
52 return TestUtil.finishContainerPrepare(war, null, ClientInvocationBuilderResource.class);
53 }
54
55 @Test
56 public void testBuildMethodReturnNewInstance() {
57 ResteasyClient client = new ResteasyClientBuilder().build();
58 try {
59 ResteasyWebTarget webTarget = client.target(generateURL(""));
60 Builder invocationBuilder = webTarget.request();
61
62 // GET invocation
63 ClientInvocation getInvocation = (ClientInvocation) invocationBuilder.accept(MediaType.TEXT_PLAIN_TYPE)
64 .build("GET");
65 Assert.assertEquals("default", getInvocation.invoke(String.class));
66
67 // Alter invocationBuilder
68 invocationBuilder.accept(MediaType.APPLICATION_XML_TYPE);
69 invocationBuilder.property("property1", "property1Value");
70 // Previously built getInvocation must not have been altered.(Those
71 // tests are not about immutability of
72 // getInvocation instance but about Builder pattern behavior).
73 Assert.assertFalse(getInvocation.getHeaders().getAcceptableMediaTypes()
74 .contains(MediaType.APPLICATION_XML_TYPE));
75 Assert.assertFalse(getInvocation.getConfiguration().getProperties().containsKey("property1"));
76
77 // POST invocation
78 ClientInvocation postInvocation = (ClientInvocation) invocationBuilder.accept(MediaType.TEXT_PLAIN_TYPE)
79 .build("POST", Entity.text("test"));
80 // Previous lines must build a new postInvocation instance and not
81 // modify previously built getInvocation instance.
82 // (It's all about Builder pattern behavior not immutability since
83 // Invocation is a mutable object.)
84 Assert.assertNotSame(getInvocation, postInvocation);
85 Assert.assertEquals("default", getInvocation.invoke(String.class));
86 Assert.assertTrue(postInvocation.getConfiguration().getProperties().containsKey("property1"));
87 Assert.assertEquals("test", postInvocation.invoke(String.class));
88 } finally {
89 client.close();
90 }
91 }
92
93 @Test
94 public void testBuildMethodResetEntity() throws InterruptedException, ExecutionException {
95 ResteasyClient client = new ResteasyClientBuilder().build();
96 try {
97 ResteasyWebTarget webTarget = client.target(generateURL(""));
98 Builder invocationBuilder = webTarget.request().accept(MediaType.TEXT_PLAIN_TYPE);
99
100 // POST invocation
101 ClientInvocation postInvocation = (ClientInvocation) invocationBuilder.build("POST", Entity.text("test"));
102 Assert.assertEquals("test", postInvocation.invoke(String.class));
103
104 // GET invocation
105 ClientInvocation getInvocation = (ClientInvocation) invocationBuilder.build("GET");
106 // In order the request to be OK, invocation instance built from
107 // invocationBuilder must not contain the previous entity used for
108 // post request.
109 Assert.assertNull(getInvocation.getEntity());
110 Assert.assertEquals("default", getInvocation.invoke(String.class));
111
112 // Same test for async request
113 AsyncInvoker async = invocationBuilder.async();
114
115 // POST invocation
116 Future<String> postFuture = async.post(Entity.text("test"), String.class);
117 Assert.assertEquals("test", postFuture.get());
118
119 // GET invocation
120 Future<String> getFuture = async.get(String.class);
121 Assert.assertEquals("default", getFuture.get());
122 } finally {
123 client.close();
124 }
125 }
126
127
128
129 }
+0
-129
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientProviderTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.client.resource.ClientProviderStringEntityProviderReader;
6 import org.jboss.resteasy.test.client.resource.ClientProviderStringEntityProviderWriter;
7 import org.jboss.resteasy.utils.TestUtil;
8 import org.jboss.shrinkwrap.api.Archive;
9 import org.jboss.shrinkwrap.api.spec.WebArchive;
10 import org.junit.After;
11 import org.junit.Assert;
12 import org.junit.Test;
13 import org.junit.Before;
14 import org.junit.runner.RunWith;
15
16 import javax.ws.rs.Path;
17 import javax.ws.rs.Consumes;
18 import javax.ws.rs.Produces;
19 import javax.ws.rs.POST;
20 import javax.ws.rs.GET;
21 import javax.ws.rs.client.Client;
22 import javax.ws.rs.client.ClientBuilder;
23 import javax.ws.rs.client.Entity;
24 import javax.ws.rs.client.WebTarget;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.BufferedReader;
29 import java.io.Reader;
30
31 /**
32 * @author <a href="mailto:kanovotn@redhat.com">Katerina Novotna</a>
33 * @tpSubChapter Resteasy-client
34 * @tpChapter Integration tests
35 * @tpTestCaseDetails Client registers it's own implementations as variants of built-in entity providers.
36 * The entity providers registered by client have to be used before built-in ones. See spec 4.2.4:
37 * "An implementation MUST support application-provided entity providers and MUST use those in preference to
38 * its own pre-packaged providers when either could handle the same request."
39 * @tpSince RESTEasy 3.0.16
40 */
41 @RunWith(Arquillian.class)
42 @RunAsClient
43 public class ClientProviderTest extends ClientTestBase{
44
45 static Client client;
46
47 @Before
48 public void before() {
49 client = ClientBuilder.newClient();
50 }
51
52 @Deployment
53 public static Archive<?> deploy() {
54 WebArchive war = TestUtil.prepareArchive(ClientProviderTest.class.getSimpleName());
55 war.addClass(ClientTestBase.class);
56 return TestUtil.finishContainerPrepare(war, null, ClientProviderResource.class);
57 }
58
59 @After
60 public void close() {
61 client.close();
62 }
63
64 @Path("/")
65 @Produces("text/plain")
66 @Consumes("text/plain")
67 public static class ClientProviderResource {
68 @POST
69 @Path("post")
70 public String post(String value) {
71 return value;
72 }
73
74 @GET
75 @Path("get")
76 public String nothing() {
77 return "OK";
78 }
79 }
80
81 public static final String readFromStream(InputStream stream) throws IOException {
82 InputStreamReader isr = new InputStreamReader(stream);
83 return readFromReader(isr);
84 }
85
86 public static final String readFromReader(Reader reader) throws IOException {
87 BufferedReader br = new BufferedReader(reader);
88 String entity = br.readLine();
89 br.close();
90 return entity;
91 }
92
93 /**
94 * @tpTestDetails Create WebTarget from client and register custom MessageBodyReader on it
95 * @tpPassCrit Verify application provided MessageBodyReader is used instead of built-in one,
96 * verify that following request is is processed by built-in MessageBodyReader again
97 * @tpSince RESTEasy 3.0.16
98 */
99 @Test
100 public void applicationDefinedMessageBodyReaderTest() {
101 WebTarget base = client.target(generateURL("/") + "get");
102 String result = base.register(ClientProviderStringEntityProviderReader.class).request().get(String.class);
103 Assert.assertEquals("Application defined provider reader: OK", result);
104
105 base = client.target(generateURL("/") + "get");
106 result = base.request().get(String.class);
107 Assert.assertEquals("OK", result);
108 }
109
110 /**
111 * @tpTestDetails Create WebTarget from client and register custom MessageBodyWriter on it
112 * @tpPassCrit Verify application provided MessageBodyWriter is used instead of built-in one,
113 * verify that following request is is processed by built-in MessageBodyWriter again
114 * @tpSince RESTEasy 3.0.16
115 */
116 @Test
117 public void applicationDefinedMessageBodyWriterTest() {
118 WebTarget base = client.target(generateURL("/") + "post");
119 String result = base.register(ClientProviderStringEntityProviderWriter.class).request().post(Entity.text("test"), String.class);
120 Assert.assertEquals("Application defined provider writer: text/plain[Content-Type=text/plain]", result);
121
122 base = client.target(generateURL("/") + "post");
123 result = base.request().post(Entity.text("test"), String.class);
124 Assert.assertEquals("test", result);
125 }
126
127
128 }
+0
-140
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientResponseRedirectTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
8 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
9 import org.jboss.resteasy.client.ProxyFactory;
10 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
11 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
12 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
13 import org.jboss.resteasy.test.client.resource.ClientResponseRedirectClientResponseOld;
14 import org.jboss.resteasy.test.client.resource.ClientResponseRedirectIntf;
15 import org.jboss.resteasy.test.client.resource.ClientResponseRedirectResource;
16 import org.jboss.resteasy.util.HttpResponseCodes;
17 import org.jboss.resteasy.utils.PortProviderUtil;
18 import org.jboss.resteasy.utils.TestUtil;
19 import org.jboss.shrinkwrap.api.Archive;
20 import org.jboss.shrinkwrap.api.spec.WebArchive;
21 import org.junit.After;
22 import org.junit.Assert;
23 import org.junit.Before;
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26
27 import javax.ws.rs.core.MultivaluedMap;
28 import javax.ws.rs.core.Response;
29 import java.net.HttpURLConnection;
30 import java.net.URL;
31
32 /**
33 * @tpSubChapter Resteasy-client
34 * @tpChapter Integration tests
35 * @tpSince RESTEasy 3.0.16
36 */
37 @RunWith(Arquillian.class)
38 @RunAsClient
39 public class ClientResponseRedirectTest extends ClientTestBase{
40
41
42 protected static final Logger logger = LogManager.getLogger(ClientResponseRedirectTest.class.getName());
43 static ResteasyClient client;
44
45 @Deployment
46 public static Archive<?> deploy() {
47 WebArchive war = TestUtil.prepareArchive(ClientResponseRedirectTest.class.getSimpleName());
48 war.addClass(ClientTestBase.class);
49 return TestUtil.finishContainerPrepare(war, null, ClientResponseRedirectResource.class, PortProviderUtil.class);
50 }
51
52 @Before
53 public void init() {
54 client = new ResteasyClientBuilder().build();
55 }
56
57 @After
58 public void after() throws Exception {
59 client.close();
60 }
61
62 /**
63 * @tpTestDetails Tests redirection of the request using deprecated ProxyFactory client
64 * @tpPassCrit The header 'location' contains the redirected target
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testRedirectProxyFactory() throws Exception {
69 testRedirect(ProxyFactory.create(ClientResponseRedirectClientResponseOld.class, PortProviderUtil.generateBaseUrl(ClientResponseRedirectTest.class.getSimpleName())).get());
70 }
71
72 /**
73 * @tpTestDetails Tests redirection of the request using ProxyBuilder client
74 * @tpPassCrit The header 'location' contains the redirected target
75 * @tpSince RESTEasy 3.0.16
76 */
77 @Test
78 public void testRedirectProxyBuilder() throws Exception {
79 testRedirect(ProxyBuilder.builder(ClientResponseRedirectIntf.class, client.target(generateURL(""))).build().get());
80 }
81
82 /**
83 * @tpTestDetails Tests redirection of the request using deprecated ClientRequest
84 * @tpPassCrit The header 'location' contains the redirected target
85 * @tpSince RESTEasy 3.0.16
86 */
87 @Test
88 public void testRedirectClientRequest() throws Exception {
89 testRedirect(new ClientRequest(generateURL("/redirect")).get());
90 }
91
92 /**
93 * @tpTestDetails Tests redirection of the request using Client Webtarget request
94 * @tpPassCrit The header 'location' contains the redirected target
95 * @tpSince RESTEasy 3.0.16
96 */
97 @Test
98 public void testRedirectClientTargetRequest() throws Exception {
99 testRedirect(client.target(generateURL("/redirect")).request().get());
100 }
101
102 /**
103 * @tpTestDetails Tests redirection of the request using HttpUrlConnection
104 * @tpPassCrit The header 'location' contains the redirected target
105 * @tpSince RESTEasy 3.0.16
106 */
107 @Test
108 public void testRedirectHttpUrlConnection() throws Exception {
109 URL url = PortProviderUtil.createURL("/redirect", ClientResponseRedirectTest.class.getSimpleName());
110 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
111 conn.setInstanceFollowRedirects(false);
112 conn.setRequestMethod("GET");
113 for (Object name : conn.getHeaderFields().keySet()) {
114 logger.info(name);
115 }
116 logger.info("The response from the server was: " + conn.getResponseCode());
117 Assert.assertEquals(HttpResponseCodes.SC_SEE_OTHER, conn.getResponseCode());
118 }
119
120 private void testRedirect(ClientResponse response) {
121 MultivaluedMap headers = response.getResponseHeaders();
122 logger.info("size: " + headers.size());
123 for (Object name : headers.keySet()) {
124 logger.info(name + ":" + headers.getFirst(name.toString()));
125 }
126 Assert.assertEquals("The location header doesn't have the expected value", generateURL("/redirect/data"), headers.getFirst("location"));
127 }
128
129 @SuppressWarnings(value = "unchecked")
130 private void testRedirect(Response response) {
131 MultivaluedMap headers = response.getHeaders();
132 logger.info("size: " + headers.size());
133 for (Object name : headers.keySet()) {
134 logger.info(name + ":" + headers.getFirst(name.toString()));
135 }
136 Assert.assertEquals("The location header doesn't have the expected value", generateURL("/redirect/data"), headers.getFirst("location"));
137 }
138
139 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientTestBase.java less more
0 /*
1 * JBoss, Home of Professional Open Source
2 * Copyright 2016, Red Hat, Inc., and individual contributors as indicated
3 * by the @authors tag.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.jboss.resteasy.test.client;
19
20 import java.net.URI;
21
22 import org.jboss.arquillian.test.api.ArquillianResource;
23
24 /**
25 * @author Tomaz Cerar (c) 2016 Red Hat Inc.
26 */
27 abstract class ClientTestBase {
28
29 @ArquillianResource
30 URI baseUri;
31
32 protected String generateURL(String path) {
33 if (path.startsWith("/")){
34 path = path.substring(1);
35 }
36 return baseUri.resolve(path).toString();
37 }
38 }
+0
-212
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/EntityBufferingInFileTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.apache.commons.io.IOUtils;
3 import org.apache.http.HttpEntity;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.dmr.ModelNode;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
11 import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
12 import org.jboss.resteasy.test.client.resource.EntityBufferingInFileResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.Assert;
18 import org.junit.Test;
19 import org.junit.BeforeClass;
20 import org.junit.AfterClass;
21 import org.junit.Ignore;
22
23
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.core.Response;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.StringWriter;
29
30 import org.jboss.logging.Logger;
31 import org.junit.runner.RunWith;
32 import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
33 import org.wildfly.extras.creaper.core.online.operations.Address;
34 import org.wildfly.extras.creaper.core.online.operations.Operations;
35 import org.wildfly.extras.creaper.core.online.operations.admin.Administration;
36
37 /**
38 * @tpSubChapter Resteasy-client
39 * @tpChapter Integration tests
40 * @tpSince RESTEasy 3.0.16
41 */
42 @RunWith(Arquillian.class)
43 @RunAsClient
44 public class EntityBufferingInFileTest extends ClientTestBase{
45
46 private static final Logger logger = Logger.getLogger(EntityBufferingInFileTest.class);
47 private static final long MAX_POST_SIZE = 2147483647;
48 private static ModelNode origMaxPostSizeValue;
49 private static Address address = Address.subsystem("undertow").and("server", "default-server").and("http-listener", "default");
50
51 @BeforeClass
52 public static void setMaxPostSize() throws Exception {
53 OnlineManagementClient client = TestUtil.clientInit();
54 Administration admin = new Administration(client);
55 Operations ops = new Operations(client);
56
57 // get original 'max-post-size' value
58 origMaxPostSizeValue = ops.readAttribute(address, "max-post-size").value();
59 // set 'max-post-size' - max size of the object send in the post request
60 ops.writeAttribute(address, "max-post-size", MAX_POST_SIZE);
61 // reload server
62 admin.reload();
63 client.close();
64 }
65
66 @AfterClass
67 public static void resetToDefault() throws Exception {
68 OnlineManagementClient client = TestUtil.clientInit();
69 Administration admin = new Administration(client);
70 Operations ops = new Operations(client);
71
72 // write original 'disallowed methods' value
73 ops.writeAttribute(address, "max-post-size", origMaxPostSizeValue);
74 // reload server
75 admin.reload();
76 client.close();
77 }
78
79 @Deployment
80 public static Archive<?> deploy() {
81 WebArchive war = TestUtil.prepareArchive(EntityBufferingInFileTest.class.getSimpleName());
82 war.addClass(EntityBufferingInFileTest.class);
83 return TestUtil.finishContainerPrepare(war, null, EntityBufferingInFileResource.class);
84 }
85
86 /**
87 * @tpTestDetails Custom ApacheHttpClient4Engine is created which defines maximum file size allowed in memory - 16 bytes
88 * (defined by memoryUnit and threshold size in doTest() method). Client then sends POST request with String entity
89 * of defined size (10 bytes),
90 * @tpPassCrit Successful response is returned, the entity stream returned is same as original string
91 * Response entity is type of ByteArrayEntity.
92 * @tpSince RESTEasy 3.0.16
93 */
94 @Test
95 public void testBytes1() throws Exception {
96 doTest(ApacheHttpClient4Engine.MemoryUnit.BY, 16, 10, true);
97 }
98
99 /**
100 * @tpTestDetails Custom ApacheHttpClient4Engine is created which defines maximum file size allowed in memory - 16 bytes
101 * (defined by memoryUnit and threshold size in doTest() method). Client then sends POST request with String entity
102 * of defined size (20 bytes)
103 * @tpPassCrit Successful response is returned, the entity stream returned is same as original string
104 * @tpSince RESTEasy 3.0.16
105 */
106 @Test
107 public void testBytes2() throws Exception {
108 doTest(ApacheHttpClient4Engine.MemoryUnit.BY, 16, 20, false);
109 }
110
111 /**
112 * @tpTestDetails Custom ApacheHttpClient4Engine is created which defines maximum file size allowed in memory - 1 KB
113 * (defined by memoryUnit and threshold size in doTest() method). Client then sends POST request with String entity
114 * of defined size (500 bytes)
115 * @tpPassCrit Successful response is returned, the entity stream returned is same as original string
116 * @tpSince RESTEasy 3.0.16
117 */
118 @Test
119 public void testKilobytes1() throws Exception {
120 doTest(ApacheHttpClient4Engine.MemoryUnit.KB, 1, 500, true);
121 }
122
123 /**
124 * @tpTestDetails Custom ApacheHttpClient4Engine is created which defines maximum file size allowed in memory - 1 KB
125 * (defined by memoryUnit and threshold size in doTest() method). Client then sends POST request with String entity
126 * of defined size (2000 bytes)
127 * @tpPassCrit Successful response is returned, the entity stream returned is same as original string
128 * @tpSince RESTEasy 3.0.16
129 */
130 @Test
131 public void testKilobytes2() throws Exception {
132 doTest(ApacheHttpClient4Engine.MemoryUnit.KB, 1, 2000, false);
133 }
134
135 /**
136 * @tpTestDetails Custom ApacheHttpClient4Engine is created which defines maximum file size allowed in memory - 1 MB
137 * (defined by memoryUnit and threshold size in doTest() method). Client then sends POST request with String entity
138 * of defined size (500000 bytes)
139 * @tpPassCrit Successful response is returned, the entity stream returned is same as original string
140 * @tpSince RESTEasy 3.0.16
141 */
142 @Test
143 public void testMegabytes1() throws Exception {
144 doTest(ApacheHttpClient4Engine.MemoryUnit.MB, 1, 500000, true);
145 }
146
147 /**
148 * @tpTestDetails Custom ApacheHttpClient4Engine is created which defines maximum file size allowed in memory - 1 GB
149 * (defined by memoryUnit and threshold size in doTest() method). Client then sends POST request with String entity
150 * of defined size (2000000000 bytes)
151 * @tpPassCrit Successful response is returned, the entity stream returned is same as original string
152 * @tpSince RESTEasy 3.0.16
153 */
154 @Test
155 public void testMegabytes2() throws Exception {
156 doTest(ApacheHttpClient4Engine.MemoryUnit.MB, 1, 2000000, false);
157 }
158
159 /**
160 * @tpTestDetails Custom ApacheHttpClient4Engine is created which defines maximum file size allowed in memory - 1 GB
161 * (defined by memoryUnit and threshold size in doTest() method). Client then sends POST request with String entity
162 * of defined size (500000000 bytes)
163 * @tpPassCrit Successful response is returned, the entity stream returned is same as original string
164 * @tpSince RESTEasy 3.0.16
165 */
166 @Ignore("The tests fails on some machines on client side. As this is performance test and performance tests were dropped" +
167 "from EAP7 rfe list, this is not priority now.")
168 @Test
169 public void testGigabytes1() throws Exception {
170 doTest(ApacheHttpClient4Engine.MemoryUnit.GB, 1, 500000000, true);
171 }
172
173 protected void doTest(ApacheHttpClient4Engine.MemoryUnit memoryUnit, int threshold, int length, boolean inMemory) throws Exception {
174 try {
175 TestClientExecutor executor = new TestClientExecutor();
176 executor.setFileUploadMemoryUnit(memoryUnit);
177 executor.setFileUploadInMemoryThresholdLimit(threshold);
178 StringBuffer sb = new StringBuffer();
179 for (int i = 0; i < length; i++) {
180 sb.append("0");
181 }
182 String body = sb.toString();
183
184 ResteasyClient client = new ResteasyClientBuilder().httpEngine(executor).build();
185 Response response = client.target(generateURL("/hello")).request().header("content-type", "text/plain; charset=UTF-8").post(Entity.text(body));
186 logger.info("Received response");
187 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
188 InputStream in = response.readEntity(InputStream.class);
189 StringWriter writer = new StringWriter();
190 IOUtils.copy(in, writer, "UTF-8");
191 String responseString = writer.toString();
192 Assert.assertEquals(body, responseString);
193 response.close();
194 } catch (OutOfMemoryError e) {
195 logger.info("OutOfMemoryError on " + memoryUnit + " test.");
196 }
197 }
198
199 static class TestClientExecutor extends ApacheHttpClient4Engine {
200 private HttpEntity entityToBuild;
201
202 protected HttpEntity buildEntity(final ClientInvocation request) throws IOException {
203 entityToBuild = super.buildEntity(request);
204 return entityToBuild;
205 }
206
207 public HttpEntity getBuildEntity() {
208 return entityToBuild;
209 }
210 }
211 }
+0
-50
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/GenericReturnTypeTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.client.resource.GenericReturnTypeInterface;
9 import org.jboss.resteasy.test.client.resource.GenericReturnTypeReader;
10 import org.jboss.resteasy.test.client.resource.GenericReturnTypeResource;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Assert;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.client.Client;
19
20 /**
21 * @tpSubChapter Resteasy-client
22 * @tpChapter Client tests
23 * @tpSince RESTEasy 3.0.17
24 * @tpTestCaseDetails Regression for JBEAP-4699
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class GenericReturnTypeTest extends ClientTestBase{
29
30 @Deployment
31 public static Archive<?> deploy() {
32 WebArchive war = TestUtil.prepareArchive(GenericReturnTypeTest.class.getSimpleName());
33 war.addClasses(GenericReturnTypeInterface.class);
34 return TestUtil.finishContainerPrepare(war, null, GenericReturnTypeResource.class, GenericReturnTypeReader.class);
35 }
36
37 /**
38 * @tpTestDetails Test generic type of proxy
39 * @tpSince RESTEasy 3.0.17
40 */
41 @Test
42 public void testGenericReturnType() {
43 Client client = ResteasyClientBuilder.newClient();
44 ResteasyWebTarget target = (ResteasyWebTarget) client.target(generateURL("")).register(GenericReturnTypeReader.class);
45 GenericReturnTypeInterface<?> server = ProxyBuilder.builder(GenericReturnTypeInterface.class, target).build();
46 Object result = server.t();
47 Assert.assertEquals("abc", result);
48 }
49 }
+0
-105
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/IndirectInvocationTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.client.resource.IndirectInvocationTestResource;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.PortProviderUtil;
8 import org.jboss.resteasy.utils.TestUtil;
9 import org.jboss.shrinkwrap.api.Archive;
10 import org.jboss.shrinkwrap.api.spec.WebArchive;
11 import org.junit.AfterClass;
12 import org.junit.Assert;
13 import org.junit.Before;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.client.Entity;
20 import javax.ws.rs.client.Invocation;
21 import javax.ws.rs.core.Response;
22
23 import java.util.Arrays;
24 import java.util.Collection;
25
26 /**
27 * @author <a href="mailto:kanovotn@redhat.com">Katerina Novotna</a>
28 * @tpSubChapter Resteasy-client
29 * @tpChapter Integration tests
30 * @tpSince RESTEasy 3.0.16
31 *
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class IndirectInvocationTest extends ClientTestBase{
36
37 public static final int REPEAT = 15;
38
39 static Client client;
40
41 @Before
42 public void before() {
43 client = ClientBuilder.newClient();
44 }
45
46 @Deployment
47 public static Archive<?> deploy() {
48 WebArchive war = TestUtil.prepareArchive(IndirectInvocationTest.class.getSimpleName());
49 return TestUtil.finishContainerPrepare(war, null, IndirectInvocationTestResource.class);
50 }
51
52 @AfterClass
53 public static void close() {
54 client.close();
55 }
56
57 /**
58 * @tpTestDetails Create Invocation request and submit it using invoke() method, verify the answer
59 * @tpPassCrit Expected response is returned from the server
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void invokeLaterTest() {
64 Invocation inv = client.target(generateURL("/") + "test/query")
65 .queryParam("param", "123456")
66 .queryParam("id", "3")
67 .request("text/plain").buildGet();
68
69 Response response = inv.invoke();
70 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
71 Assert.assertEquals("123456 3", response.readEntity(String.class));
72 }
73
74 /**
75 * @tpTestDetails Create two Invocations requests, store them in the list and then call them multiple times
76 * @tpPassCrit Expected response is returned from the server
77 * @tpInfo https://weblogs.java.net/blog/spericas/archive/2011/10/20/jax-rs-20-client-api-generic-interface
78 * @tpSince RESTEasy 3.0.16
79 */
80 @Test
81 public void invokeMultipleTimes() {
82 Invocation inv1 = client.target(generateURL("/") + "test/query")
83 .queryParam("param", "123456")
84 .queryParam("id", "3")
85 .request("text/plain").buildGet();
86
87 Invocation inv2 = client.target(generateURL("/") + "test/send")
88 .queryParam("param", "123456")
89 .queryParam("id", "3")
90 .request("text/plain").buildPost(Entity.text("50.0"));
91
92
93 Collection<Invocation> invs = Arrays.asList(inv1, inv2);
94
95 for (int i = 0; i < REPEAT; i++) {
96 for (Invocation inv : invs) {
97 Response response = inv.invoke();
98 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
99 response.close();
100 }
101 }
102 }
103
104 }
+0
-70
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/InputStreamResourceTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import java.io.ByteArrayInputStream;
3 import java.io.InputStream;
4
5 import javax.ws.rs.client.Client;
6 import javax.ws.rs.client.ClientBuilder;
7 import javax.ws.rs.core.Response;
8
9 import org.jboss.arquillian.container.test.api.Deployment;
10 import org.jboss.arquillian.container.test.api.RunAsClient;
11 import org.jboss.arquillian.junit.Arquillian;
12 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
13 import org.jboss.resteasy.test.client.resource.InputStreamResourceClient;
14 import org.jboss.resteasy.test.client.resource.InputStreamResourceService;
15 import org.jboss.resteasy.util.ReadFromStream;
16 import org.jboss.resteasy.utils.TestUtil;
17 import org.jboss.shrinkwrap.api.Archive;
18 import org.jboss.shrinkwrap.api.spec.WebArchive;
19 import org.junit.AfterClass;
20 import org.junit.Assert;
21 import org.junit.BeforeClass;
22 import org.junit.Test;
23 import org.junit.runner.RunWith;
24
25 /**
26 * @tpSubChapter Resource
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Read and write InputStreams
29 * @tpSince RESTEasy 3.0.20
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class InputStreamResourceTest extends ClientTestBase{
34
35 static Client resteasyClient;
36
37 @BeforeClass
38 public static void setup() {
39 resteasyClient = ClientBuilder.newClient();
40 }
41
42 @AfterClass
43 public static void close() {
44 resteasyClient.close();
45 }
46
47 @Deployment
48 public static Archive<?> deploy() {
49 WebArchive war = TestUtil.prepareArchive(InputStreamResourceTest.class.getSimpleName());
50 return TestUtil.finishContainerPrepare(war, null, InputStreamResourceService.class);
51 }
52
53 /**
54 * @tpTestDetails Read Strings as either Strings or InputStreams
55 * @tpSince RESTEasy 3.0.20
56 */
57 @Test
58 public void testClientResponse() throws Exception {
59 InputStreamResourceClient client = ProxyBuilder.builder(InputStreamResourceClient.class, resteasyClient.target(generateURL(""))).build();
60 Assert.assertEquals("hello", client.getAsString());
61 Response is = client.getAsInputStream();
62 Assert.assertEquals("hello", new String(ReadFromStream.readFromStream(1024, is.readEntity(InputStream.class))));
63 is.close();
64 client.postString("new value");
65 Assert.assertEquals("new value", client.getAsString());
66 client.postInputStream(new ByteArrayInputStream("new value 2".getBytes()));
67 Assert.assertEquals("new value 2", client.getAsString());
68 }
69 }
+0
-101
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/InputStreamTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.client.resource.InputStreamResource;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Test;
14 import org.junit.Before;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.GET;
20 import javax.ws.rs.Path;
21 import javax.ws.rs.Produces;
22 import java.io.InputStream;
23
24
25 /**
26 * @tpSubChapter Resteasy-client
27 * @tpChapter Client tests
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class InputStreamTest extends ClientTestBase{
33
34 @Path("/")
35 public interface InputStreamInterface {
36 @Path("test")
37 @Produces("text/plain")
38 @GET
39 default InputStream get() {
40 return null;
41 }
42
43 }
44
45 protected static final Logger logger = LogManager.getLogger(InputStreamTest.class.getName());
46
47 static ResteasyClient client;
48
49 @Deployment
50 public static Archive<?> deploy() {
51 WebArchive war = TestUtil.prepareArchive(InputStreamTest.class.getSimpleName());
52 war.addClass(InputStreamTest.class);
53 return TestUtil.finishContainerPrepare(war, null, InputStreamResource.class);
54 }
55
56 @Before
57 public void init() {
58 client = new ResteasyClientBuilder().build();
59 }
60
61 @After
62 public void after() throws Exception {
63 client.close();
64 }
65
66
67 /**
68 * @tpTestDetails Client sends GET request with requested return type of InputStream.
69 * @tpPassCrit The response String can be read from returned input stream and matches expected text.
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test
73 public void testInputStream() throws Exception {
74 InputStream is = client.target(generateURL("/test")).request().get(InputStream.class);
75 byte[] buf = new byte[1024];
76 int read = is.read(buf);
77 String str = new String(buf, 0, read);
78 Assert.assertEquals("The returned inputStream doesn't contain expexted text", "hello world", str);
79 logger.info("Text from inputstream: " + str);
80 is.close();
81 }
82
83 /**
84 * @tpTestDetails Client sends GET request with requested return type of InputStream. The request is created
85 * via client proxy
86 * @tpPassCrit The response with expected Exception text is returned
87 * @tpSince RESTEasy 3.0.16
88 */
89 @Test
90 public void testInputStreamProxy() throws Exception {
91 InputStreamInterface proxy = client.target(generateURL("/")).proxy(InputStreamInterface.class);
92 byte[] buf = new byte[1024];
93 InputStream is = proxy.get();
94 int read = is.read(buf);
95 String str = new String(buf, 0, read);
96 Assert.assertEquals("The returned inputStream doesn't contain expexted text", "hello world", str);
97 is.close();
98 }
99
100 }
+0
-111
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/LinkHeaderTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.client.LinkHeaderDelegate;
10 import org.jboss.resteasy.client.LinkHeader;
11 import org.jboss.resteasy.test.client.resource.LinkHeaderService;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.asset.StringAsset;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Resteasy-client
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails LinkHeader (it use deprecated Link). Test also new Link provided by jax-rs 2.0 spec
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class LinkHeaderTest extends ClientTestBase{
34
35 protected static ResteasyClient client;
36
37 @Before
38 public void setup() throws Exception {
39 client = new ResteasyClientBuilder().build();
40 }
41
42 @Deployment
43 public static Archive<?> createTestArchive() {
44 WebArchive war = TestUtil.prepareArchive(LinkHeaderTest.class.getSimpleName());
45 return TestUtil.finishContainerPrepare(war, null, LinkHeaderService.class);
46 }
47
48 @After
49 public void shutdown() throws Exception {
50 client.close();
51 }
52
53 /**
54 * @tpTestDetails Test new client without API and old client with API
55 * @tpSince RESTEasy 3.0.16
56 */
57 @Test
58 public void testLinkheader() throws Exception {
59 // old client testing
60 {
61 ClientRequest request = new ClientRequest(generateURL("/linkheader/str"));
62 request.addLink("previous chapter", "previous", "http://example.com/TheBook/chapter2", null);
63 ClientResponse response = request.post();
64 LinkHeader header = response.getLinkHeader();
65 Assert.assertNotNull(header);
66 Assert.assertTrue("Wrong link", header.getLinksByTitle().containsKey("previous chapter"));
67 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("previous"));
68 Assert.assertEquals("Wrong link", header.getLinksByTitle().get("previous chapter").getHref(), "http://example.com/TheBook/chapter2");
69 }
70
71 // new client testing
72 {
73 Response response = client.target(generateURL("/linkheader/str")).request().header("Link",
74 "<http://example.com/TheBook/chapter2>; rel=\"previous\"; title=\"previous chapter\"").post(Entity.text(new String()));
75 javax.ws.rs.core.Link link = response.getLink("previous");
76 Assert.assertNotNull(link);
77 Assert.assertEquals("Wrong link", "previous chapter", link.getTitle());
78 Assert.assertEquals("Wrong link", "http://example.com/TheBook/chapter2", link.getUri().toString());
79 }
80 }
81
82 /**
83 * @tpTestDetails Test old client without API
84 * @tpSince RESTEasy 3.0.16
85 */
86 @Test
87 public void testLinkheaderOldClientWithoutApi() throws Exception {
88 LinkHeaderDelegate delegate = new LinkHeaderDelegate();
89 LinkHeader header = delegate.fromString("<http://example.org/>; rel=index;\n" +
90 " rel=\"start http://example.net/relation/other\"");
91 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("index"));
92 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("start"));
93 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("http://example.net/relation/other"));
94 String str = delegate.toString(header);
95 header = delegate.fromString(str);
96 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("index"));
97 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("start"));
98 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("http://example.net/relation/other"));
99 ClientRequest request = new ClientRequest(generateURL("/linkheader"));
100 request.header("link", "<http://example.org/>; rel=index;" +
101 " rel=\"start http://example.net/relation/other\"");
102 ClientResponse response = request.post();
103 header = response.getLinkHeader();
104 Assert.assertNotNull("Wrong link", header);
105 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("index"));
106 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("start"));
107 Assert.assertTrue("Wrong link", header.getLinksByRelationship().containsKey("http://example.net/relation/other"));
108 }
109
110 }
+0
-114
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/NullEntityTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.client.resource.NullEntityResource;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.Assert;
13 import org.junit.Test;
14 import org.junit.runner.RunWith;
15
16 import javax.ws.rs.client.Entity;
17 import javax.ws.rs.core.Form;
18 import javax.ws.rs.core.MediaType;
19
20 /**
21 * @tpSubChapter Resteasy-client
22 * @tpChapter Client tests
23 * @tpSince RESTEasy 3.0.16
24 * @tpTestCaseDetails Regression for RESTEASY-1057
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class NullEntityTest extends ClientTestBase{
29
30 @Deployment
31 public static Archive<?> deploy() {
32 WebArchive war = TestUtil.prepareArchive(NullEntityTest.class.getSimpleName());
33 return TestUtil.finishContainerPrepare(war, null, NullEntityResource.class);
34 }
35
36 /**
37 * @tpTestDetails Test to send null by post request.
38 * @tpSince RESTEasy 3.0.16
39 */
40 @Test
41 public void testPostNull() {
42 ResteasyClient client = new ResteasyClientBuilder().build();
43 ResteasyWebTarget target = client.target(generateURL("/null"));
44 String response = target.request().post(null, String.class);
45 Assert.assertEquals("Wrong response", "", response);
46 client.close();
47 }
48
49 /**
50 * @tpTestDetails Test to send null via entity by post request.
51 * @tpSince RESTEasy 3.0.16
52 */
53 @Test
54 public void testEntity() {
55 ResteasyClient client = new ResteasyClientBuilder().build();
56 ResteasyWebTarget target = client.target(generateURL("/entity"));
57 String response = target.request().post(Entity.entity(null, MediaType.WILDCARD), String.class);
58 Assert.assertEquals("Wrong response", "", response);
59 client.close();
60 }
61
62 /**
63 * @tpTestDetails Test to send null via form
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testForm() {
68 ResteasyClient client = new ResteasyClientBuilder().build();
69 ResteasyWebTarget target = client.target(generateURL("/form"));
70 String response = target.request().post(Entity.form((Form) null), String.class);
71 Assert.assertEquals("Wrong response", null, response);
72 client.close();
73 }
74
75 /**
76 * @tpTestDetails Test resource with "text/html" media type
77 * @tpSince RESTEasy 3.0.16
78 */
79 @Test
80 public void testHtml() {
81 ResteasyClient client = new ResteasyClientBuilder().build();
82 ResteasyWebTarget target = client.target(generateURL("/html"));
83 String response = target.request().post(Entity.html(null), String.class);
84 Assert.assertEquals("Wrong response", "", response);
85 client.close();
86 }
87
88 /**
89 * @tpTestDetails Test resource with "application/xhtml+xml" media type
90 * @tpSince RESTEasy 3.0.16
91 */
92 @Test
93 public void testXhtml() {
94 ResteasyClient client = new ResteasyClientBuilder().build();
95 ResteasyWebTarget target = client.target(generateURL("/xhtml"));
96 String response = target.request().post(Entity.xhtml(null), String.class);
97 Assert.assertEquals("Wrong response", "", response);
98 client.close();
99 }
100
101 /**
102 * @tpTestDetails Test resource with "application/xml" media type
103 * @tpSince RESTEasy 3.0.16
104 */
105 @Test
106 public void testXml() {
107 ResteasyClient client = new ResteasyClientBuilder().build();
108 ResteasyWebTarget target = client.target(generateURL("/xml"));
109 String response = target.request().post(Entity.xml(null), String.class);
110 Assert.assertEquals("Wrong response", "", response);
111 client.close();
112 }
113 }
+0
-432
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/ParameterListTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
8 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
9 import org.jboss.resteasy.client.ProxyFactory;
10 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
11 import org.jboss.resteasy.test.client.resource.ParameterListInterface;
12 import org.jboss.resteasy.test.client.resource.ParameterListResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Client;
25 import javax.ws.rs.client.ClientBuilder;
26 import javax.ws.rs.core.Response;
27 import java.util.ArrayList;
28 import java.util.HashSet;
29 import java.util.TreeSet;
30
31 /**
32 * @tpSubChapter Resteasy-client
33 * @tpChapter Client tests
34 * @tpSince RESTEasy 3.0.16
35 * @tpTestCaseDetails Regression for RESTEASY-756
36 */
37 @RunWith(Arquillian.class)
38 @RunAsClient
39 public class ParameterListTest extends ClientTestBase{
40
41 protected static final Logger logger = LogManager.getLogger(ParameterListTest.class.getName());
42
43 private static final String ERROR_MESSAGE = "Wrong parameters in response received";
44 private static Client restClient;
45
46 @Before
47 public void init() {
48 restClient = ClientBuilder.newClient();
49 }
50
51 @After
52 public void after() throws Exception {
53 restClient.close();
54 }
55
56 @Deployment
57 public static Archive<?> deploy() {
58 WebArchive war = TestUtil.prepareArchive(ParameterListTest.class.getSimpleName());
59 war.addClass(ParameterListInterface.class);
60 return TestUtil.finishContainerPrepare(war, null, ParameterListResource.class);
61 }
62
63 private String generateBaseUrl() {
64 return PortProviderUtil.generateBaseUrl(ParameterListTest.class.getSimpleName());
65 }
66
67 /**
68 * @tpTestDetails Old client: set matrix param by URL and by matrixParameter function
69 * @tpSince RESTEasy 3.0.16
70 */
71 @Test
72 public void testMatrixOldClient() throws Exception {
73 ClientRequest request = new ClientRequest(generateURL("/matrix;m1=a/list;m1=b;p2=c"));
74 request.matrixParameter("m1", "d");
75 ClientResponse<String> response = request.get(String.class);
76 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
77 Assert.assertEquals(ERROR_MESSAGE, "a:b:d:", response.getEntity());
78 }
79
80 /**
81 * @tpTestDetails Old client: set query param by URL and by queryParameter function
82 * @tpSince RESTEasy 3.0.16
83 */
84 @Test
85 public void testQueryOldClient() throws Exception {
86 ClientRequest request = new ClientRequest(generateURL("/query/list?q1=a&q2=b&q1=c"));
87 request.queryParameter("q1", "d");
88 ClientResponse<String> response = request.get(String.class);
89 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
90 Assert.assertEquals(ERROR_MESSAGE, "a:c:d:", response.getEntity());
91 }
92
93 /**
94 * @tpTestDetails New client: set matrix param by URL and by matrixParam function
95 * @tpSince RESTEasy 3.0.16
96 */
97 @Test
98 public void testMatrixNewClient() throws Exception {
99 Response response = restClient.target(generateURL("/matrix;m1=a/list;m1=b;p2=c")).matrixParam("m1", "d").request().get();
100 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
101 Assert.assertEquals(ERROR_MESSAGE, "a:b:d:", response.readEntity(String.class));
102 }
103
104 /**
105 * @tpTestDetails New client: set query param by URL and by queryParam function
106 * @tpSince RESTEasy 3.0.16
107 */
108 @Test
109 public void testQueryNewClient() throws Exception {
110 Response response = restClient.target(generateURL("/query/list?q1=a&q2=b&q1=c")).queryParam("q1", "d").request().get();
111 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
112 Assert.assertEquals(ERROR_MESSAGE, "a:c:d:", response.readEntity(String.class));
113 }
114
115
116 /**
117 * @tpTestDetails Old client: check settings of matrix list by proxy
118 * @tpSince RESTEasy 3.0.16
119 */
120 @SuppressWarnings("unchecked")
121 @Test
122 public void testMatrixProxyListOldClient() throws Exception {
123 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
124 ArrayList<String> list = new ArrayList<>();
125 list.add("a");
126 list.add("b");
127 list.add("c");
128 ClientResponse<String> response = ClientResponse.class.cast(client.matrixList(list));
129 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
130 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
131 }
132
133 /**
134 * @tpTestDetails Old client: check settings of matrix set by proxy
135 * @tpSince RESTEasy 3.0.16
136 */
137 @SuppressWarnings("unchecked")
138 @Test
139 public void testMatrixProxySetOldClient() throws Exception {
140 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
141 HashSet<String> set = new HashSet<>();
142 set.add("a");
143 set.add("b");
144 set.add("c");
145 ClientResponse<String> response = ClientResponse.class.cast(client.matrixSet(set));
146 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
147 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
148 }
149
150 /**
151 * @tpTestDetails Old client: check settings of matrix sorted set by proxy
152 * @tpSince RESTEasy 3.0.16
153 */
154 @SuppressWarnings("unchecked")
155 @Test
156 public void testMatrixProxySortedSetOldClient() throws Exception {
157 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
158 TreeSet<String> set = new TreeSet<String>();
159 set.add("a");
160 set.add("b");
161 set.add("c");
162 ClientResponse<String> response = ClientResponse.class.cast(client.matrixSortedSet(set));
163 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
164 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
165 }
166
167 /**
168 * @tpTestDetails Old client: check settings of matrix list and other parameter by proxy
169 * @tpSince RESTEasy 3.0.16
170 */
171 @SuppressWarnings("unchecked")
172 @Test
173 public void testMatrixWithEntityProxyOldClient() throws Exception {
174 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
175 ArrayList<String> list = new ArrayList<>();
176 list.add("a");
177 list.add("b");
178 list.add("c");
179 ClientResponse<String> response = ClientResponse.class.cast(client.matrixWithEntity(list, "entity"));
180 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
181 Assert.assertEquals(ERROR_MESSAGE, "entity:a:b:c:", response.getEntity(String.class));
182 }
183
184 /**
185 * @tpTestDetails Old client: check settings of query list by proxy
186 * @tpSince RESTEasy 3.0.16
187 */
188 @SuppressWarnings("unchecked")
189 @Test
190 public void testQueryProxyListOldClient() throws Exception {
191 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
192 ArrayList<String> list = new ArrayList<>();
193 list.add("a");
194 list.add("b");
195 list.add("c");
196 ClientResponse<String> response = ClientResponse.class.cast(client.queryList(list));
197 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
198 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
199 }
200
201 /**
202 * @tpTestDetails Old client: check settings of query set by proxy
203 * @tpSince RESTEasy 3.0.16
204 */
205 @SuppressWarnings("unchecked")
206 @Test
207 public void testQueryProxySetOldClient() throws Exception {
208 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
209 HashSet<String> set = new HashSet<>();
210 set.add("a");
211 set.add("b");
212 set.add("c");
213 ClientResponse<String> response = ClientResponse.class.cast(client.querySet(set));
214 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
215 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
216 }
217
218 /**
219 * @tpTestDetails Old client: check settings of query sorted set by proxy
220 * @tpSince RESTEasy 3.0.16
221 */
222 @SuppressWarnings("unchecked")
223 @Test
224 public void testQueryProxySortedSetOldClient() throws Exception {
225 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
226 TreeSet<String> set = new TreeSet<String>();
227 set.add("a");
228 set.add("b");
229 set.add("c");
230 ClientResponse<String> response = ClientResponse.class.cast(client.querySortedSet(set));
231 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
232 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.getEntity(String.class));
233 }
234
235 /**
236 * @tpTestDetails Old client: check settings of query list with other parameter by proxy
237 * @tpSince RESTEasy 3.0.16
238 */
239 @SuppressWarnings("unchecked")
240 @Test
241 public void testQueryWithEntityProxyOldClient() throws Exception {
242 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
243 ArrayList<String> list = new ArrayList<>();
244 list.add("a");
245 list.add("b");
246 list.add("c");
247 ClientResponse<String> response = ClientResponse.class.cast(client.queryWithEntity(list, "entity"));
248 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
249 Assert.assertEquals(ERROR_MESSAGE, "entity:a:b:c:", response.getEntity(String.class));
250 }
251
252 /**
253 * @tpTestDetails Old client: check settings of query list, matrix list and other parameter by proxy
254 * @tpSince RESTEasy 3.0.16
255 */
256 @SuppressWarnings("unchecked")
257 @Test
258 public void testMatrixQueryWithEntityProxyOldClient() throws Exception {
259 ParameterListInterface client = ProxyFactory.create(ParameterListInterface.class, generateBaseUrl());
260 ArrayList<String> matrixParams = new ArrayList<>();
261 matrixParams.add("a");
262 matrixParams.add("b");
263 matrixParams.add("c");
264 ArrayList<String> queryParams = new ArrayList<>();
265 queryParams.add("x");
266 queryParams.add("y");
267 queryParams.add("z");
268 ClientResponse<String> response = ClientResponse.class.cast(client.matrixQueryWithEntity(matrixParams, queryParams, "entity"));
269 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
270 Assert.assertEquals(ERROR_MESSAGE, "entity:a:b:c:x:y:z:", response.getEntity(String.class));
271 }
272
273
274 /**
275 * @tpTestDetails New client: check settings of matrix list by proxy
276 * @tpSince RESTEasy 3.0.16
277 */
278 @Test
279 public void testMatrixProxyListNewClient() throws Exception {
280 final ParameterListInterface client = ProxyBuilder.builder(ParameterListInterface.class,
281 restClient.target(generateBaseUrl())).build();
282 ArrayList<String> list = new ArrayList<>();
283 list.add("a");
284 list.add("b");
285 list.add("c");
286 Response response = client.matrixList(list);
287 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
288 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.readEntity(String.class));
289 response.close();
290 }
291
292 /**
293 * @tpTestDetails New client: check settings of matrix set by proxy
294 * @tpSince RESTEasy 3.0.16
295 */
296 @Test
297 public void testMatrixProxySetNewClient() throws Exception {
298 final ParameterListInterface client = ProxyBuilder.builder(ParameterListInterface.class,
299 restClient.target(generateBaseUrl())).build();
300 HashSet<String> set = new HashSet<>();
301 set.add("a");
302 set.add("b");
303 set.add("c");
304 Response response = client.matrixSet(set);
305 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
306 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.readEntity(String.class));
307 }
308
309 /**
310 * @tpTestDetails New client: check settings of matrix sorted set by proxy
311 * @tpSince RESTEasy 3.0.16
312 */
313 @Test
314 public void testMatrixProxySortedSetNewClient() throws Exception {
315 final ParameterListInterface client = ProxyBuilder.builder(ParameterListInterface.class,
316 restClient.target(generateBaseUrl())).build();
317 TreeSet<String> set = new TreeSet<String>();
318 set.add("a");
319 set.add("b");
320 set.add("c");
321 Response response = client.matrixSortedSet(set);
322 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
323 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.readEntity(String.class));
324 }
325
326 /**
327 * @tpTestDetails New client: check settings of matrix list and other parameter by proxy
328 * @tpSince RESTEasy 3.0.16
329 */
330 @Test
331 public void testMatrixWithEntityProxyNewClient() throws Exception {
332 final ParameterListInterface client = ProxyBuilder.builder(ParameterListInterface.class,
333 restClient.target(generateBaseUrl())).build();
334 ArrayList<String> list = new ArrayList<>();
335 list.add("a");
336 list.add("b");
337 list.add("c");
338 Response response = client.matrixWithEntity(list, "entity");
339 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
340 Assert.assertEquals(ERROR_MESSAGE, "entity:a:b:c:", response.readEntity(String.class));
341 }
342
343 /**
344 * @tpTestDetails New client: check settings of query list by proxy
345 * @tpSince RESTEasy 3.0.16
346 */
347 @Test
348 public void testQueryProxyListNewClient() throws Exception {
349 final ParameterListInterface client = ProxyBuilder.builder(ParameterListInterface.class,
350 restClient.target(generateBaseUrl())).build();
351 ArrayList<String> list = new ArrayList<>();
352 list.add("a");
353 list.add("b");
354 list.add("c");
355 Response response = client.queryList(list);
356 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
357 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.readEntity(String.class));
358 }
359
360 /**
361 * @tpTestDetails New client: check settings of query set by proxy
362 * @tpSince RESTEasy 3.0.16
363 */
364 @Test
365 public void testQueryProxySetNewClient() throws Exception {
366 final ParameterListInterface client = ProxyBuilder.builder(ParameterListInterface.class,
367 restClient.target(generateBaseUrl())).build();
368 HashSet<String> set = new HashSet<>();
369 set.add("a");
370 set.add("b");
371 set.add("c");
372 Response response = client.querySet(set);
373 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
374 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.readEntity(String.class));
375 }
376
377 /**
378 * @tpTestDetails New client: check settings of query sorted set by proxy
379 * @tpSince RESTEasy 3.0.16
380 */
381 @Test
382 public void testQueryProxySortedSetNewClient() throws Exception {
383 final ParameterListInterface client = ProxyBuilder.builder(ParameterListInterface.class,
384 restClient.target(generateBaseUrl())).build();
385 TreeSet<String> set = new TreeSet<String>();
386 set.add("a");
387 set.add("b");
388 set.add("c");
389 Response response = client.querySortedSet(set);
390 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
391 Assert.assertEquals(ERROR_MESSAGE, "a:b:c:", response.readEntity(String.class));
392 }
393
394 /**
395 * @tpTestDetails New client: check settings of query list with other parameter by proxy
396 * @tpSince RESTEasy 3.0.16
397 */
398 @Test
399 public void testQueryWithEntityProxyNewClient() throws Exception {
400 final ParameterListInterface client = ProxyBuilder.builder(ParameterListInterface.class,
401 restClient.target(generateBaseUrl())).build();
402 ArrayList<String> list = new ArrayList<>();
403 list.add("a");
404 list.add("b");
405 list.add("c");
406 Response response = client.queryWithEntity(list, "entity");
407 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
408 Assert.assertEquals(ERROR_MESSAGE, "entity:a:b:c:", response.readEntity(String.class));
409 }
410
411 /**
412 * @tpTestDetails New client: check settings of query list, matrix list and other parameter by proxy
413 * @tpSince RESTEasy 3.0.16
414 */
415 @Test
416 public void testMatrixQueryWithEntityProxyNewClient() throws Exception {
417 final ParameterListInterface client = ProxyBuilder.builder(ParameterListInterface.class,
418 restClient.target(generateBaseUrl())).build();
419 ArrayList<String> matrixParams = new ArrayList<>();
420 matrixParams.add("a");
421 matrixParams.add("b");
422 matrixParams.add("c");
423 ArrayList<String> queryParams = new ArrayList<>();
424 queryParams.add("x");
425 queryParams.add("y");
426 queryParams.add("z");
427 Response response = client.matrixQueryWithEntity(matrixParams, queryParams, "entity");
428 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
429 Assert.assertEquals(ERROR_MESSAGE, "entity:a:b:c:x:y:z:", response.readEntity(String.class));
430 }
431 }
+0
-86
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/PrimitiveTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.client.resource.PrimitiveResource;
6 import org.jboss.resteasy.utils.TestUtil;
7 import org.jboss.shrinkwrap.api.Archive;
8 import org.jboss.shrinkwrap.api.spec.WebArchive;
9 import org.junit.AfterClass;
10 import org.junit.Assert;
11 import org.junit.BeforeClass;
12 import org.junit.Test;
13 import org.junit.runner.RunWith;
14
15 import javax.ws.rs.client.Client;
16 import javax.ws.rs.client.ClientBuilder;
17 import javax.ws.rs.client.Entity;
18 import javax.ws.rs.core.Response;
19
20 /**
21 * @tpSubChapter Resteasy-client
22 * @tpChapter Integration tests
23 * @tpSince RESTEasy 3.0.16
24 */
25 @RunWith(Arquillian.class)
26 @RunAsClient
27 public class PrimitiveTest extends ClientTestBase{
28
29 static Client client;
30
31 @BeforeClass
32 public static void setup() {
33 client = ClientBuilder.newClient();
34 }
35
36 @AfterClass
37 public static void close() {
38 client.close();
39 }
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(PrimitiveTest.class.getSimpleName());
44 return TestUtil.finishContainerPrepare(war, null, PrimitiveResource.class);
45 }
46
47 /**
48 * @tpTestDetails Client sends POST request with text entity, server sends echoes to value and returns int.
49 * @tpPassCrit Correct response is returned from the server
50 * @tpSince RESTEasy 3.0.16
51 */
52 @Test
53 public void testInt() {
54 Response response = client.target(generateURL("/int")).request().post(Entity.text("5"));
55 Assert.assertEquals(200, response.getStatus());
56 Assert.assertEquals("5", response.readEntity(String.class));
57 response.close();
58 }
59
60 /**
61 * @tpTestDetails Client sends POST request with text entity, server sends echoes to value and returns boolean.
62 * @tpPassCrit Correct response is returned from the server
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void testBoolean() {
67 Response response = client.target(generateURL("/boolean")).request().post(Entity.text("true"));
68 Assert.assertEquals(200, response.getStatus());
69 Assert.assertEquals("true", response.readEntity(String.class));
70 response.close();
71 }
72
73 /**
74 * @tpTestDetails Client sends GET request, server sends Accepted response
75 * @tpPassCrit Correct response is returned from the server
76 * @tpSince RESTEasy 3.0.16
77 */
78 @Test
79 public void testBuildResponse() {
80 Response response = client.target(generateURL("/nothing")).request().get();
81 Assert.assertEquals("", response.readEntity(String.class));
82 Assert.assertEquals(200, response.getStatus());
83 response.close();
84 }
85 }
+0
-67
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/SmokeParamTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.client.resource.SmokeParamResource;
6 import org.jboss.resteasy.utils.TestUtil;
7 import org.jboss.shrinkwrap.api.Archive;
8 import org.jboss.shrinkwrap.api.spec.WebArchive;
9 import org.junit.AfterClass;
10 import org.junit.Assert;
11 import org.junit.BeforeClass;
12 import org.junit.Test;
13 import org.junit.runner.RunWith;
14
15 import javax.ws.rs.client.Client;
16 import javax.ws.rs.client.ClientBuilder;
17 import javax.ws.rs.client.Entity;
18 import javax.ws.rs.core.Response;
19
20 /**
21 * @tpSubChapter Resteasy-client
22 * @tpChapter Integration tests
23 * @tpTestCaseDetails Smoke parameter test.
24 * @tpSince RESTEasy 3.0.16
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class SmokeParamTest extends ClientTestBase{
29
30 static Client client;
31
32 @BeforeClass
33 public static void setup() throws Exception {
34 client = ClientBuilder.newClient();
35 }
36
37 @Deployment
38 public static Archive<?> deploy() {
39 WebArchive war = TestUtil.prepareArchive(SmokeParamTest.class.getSimpleName());
40 return TestUtil.finishContainerPrepare(war, null, SmokeParamResource.class);
41 }
42
43 @AfterClass
44 public static void close() throws Exception {
45 client.close();
46 }
47
48 /**
49 * @tpTestDetails Test one request with header and query parameter.
50 * @tpSince RESTEasy 3.0.16
51 */
52 @Test
53 public void testSimple() throws Exception {
54 Response response = client.target(generateURL("/foo")).request()
55 .post(Entity.entity("hello world", "text/plain"));
56 Assert.assertEquals("hello world", response.readEntity(String.class));
57 response.close();
58
59 response = client.target(generateURL("/foo")).queryParam("b", "world").request()
60 .header("a", "hello")
61 .get();
62 Assert.assertEquals("hello world", response.readEntity(String.class));
63 response.close();
64
65 }
66 }
+0
-179
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/SyncInvokeTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.client.resource.SyncInvokeResource;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.TestUtil;
8 import org.jboss.shrinkwrap.api.Archive;
9 import org.jboss.shrinkwrap.api.spec.WebArchive;
10 import org.junit.Test;
11 import org.junit.Before;
12 import org.junit.After;
13 import org.junit.Assert;
14 import org.junit.runner.RunWith;
15
16 import javax.ws.rs.HttpMethod;
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.client.Entity;
20 import javax.ws.rs.core.Response;
21 import java.lang.annotation.ElementType;
22 import java.lang.annotation.Retention;
23 import java.lang.annotation.RetentionPolicy;
24
25 /**
26 * @tpSubChapter Resteasy-client
27 * @tpChapter Client tests
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class SyncInvokeTest extends ClientTestBase{
33
34 @java.lang.annotation.Target({ElementType.METHOD})
35 @Retention(RetentionPolicy.RUNTIME)
36 @HttpMethod("PATCH")
37 public @interface PATCH {
38 }
39
40 static Client client;
41
42 @Deployment
43 public static Archive<?> deploy() {
44 WebArchive war = TestUtil.prepareArchive(SyncInvokeTest.class.getSimpleName());
45 war.addClass(SyncInvokeTest.class);
46 return TestUtil.finishContainerPrepare(war, null, SyncInvokeResource.class);
47 }
48
49 @Before
50 public void init() {
51 client = ClientBuilder.newClient();
52 }
53
54 @After
55 public void after() throws Exception {
56 client.close();
57 }
58
59 /**
60 * @tpTestDetails Client sends GET, PUT, DELETE, POST and custom defined requests. First request expects
61 * Response object in return, the second expects String object in return
62 * @tpPassCrit Successful response is returned
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void testMethods() throws Exception {
67 {
68 Response res = client.target(generateURL("/test")).request().get();
69 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
70 String entity = res.readEntity(String.class);
71 Assert.assertEquals("get", entity);
72 }
73 {
74 String entity = client.target(generateURL("/test")).request().get(String.class);
75 Assert.assertEquals("get", entity);
76 }
77 {
78 Response res = client.target(generateURL("/test")).request().delete();
79 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
80 String entity = res.readEntity(String.class);
81 Assert.assertEquals("delete", entity);
82 }
83 {
84 String entity = client.target(generateURL("/test")).request().delete(String.class);
85 Assert.assertEquals("delete", entity);
86 }
87 {
88 Response res = client.target(generateURL("/test")).request().put(Entity.text("hello"));
89 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
90 String entity = res.readEntity(String.class);
91 Assert.assertEquals("put hello", entity);
92 }
93 {
94 String entity = client.target(generateURL("/test")).request().put(Entity.text("hello"), String.class);
95 Assert.assertEquals("put hello", entity);
96 }
97 {
98 Response res = client.target(generateURL("/test")).request().post(Entity.text("hello"));
99 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
100 String entity = res.readEntity(String.class);
101 Assert.assertEquals("post hello", entity);
102 }
103 {
104 String entity = client.target(generateURL("/test")).request().post(Entity.text("hello"), String.class);
105 Assert.assertEquals("post hello", entity);
106 }
107 {
108 Response res = client.target(generateURL("/test")).request().method("PATCH", Entity.text("hello"));
109 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
110 String entity = res.readEntity(String.class);
111 Assert.assertEquals("patch hello", entity);
112 }
113 {
114 String entity = client.target(generateURL("/test")).request().method("PATCH", Entity.text("hello"), String.class);
115 Assert.assertEquals("patch hello", entity);
116 }
117 }
118
119 /**
120 * @tpTestDetails Client sends GET, PUT, DELETE, POST and custom defined requests. The request is send using
121 * invoke() method. First request expects Response object in return, the second expects String object in return
122 * @tpPassCrit Successful response is returned
123 * @tpSince RESTEasy 3.0.16
124 */
125 @Test
126 public void testInvoke() throws Exception {
127 {
128 Response res = client.target(generateURL("/test")).request().buildGet().invoke();
129 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
130 String entity = res.readEntity(String.class);
131 Assert.assertEquals("get", entity);
132 }
133 {
134 String entity = client.target(generateURL("/test")).request().buildGet().invoke(String.class);
135 Assert.assertEquals("get", entity);
136 }
137 {
138 Response res = client.target(generateURL("/test")).request().buildDelete().invoke();
139 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
140 String entity = res.readEntity(String.class);
141 Assert.assertEquals("delete", entity);
142 }
143 {
144 String entity = client.target(generateURL("/test")).request().buildDelete().invoke(String.class);
145 Assert.assertEquals("delete", entity);
146 }
147 {
148 Response res = client.target(generateURL("/test")).request().buildPut(Entity.text("hello")).invoke();
149 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
150 String entity = res.readEntity(String.class);
151 Assert.assertEquals("put hello", entity);
152 }
153 {
154 String entity = client.target(generateURL("/test")).request().buildPut(Entity.text("hello")).invoke(String.class);
155 Assert.assertEquals("put hello", entity);
156 }
157 {
158 Response res = client.target(generateURL("/test")).request().buildPost(Entity.text("hello")).invoke();
159 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
160 String entity = res.readEntity(String.class);
161 Assert.assertEquals("post hello", entity);
162 }
163 {
164 String entity = client.target(generateURL("/test")).request().buildPost(Entity.text("hello")).invoke(String.class);
165 Assert.assertEquals("post hello", entity);
166 }
167 {
168 Response res = client.target(generateURL("/test")).request().build("PATCH", Entity.text("hello")).invoke();
169 Assert.assertEquals(HttpResponseCodes.SC_OK, res.getStatus());
170 String entity = res.readEntity(String.class);
171 Assert.assertEquals("patch hello", entity);
172 }
173 {
174 String entity = client.target(generateURL("/test")).request().build("PATCH", Entity.text("hello")).invoke(String.class);
175 Assert.assertEquals("patch hello", entity);
176 }
177 }
178 }
+0
-80
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/TimeoutTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.client.resource.TimeoutResource;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Test;
14 import org.junit.Assert;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.GET;
18 import javax.ws.rs.Path;
19 import javax.ws.rs.ProcessingException;
20 import javax.ws.rs.Produces;
21 import javax.ws.rs.QueryParam;
22
23 import java.net.SocketTimeoutException;
24 import java.util.concurrent.TimeUnit;
25
26 /**
27 * @tpSubChapter Resteasy-client
28 * @tpChapter Client tests
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class TimeoutTest extends ClientTestBase{
34 @Path("/timeout")
35 public interface TimeoutResourceInterface {
36 @GET
37 @Produces("text/plain")
38 String get(@QueryParam("sleep") int sleep) throws Exception;
39 }
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(TimeoutTest.class.getSimpleName());
44 war.addClass(TimeoutTest.class);
45 war.addClass(ClientTestBase.class);
46 return TestUtil.finishContainerPrepare(war, null, TimeoutResource.class);
47 }
48
49 /**
50 * @tpTestDetails Create client with custom SocketTimeout setting. Client sends GET request for the resource which
51 * calls sleep() for the specified amount of time.
52 * @tpPassCrit The request gets timeouted
53 * @tpSince RESTEasy 3.0.16
54 */
55 @Test
56 public void testTimeout() throws Exception {
57 ResteasyClient clientengine = new ResteasyClientBuilder().socketTimeout(2, TimeUnit.SECONDS).build();
58 ClientHttpEngine engine = clientengine.httpEngine();
59 Assert.assertNotNull("Client engine is was not created", engine);
60
61 ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
62 ResteasyWebTarget target = client.target(generateURL("/timeout"));
63 try {
64 target.queryParam("sleep", "5").request().get();
65 Assert.fail("The request didn't timeout as expected");
66 } catch (ProcessingException e) {
67 Assert.assertEquals("Expected SocketTimeoutException", e.getCause().getClass(), SocketTimeoutException.class);
68 }
69
70 TimeoutResourceInterface proxy = client.target(generateURL("")).proxy(TimeoutResourceInterface.class);
71 try {
72 proxy.get(5);
73 Assert.fail("The request didn't timeout as expected when using client proxy");
74 } catch (ProcessingException e) {
75 Assert.assertEquals("Expected SocketTimeoutException", e.getCause().getClass(), SocketTimeoutException.class);
76 }
77 clientengine.close();
78 }
79 }
+0
-112
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/TraceTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.dmr.ModelNode;
8 import org.jboss.resteasy.test.client.resource.TraceResource;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Test;
14 import org.junit.Before;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.BeforeClass;
18 import org.junit.AfterClass;
19 import org.junit.runner.RunWith;
20 import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
21 import org.wildfly.extras.creaper.core.online.operations.Address;
22 import org.wildfly.extras.creaper.core.online.operations.Operations;
23 import org.wildfly.extras.creaper.core.online.operations.admin.Administration;
24
25 import javax.ws.rs.HttpMethod;
26 import javax.ws.rs.client.Client;
27 import javax.ws.rs.client.ClientBuilder;
28 import javax.ws.rs.core.Response;
29 import java.lang.annotation.ElementType;
30 import java.lang.annotation.Retention;
31 import java.lang.annotation.RetentionPolicy;
32 import java.lang.annotation.Target;
33
34 /**
35 * @tpSubChapter Resteasy-client
36 * @tpChapter Client tests
37 * @tpSince RESTEasy 3.0.16
38 */
39 @RunWith(Arquillian.class)
40 @RunAsClient
41 public class TraceTest extends ClientTestBase{
42
43 private static ModelNode origDisallowedMethodsValue;
44 private static Address address = Address.subsystem("undertow").and("server", "default-server").and("http-listener", "default");
45 protected static final Logger logger = LogManager.getLogger(TraceTest.class.getName());
46 private static Client client;
47
48 @HttpMethod("TRACE")
49 @Target(value = ElementType.METHOD)
50 @Retention(value = RetentionPolicy.RUNTIME)
51 public @interface TRACE {
52 }
53
54 @BeforeClass
55 public static void setMaxPostSize() throws Exception {
56 OnlineManagementClient client = TestUtil.clientInit();
57 Administration admin = new Administration(client);
58 Operations ops = new Operations(client);
59
60 // get original 'disallowed methods' value
61 origDisallowedMethodsValue = ops.readAttribute(address, "disallowed-methods").value();
62 // set 'disallowed methods' to empty list to allow TRACE
63 ops.writeAttribute(address, "disallowed-methods", new ModelNode().setEmptyList());
64
65 // reload server
66 admin.reload();
67 client.close();
68 }
69
70 @AfterClass
71 public static void resetToDefault() throws Exception {
72 OnlineManagementClient client = TestUtil.clientInit();
73 Administration admin = new Administration(client);
74 Operations ops = new Operations(client);
75
76 // write original 'disallowed methods' value
77 ops.writeAttribute(address, "disallowed-methods", origDisallowedMethodsValue);
78
79 // reload server
80 admin.reload();
81 client.close();
82 }
83
84 @Deployment
85 public static Archive<?> deploy() {
86 WebArchive war = TestUtil.prepareArchive(TraceTest.class.getSimpleName());
87 war.addClass(TraceTest.class);
88 return TestUtil.finishContainerPrepare(war, null, TraceResource.class);
89 }
90
91 @Before
92 public void init() {
93 client = ClientBuilder.newClient();
94 }
95
96 @After
97 public void after() throws Exception {
98 client.close();
99 }
100
101 /**
102 * @tpTestDetails Client sends request for custom defined http method 'TRACE'
103 * @tpPassCrit Successful response is returned
104 * @tpSince RESTEasy 3.0.16
105 */
106 @Test
107 public void TraceTest() {
108 Response response = client.target(generateURL("/resource/trace")).request().trace(Response.class);
109 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
110 }
111 }
+0
-312
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/WebTargetTest.java less more
0 package org.jboss.resteasy.test.client;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.client.resource.WebTargetResource;
6 import org.jboss.resteasy.utils.TestUtil;
7 import org.jboss.shrinkwrap.api.Archive;
8 import org.jboss.shrinkwrap.api.spec.WebArchive;
9 import org.junit.Assert;
10 import org.junit.AfterClass;
11 import org.junit.BeforeClass;
12 import org.junit.Test;
13 import org.junit.runner.RunWith;
14
15 import javax.ws.rs.client.Client;
16 import javax.ws.rs.client.ClientBuilder;
17 import javax.ws.rs.client.WebTarget;
18
19 import java.util.HashMap;
20 import java.util.Map;
21
22 /**
23 * @author <a href="mailto:kanovotn@redhat.com">Katerina Novotna</a>
24 * @tpSubChapter Resteasy-client
25 * @tpChapter Integration tests
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class WebTargetTest extends ClientTestBase{
31
32 static Client client;
33
34 @BeforeClass
35 public static void before() {
36 client = ClientBuilder.newClient();
37 }
38
39 @Deployment
40 public static Archive<?> deploy() {
41 WebArchive war = TestUtil.prepareArchive(WebTargetTest.class.getSimpleName());
42 return TestUtil.finishContainerPrepare(war, null, WebTargetResource.class);
43 }
44
45 @AfterClass
46 public static void close() {
47 client.close();
48 }
49
50 /**
51 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance
52 * @tpPassCrit Original web target instance stayed untouched.
53 * @tpProcedure <ul>
54 * <li>Create WebTarget Instance from another base WebTarget instance</li>
55 * <li>Resolve templates in the uri</li>
56 * <li>Resolve "id" template, resolve "username" template, resolve again "id" template which should be ignored</li>
57 * <li>Resolve "username" template, create separate WebTarget instance, again resolve "username" template, resolve "id" twice</li>
58 * <li>Check original web target instance stayed untouched</li>
59 * </ul>
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void testResolveTemplate() {
64 WebTarget base = client.target(generateURL("/") + "users/{username}");
65 WebTarget created = base.path("{id}");
66
67 String result = created.resolveTemplate("id", "1").resolveTemplate("username", "test").request().get(String.class);
68 Assert.assertEquals("username: test, 1", result);
69
70 String result2 = created.resolveTemplate("id", "2").resolveTemplate("username", "test").resolveTemplate("id", "ignore").request().get(String.class);
71 Assert.assertEquals("username: test, 2", result2);
72
73 WebTarget modified = created.resolveTemplate("username", "test");
74 String result3 = modified.resolveTemplate("username", "ignore").resolveTemplate("id", "3").resolveTemplate("id", "ignore").request().get(String.class);
75 Assert.assertEquals("username: test, 3", result3);
76
77 // Original Web target remains remains same
78 Assert.assertEquals(generateURL("/") + "users/{username}" + "/{id}", created.getUriBuilder().toTemplate());
79 }
80
81 /**
82 * @tpTestDetails Create WebTarget instance and call resolveTemplate with 'null' parameter
83 * @tpPassCrit NullPointerException is raised
84 * @tpSince RESTEasy 3.0.16
85 */
86 @Test(expected = NullPointerException.class)
87 public void testResolveTemplateNull() {
88 WebTarget base = client.target(generateURL("/") + "users/{username}");
89 WebTarget created = base.path("{id}");
90
91 created.resolveTemplate(null, null);
92 }
93
94 /**
95 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, slash in the path.
96 * @tpPassCrit Response from the server matches the pattern
97 * @tpSince RESTEasy 3.0.16
98 */
99 @Test
100 public void testResolveTemplateSlash() {
101 WebTarget base = client.target(generateURL("/") + "users/{username}");
102 WebTarget created = base.path("{id}");
103 String result = created.resolveTemplate("id", "1", false).resolveTemplate("username", "te//st", true).request().get(String.class);
104 Assert.assertEquals("username: te//st, 1", result);
105 }
106
107 /**
108 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, resolve template
109 * from decoded characters
110 * @tpPassCrit Response from the server matches the pattern
111 * @tpSince RESTEasy 3.0.16
112 */
113 @Test
114 public void testResolveTemplateDecoded() {
115 final String a = "a%20%3F/*/";
116 final String b = "/b/";
117
118 WebTarget base = client.target(generateURL("/") + "users/{username}");
119 WebTarget created = base.path("{id}");
120
121 String r2 = created.resolveTemplate("username", a).resolveTemplate("id", b).getUri().toString();
122 Assert.assertEquals(generateURL("/") + "users/a%2520%253F%2F*%2F/%2Fb%2F", r2);
123
124 String result = created.resolveTemplate("id", b).resolveTemplate("username", a).request().get(String.class);
125 Assert.assertEquals("username: a%20%3F/*/, /b/", result);
126 }
127
128 /**
129 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, resolve template
130 * from encoded characters
131 * @tpPassCrit Response from the server matches the pattern
132 * @tpSince RESTEasy 3.0.16
133 */
134 @Test
135 public void testResolveTemplateEncoded() {
136 final String a = "a%20%3F/*/";
137 final String b = "/b/";
138
139 WebTarget base = client.target(generateURL("/") + "users/{username}");
140 WebTarget created = base.path("{id}");
141
142 String result_encoded = created.resolveTemplateFromEncoded("id", b).resolveTemplateFromEncoded("username", a).request().get(String.class);
143 Assert.assertEquals("username: a ?/*/, /b/", result_encoded);
144 }
145
146 /**
147 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, resolve multiple templates at once.
148 * @tpPassCrit Response from the server matches the pattern
149 * @tpSince RESTEasy 3.0.16
150 */
151 @Test
152 public void testResolveTemplates() {
153 WebTarget base = client.target(generateURL("/") + "users/{username}");
154 WebTarget created = base.path("{id}/{question}/{question}");
155
156 // Create and fill map
157 Map<String, Object> values = new HashMap<String, Object>();
158 values.put("question", "WHY");
159 values.put("id", "1");
160 values.put("username", "test");
161 values.put("unknown", "none");
162
163 String result = created.resolveTemplates(values).request().get(String.class);
164 Assert.assertEquals("username: test, 1, WHY", result);
165 }
166
167 /**
168 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, resolve templates with empty map
169 * @tpPassCrit Response from the server matches the pattern
170 * @tpSince RESTEasy 3.0.16
171 */
172 @Test
173 public void testResolveTemplatesEmptyMap() {
174 WebTarget base = client.target(generateURL("/") + "users/{username}");
175 WebTarget created = base.path("{id}/{question}/{question}");
176
177 // Create and fill map
178 Map<String, Object> values = new HashMap<String, Object>();
179
180 WebTarget result = created.resolveTemplates(values);
181 Assert.assertEquals(result, created);
182 }
183
184 /**
185 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, resolve multiple templates
186 * at once, path includes slash
187 * @tpPassCrit Response from the server matches the pattern
188 * @tpSince RESTEasy 3.0.16
189 */
190 @Test
191 public void testResolveTemplatesSlash() {
192 WebTarget base = client.target(generateURL("/") + "users/{username}");
193 WebTarget created = base.path("{id}/{question}/{question}");
194
195 // Create and fill map
196 Map<String, Object> values = new HashMap<String, Object>();
197 values.put("question", "/WHY/");
198 values.put("id", "1");
199 values.put("username", "//test");
200 values.put("unknown", "none");
201
202 String result = created.resolveTemplates(values, true).request().get(String.class);
203 Assert.assertEquals("username: //test, 1, /WHY/", result);
204 }
205
206 /**
207 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, resolve multiple
208 * templates at once, encode values
209 * @tpPassCrit Response from the server matches the pattern
210 * @tpSince RESTEasy 3.0.16
211 */
212 @Test
213 public void testResolveTemplatesEncoded() {
214 WebTarget base = client.target(generateURL("/") + "users/{username}");
215 WebTarget created = base.path("{id}/{question}/{question}");
216
217 // Create and fill map
218 Map<String, Object> values = new HashMap<String, Object>();
219 values.put("question", "hello%20world");
220 values.put("id", "%1");
221 values.put("username", "ab%5Ec");
222 values.put("unknown", "none");
223
224 String result = created.resolveTemplatesFromEncoded(values).request().get(String.class);
225 Assert.assertEquals("username: ab^c, %1, hello world", result);
226 }
227
228 /**
229 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, add and remove query params
230 * @tpPassCrit Response from the server matches the pattern
231 * @tpSince RESTEasy 3.0.16
232 */
233 @Test
234 public void testQueryParamAddAndRemove() {
235 WebTarget base = client.target(generateURL("/") + "users/{username}");
236 WebTarget created = base.path("param/{id}");
237 String result = null;
238
239 result = created.queryParam("q", "a").resolveTemplate("username", "test").resolveTemplate("id", "1").request().get(String.class);
240 Assert.assertEquals("username: test, 1, q: [a], k: []", result);
241
242 result = created.queryParam("q", "a", "b").resolveTemplate("username", "test").resolveTemplate("id", "1").request().get(String.class);
243 Assert.assertEquals("username: test, 1, q: [a, b], k: []", result);
244
245 result = created.queryParam("q", "a", "b").queryParam("k", "c", "d").resolveTemplate("username", "test").resolveTemplate("id", "1").request().get(String.class);
246 Assert.assertEquals("username: test, 1, q: [a, b], k: [c, d]", result);
247
248 result = created.queryParam("q", "a", "b").queryParam("q", (Object) null).resolveTemplate("username", "test").resolveTemplate("id", "1").request().get(String.class);
249 Assert.assertEquals("username: test, 1, q: [], k: []", result);
250
251 result = created.queryParam("q", "a").queryParam("k", "b").queryParam("q", (Object) null).resolveTemplate("username", "test").resolveTemplate("id", "1").request().get(String.class);
252 Assert.assertEquals("username: test, 1, q: [], k: [b]", result);
253 }
254
255 /**
256 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, test NullPointerException
257 * @tpPassCrit NullPointerException is raised
258 * @tpSince RESTEasy 3.0.16
259 */
260 @Test(expected = NullPointerException.class)
261 public void testQueryParamNullPointer() {
262 WebTarget base = client.target(generateURL("/") + "users/{username}");
263 WebTarget created = base.path("param/{id}");
264
265 created.queryParam("q", "a", null, "b", null);
266 }
267
268 /**
269 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, change the URI by calling matrixParam()
270 * @tpPassCrit Response from the server matches the pattern
271 * @tpProcedure <ul>
272 * <li>Create WebTarget Instance from another base WebTarget instance, change the URI by calling matrixParam()</li>
273 * <li>Add two different matrix params, add path, add matrix param with already existing name
274 * and remove it, send the resulting request to the server</li>
275 * <li>Add matrix param already in the path and send the resulting request to the server,
276 * verify tha both values from matrix param are present</li>
277 * </ul>
278 * @tpSince RESTEasy 3.0.16
279 */
280 @Test
281 public void testMatrixParamModification() {
282 WebTarget base = client.target(generateURL("/") + "users/{username}");
283 WebTarget created = base.path("matrix/{id}");
284 WebTarget modified;
285
286 modified = created.matrixParam("m1", "abcd");
287 modified = modified.matrixParam("m2", "cdef");
288 modified = modified.path("path");
289 modified = modified.matrixParam("m1", "abcd2");
290 modified = modified.matrixParam("m1", new Object[]{null});
291 String result = modified.resolveTemplate("username", "test").resolveTemplate("id", "1").request().get(String.class);
292 Assert.assertEquals("username: test, 1, m1: [abcd], m2: [cdef]", result);
293
294 modified = modified.matrixParam("m1", "abcd2");
295 result = modified.resolveTemplate("username", "test").resolveTemplate("id", "1").request().get(String.class);
296 Assert.assertEquals("username: test, 1, m1: [abcd, abcd2], m2: [cdef]", result);
297 }
298
299 /**
300 * @tpTestDetails Create WebTarget Instance from another base WebTarget instance, call MatrixParam with null argument
301 * @tpPassCrit NullPointerException is raised
302 * @tpSince RESTEasy 3.0.16
303 */
304 @Test(expected = NullPointerException.class)
305 public void testMatrixParamNullPointer() {
306 WebTarget base = client.target(generateURL("/") + "users/{username}");
307 WebTarget created = base.path("matrix/{id}");
308
309 created.matrixParam("m1", "a", null, "b", null);
310 }
311 }
+0
-92
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ClientResponseFailureTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.client.proxy.resource.ClientResponseFailureResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Test;
14 import org.junit.Before;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.GET;
20 import javax.ws.rs.NotFoundException;
21 import javax.ws.rs.Path;
22 import javax.ws.rs.Produces;
23
24 /**
25 * @tpSubChapter Resteasy-client
26 * @tpChapter Integration tests
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class ClientResponseFailureTest {
32
33 @Path("/test")
34 public interface ClientResponseFailureResourceInterface {
35 @GET
36 @Produces("text/plain")
37 String get();
38
39 @GET
40 @Path("error")
41 @Produces("text/plain")
42 String error();
43 }
44
45 static ResteasyClient client;
46
47 @Deployment
48 public static Archive<?> deploy() {
49 WebArchive war = TestUtil.prepareArchive(ClientResponseFailureTest.class.getSimpleName());
50 war.addClass(ClientResponseFailureTest.class);
51 return TestUtil.finishContainerPrepare(war, null, ClientResponseFailureResource.class);
52 }
53
54 @Before
55 public void init() {
56 client = new ResteasyClientBuilder().build();
57 }
58
59 @After
60 public void after() throws Exception {
61 client.close();
62 }
63
64 private String generateURL(String path) {
65 return PortProviderUtil.generateURL(path, ClientResponseFailureTest.class.getSimpleName());
66 }
67
68 /**
69 * @tpTestDetails Client sends async GET requests thru client proxy. The NotFoundException should be thrown as response.
70 * @tpPassCrit Exception NotFoundException is thrown
71 * @tpSince RESTEasy 3.0.16
72 */
73 @Test
74 public void testStreamStillOpen() throws Exception {
75
76 final ClientResponseFailureResourceInterface proxy = client.target(generateURL(""))
77 .proxy(ClientResponseFailureResourceInterface.class);
78 boolean failed = true;
79 try {
80 proxy.error();
81 failed = false;
82 } catch (NotFoundException e) {
83 Assert.assertEquals(HttpResponseCodes.SC_NOT_FOUND, e.getResponse().getStatus());
84 Assert.assertEquals("There wasn't expected message", e.getResponse().readEntity(String.class),
85 "there was an error");
86 e.getResponse().close();
87 }
88
89 Assert.assertTrue("The expected NotFoundException didn't happened", failed);
90 }
91 }
+0
-53
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ClientSmokeTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.client.proxy.resource.ClientSmokeResource;
8 import org.jboss.resteasy.test.core.smoke.resource.ResourceWithInterfaceSimpleClient;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 /**
18 * @tpSubChapter Smoke tests for jaxrs
19 * @tpChapter Integration tests
20 * @tpTestCaseDetails Smoke test for client ProxyFactory.
21 * @tpSince RESTEasy 3.0.16
22 */
23 @RunWith(Arquillian.class)
24 @RunAsClient
25 public class ClientSmokeTest {
26
27 @Deployment
28 public static Archive<?> deploySimpleResource() {
29 WebArchive war = TestUtil.prepareArchive(ClientSmokeTest.class.getSimpleName());
30 return TestUtil.finishContainerPrepare(war, null, ClientSmokeResource.class);
31 }
32
33 /**
34 * @tpTestDetails Check results from ResourceWithInterfaceSimpleClient.
35 * @tpSince RESTEasy 3.0.16
36 */
37 @Test
38 public void testNoDefaultsResource() throws Exception {
39 ResteasyClient client = new ResteasyClientBuilder().build();
40 ResourceWithInterfaceSimpleClient proxy = client.target(
41 PortProviderUtil.generateBaseUrl(ClientSmokeTest.class.getSimpleName()))
42 .proxyBuilder(ResourceWithInterfaceSimpleClient.class).build();
43
44 Assert.assertEquals("Wrong client answer.", "basic", proxy.getBasic());
45 proxy.putBasic("hello world");
46 Assert.assertEquals("Wrong client answer.", "hello world", proxy.getQueryParam("hello world"));
47 Assert.assertEquals("Wrong client answer.", 1234, proxy.getUriParam(1234));
48
49 client.close();
50 }
51
52 }
+0
-76
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ContextTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.client.proxy.resource.ContextTestResource;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.After;
13 import org.junit.Assert;
14 import org.junit.Before;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.GET;
19 import javax.ws.rs.Path;
20 import javax.ws.rs.Produces;
21 import javax.ws.rs.core.Context;
22 import javax.ws.rs.core.UriInfo;
23
24 /**
25 * @tpSubChapter Resteasy-client
26 * @tpChapter Integration tests
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class ContextTest {
32
33 @Path(value = "/test")
34 public interface ResourceInterface {
35
36 @GET
37 @Produces("text/plain")
38 String echo(@Context UriInfo info);
39 }
40
41 static ResteasyClient client;
42
43 @Deployment
44 public static Archive<?> deploy() {
45 WebArchive war = TestUtil.prepareArchive(ContextTest.class.getSimpleName());
46 war.addClass(ContextTest.class);
47 return TestUtil.finishContainerPrepare(war, null, ContextTestResource.class);
48 }
49
50 @Before
51 public void init() {
52 client = new ResteasyClientBuilder().build();
53 }
54
55 @After
56 public void after() throws Exception {
57 client.close();
58 }
59
60 private String generateURL(String path) {
61 return PortProviderUtil.generateURL(path, ContextTest.class.getSimpleName());
62 }
63
64 /**
65 * @tpTestDetails Client sends async GET requests thru client proxy. UriInfo is injected as argument of the GET
66 * method call.
67 * @tpPassCrit UriInfo was injected into method call
68 * @tpSince RESTEasy 3.0.16
69 */
70 @Test
71 public void testContextInjectionProxy() {
72 ResourceInterface proxy = client.target(generateURL("")).proxy(ResourceInterface.class);
73 Assert.assertEquals("UriInfo was not injected", "content", proxy.echo(null));
74 }
75 }
+0
-108
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/DefaultMediaTypesTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.client.proxy.resource.DefaultMediaTypesResource;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Test;
14 import org.junit.Before;
15 import org.junit.After;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.GET;
19 import javax.ws.rs.PUT;
20 import javax.ws.rs.Path;
21 import javax.ws.rs.core.MediaType;
22
23 import static org.junit.Assert.assertEquals;
24
25 /**
26 * @tpSubChapter Resteasy-client
27 * @tpChapter Client tests
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class DefaultMediaTypesTest {
33
34 public interface Foo {
35 @GET
36 @Path("foo")
37 String getFoo();
38
39 @PUT
40 @Path("foo")
41 String setFoo(String value);
42 }
43
44 @Deployment
45 public static Archive<?> deploy() {
46 WebArchive war = TestUtil.prepareArchive(DefaultMediaTypesTest.class.getSimpleName());
47 war.addClass(DefaultMediaTypesTest.class);
48 return TestUtil.finishContainerPrepare(war, null, DefaultMediaTypesResource.class);
49 }
50
51 static ResteasyClient client;
52
53 @Before
54 public void init() {
55 client = new ResteasyClientBuilder().build();
56 }
57
58 @After
59 public void after() throws Exception {
60 client.close();
61 }
62
63 private String generateURL(String path) {
64 return PortProviderUtil.generateURL(path, DefaultMediaTypesTest.class.getSimpleName());
65 }
66
67 /**
68 * @tpTestDetails Client sends request thru client proxy, no default consumes type is specified.
69 * @tpPassCrit Runtime exception is raised
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test(expected = RuntimeException.class)
73 public void testOldBehaviorContinues() throws Exception {
74 ResteasyWebTarget target = client.target(generateURL("/foo"));
75 target.proxy(Foo.class);
76 }
77
78 /**
79 * @tpTestDetails Client sends request thru client proxy, the request has specified default produces and consumes type
80 * @tpPassCrit The response contains acceptable media types set up by client (text/plain)
81 * @tpSince RESTEasy 3.0.16
82 */
83 @Test
84 public void testDefaultValues() throws Exception {
85 ResteasyWebTarget target = client.target(generateURL("/foo"));
86 Foo foo = target.proxyBuilder(Foo.class).defaultProduces(MediaType.TEXT_PLAIN_TYPE)
87 .defaultConsumes(MediaType.TEXT_PLAIN_TYPE).build();
88
89 assertEquals("The reponse header doesn't contain the expected media type", "[text/plain]", foo.getFoo());
90 assertEquals("The reponse header doesn't contain the expected media type", "text/plain", foo.setFoo("SOMETHING"));
91 }
92
93 /**
94 * @tpTestDetails Client sends request thru client proxy, the request has specified default produces and consumes type
95 * @tpPassCrit The response contains acceptable media types set up by client (application/json)
96 * @tpSince RESTEasy 3.0.16
97 */
98 @Test
99 public void testMismatch() throws Exception {
100 ResteasyWebTarget target = client.target(generateURL("/foo"));
101 Foo foo = target.proxyBuilder(Foo.class).defaultProduces(MediaType.APPLICATION_JSON_TYPE)
102 .defaultConsumes(MediaType.APPLICATION_JSON_TYPE).build();
103
104 assertEquals("The reponse header doesn't contain the expected media type", "[application/json]", foo.getFoo());
105 assertEquals("The reponse header doesn't contain the expected media type", "application/json", foo.setFoo("SOMETHING"));
106 }
107 }
+0
-87
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/GenericProxyTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.client.proxy.resource.GenericProxyBase;
9 import org.jboss.resteasy.test.client.proxy.resource.GenericProxySpecificProxy;
10 import org.jboss.resteasy.test.client.proxy.resource.GenericProxyResource;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.AfterClass;
17 import org.junit.Assert;
18 import org.junit.BeforeClass;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Resteasy-client
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Regression test for RESTEASY-1047.
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class GenericProxyTest {
34 private static ResteasyClient client;
35
36 @BeforeClass
37 public static void before() throws Exception {
38 client = new ResteasyClientBuilder().build();
39 }
40
41 @AfterClass
42 public static void after() throws Exception {
43 client.close();
44 }
45
46 @Deployment
47 public static Archive<?> deployUriInfoSimpleResource() {
48 WebArchive war = TestUtil.prepareArchive(GenericProxyTest.class.getSimpleName());
49 war.addClasses(GenericProxyBase.class, GenericProxySpecificProxy.class);
50 return TestUtil.finishContainerPrepare(war, null, GenericProxyResource.class);
51 }
52
53 private static String generateBaseUrl() {
54 return PortProviderUtil.generateBaseUrl(GenericProxyTest.class.getSimpleName());
55 }
56
57 /**
58 * @tpTestDetails Test generic proxy in client.
59 * @tpSince RESTEasy 3.0.16
60 */
61 @Test
62 public void testEcho() {
63 ResteasyWebTarget target = client.target(generateBaseUrl());
64 GenericProxySpecificProxy proxy = target.proxy(GenericProxySpecificProxy.class);
65 String hello = proxy.sayHi("hello");
66 Assert.assertEquals("Response has wrong content", "hello", hello);
67 hello = proxy.sayHi("hello123");
68 Assert.assertEquals("Response has wrong content", "hello123", hello);
69 }
70
71 /**
72 * @tpTestDetails Test generic proxy in client.
73 * @tpSince RESTEasy 3.0.16
74 */
75 @Test
76 public void testEchoNoProxy() {
77 ResteasyWebTarget target = client.target(generateBaseUrl() + "/say/hello");
78 Response response = target.request().post(Entity.text("hello"));
79
80 String hello = response.readEntity(String.class);
81 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
82 Assert.assertEquals("Response has wrong content", "hello", hello);
83
84 response.close();
85 }
86 }
+0
-74
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/MediaTypeCaseSensitivityTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.client.proxy.resource.MediaTypeCaseSensitivityStuff;
8 import org.jboss.resteasy.test.client.proxy.resource.MediaTypeCaseSensitivityStuffProvider;
9 import org.jboss.resteasy.test.client.proxy.resource.MediaTypeCaseSensitivityStuffResource;
10 import org.jboss.resteasy.util.HttpResponseCodes;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Entity;
20 import javax.ws.rs.client.WebTarget;
21 import javax.ws.rs.core.Response;
22
23 /**
24 * @tpSubChapter Resteasy-client
25 * @tpChapter Client tests
26 * @tpTestCaseDetails Regression test for RESTEASY-207
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class MediaTypeCaseSensitivityTest {
32
33 @Deployment
34 public static Archive<?> deploy() throws Exception {
35 WebArchive war = TestUtil.prepareArchive(MediaTypeCaseSensitivityTest.class.getSimpleName());
36 war.addClass(MediaTypeCaseSensitivityStuff.class);
37 war.addClass(PortProviderUtil.class);
38 return TestUtil.finishContainerPrepare(war, null, MediaTypeCaseSensitivityStuffResource.class,
39 MediaTypeCaseSensitivityStuffProvider.class);
40 }
41
42 /**
43 * @tpTestDetails MediaType case sensitivity when matching MessageBodyReader
44 * @tpSince RESTEasy 3.0.16
45 */
46 @Test
47 public void testItPost() throws Exception {
48 ResteasyClient client = new ResteasyClientBuilder().build();
49 WebTarget base = client.target(PortProviderUtil.generateURL("/stuff", MediaTypeCaseSensitivityTest.class.getSimpleName()));
50 Response response = base.request().post(Entity.entity("bill", "Application/Stuff"));
51 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
52 response.close();
53 client.close();
54 }
55
56 /**
57 * @tpTestDetails MediaType case sensitivity when matching MessageBodyReader, check the MessageBodyReader of
58 * the custom type is available on the server
59 * @tpSince RESTEasy 3.0.16
60 */
61 @Test
62 public void testItGet() throws Exception {
63 ResteasyClient client = new ResteasyClientBuilder().build();
64 WebTarget base = client.target(PortProviderUtil.generateURL("/stuff", MediaTypeCaseSensitivityTest.class.getSimpleName()));
65 Response response = base.request().get();
66 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
67 response.close();
68 client.close();
69 }
70
71
72
73 }
+0
-87
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ProxyCastingSimpleTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
7 import org.jboss.resteasy.client.jaxrs.internal.proxy.ResteasyClientProxy;
8 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingInterfaceB;
9 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingSimpleFooBar;
10 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingSimpleFooBarImpl;
11 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingSimpleInterfaceA;
12 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingSimpleInterfaceAorB;
13 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingSimpleInterfaceB;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.AfterClass;
19 import org.junit.BeforeClass;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 import javax.ws.rs.client.Client;
24 import javax.ws.rs.client.ClientBuilder;
25
26 import static org.junit.Assert.assertEquals;
27
28 /**
29 * @tpSubChapter Configuration
30 * @tpChapter Integration tests
31 * @tpTestCaseDetails Any interface could be cast to ResteasyClientProxy.
32 * JBEAP-3197, JBEAP-4700
33 * @tpSince RESTEasy 3.0.17
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class ProxyCastingSimpleTest {
38 private static Client client;
39 private static ResteasyWebTarget target;
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(ProxyCastingSimpleTest.class.getSimpleName());
44 war.addClasses(ProxyCastingSimpleFooBar.class,
45 ProxyCastingSimpleFooBar.class, ProxyCastingInterfaceB.class,
46 ProxyCastingSimpleInterfaceA.class, ProxyCastingSimpleInterfaceAorB.class,
47 ProxyCastingSimpleInterfaceB.class);
48 return TestUtil.finishContainerPrepare(war, null, ProxyCastingSimpleFooBarImpl.class);
49 }
50
51 private static String generateURL(String path) {
52 return PortProviderUtil.generateURL(path, ProxyCastingSimpleTest.class.getSimpleName());
53 }
54
55 @BeforeClass
56 public static void before() throws Exception {
57 client = ClientBuilder.newClient();
58 target = (ResteasyWebTarget) client.target(generateURL("/foobar"));
59 }
60
61 @AfterClass
62 public static void after() throws Exception {
63 client.close();
64 }
65
66 /**
67 * @tpTestDetails Cast one proxy to other proxy. Old client.
68 * @tpSince RESTEasy 3.0.17
69 */
70 @Test
71 public void testSubresourceProxy() throws Exception {
72 ProxyCastingSimpleFooBar foobar = ProxyBuilder.builder(ProxyCastingSimpleFooBar.class, target).build();
73 {
74 ProxyCastingSimpleInterfaceA a = ((ResteasyClientProxy) foobar.getThing("a")).as(ProxyCastingSimpleInterfaceA.class);
75 assertEquals("Wrong body of response", "FOO", a.getFoo());
76 ProxyCastingSimpleInterfaceB b = ((ResteasyClientProxy) foobar.getThing("b")).as(ProxyCastingSimpleInterfaceB.class);
77 assertEquals("Wrong body of response", "BAR", b.getBar());
78 }
79 {
80 ProxyCastingSimpleInterfaceA a = foobar.getThing("a").as(ProxyCastingSimpleInterfaceA.class);
81 assertEquals("Wrong body of response", "FOO", a.getFoo());
82 ProxyCastingSimpleInterfaceB b = foobar.getThing("b").as(ProxyCastingSimpleInterfaceB.class);
83 assertEquals("Wrong body of response", "BAR", b.getBar());
84 }
85 }
86 }
+0
-87
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ProxyCastingTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ProxyFactory;
6 import org.jboss.resteasy.client.core.marshallers.ResteasyClientProxy;
7 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingResource;
10 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingInterfaceA;
11 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingInterfaceB;
12 import org.jboss.resteasy.test.client.proxy.resource.ProxyCastingNothing;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.AfterClass;
18 import org.junit.BeforeClass;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Client;
23 import javax.ws.rs.client.ClientBuilder;
24
25 import static org.junit.Assert.assertEquals;
26
27 /**
28 * @tpSubChapter Configuration
29 * @tpChapter Integration tests
30 * @tpTestCaseDetails Any interface could be cast to ResteasyClientProxy.
31 * JBEAP-3197, JBEAP-4700
32 * @tpSince RESTEasy 3.0.16
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class ProxyCastingTest {
37 private static Client client;
38 private static ResteasyWebTarget target;
39
40 @Deployment
41 public static Archive<?> deploy() {
42 WebArchive war = TestUtil.prepareArchive(ProxyCastingTest.class.getSimpleName());
43 war.addClasses(ProxyCastingNothing.class,
44 ProxyCastingInterfaceA.class, ProxyCastingInterfaceB.class);
45 return TestUtil.finishContainerPrepare(war, null, ProxyCastingResource.class);
46 }
47
48 private static String generateURL(String path) {
49 return PortProviderUtil.generateURL(path, ProxyCastingTest.class.getSimpleName());
50 }
51
52 @BeforeClass
53 public static void before() throws Exception {
54 client = ClientBuilder.newClient();
55 target = (ResteasyWebTarget) client.target(generateURL("/foobar"));
56 }
57
58 @AfterClass
59 public static void after() throws Exception {
60 client.close();
61 }
62
63 /**
64 * @tpTestDetails Cast one proxy to other proxy. Old client.
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testOldClient() throws Exception {
69 ProxyCastingInterfaceA a = ProxyFactory.create(ProxyCastingInterfaceA.class, generateURL("/foobar"));
70 assertEquals("FOO", a.getFoo());
71 ProxyCastingInterfaceB b = ((ResteasyClientProxy) a).as(ProxyCastingInterfaceB.class);
72 assertEquals("BAR", b.getBar());
73 }
74
75 /**
76 * @tpTestDetails Cast one proxy to other proxy. New client.
77 * @tpSince RESTEasy 3.0.17
78 */
79 @Test
80 public void testNewClient() throws Exception {
81 ProxyCastingInterfaceA a = ProxyBuilder.builder(ProxyCastingInterfaceA.class, target).build();
82 assertEquals("FOO", a.getFoo());
83 ProxyCastingInterfaceB b = ((org.jboss.resteasy.client.jaxrs.internal.proxy.ResteasyClientProxy) a).as(ProxyCastingInterfaceB.class);
84 assertEquals("BAR", b.getBar());
85 }
86 }
+0
-84
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ProxyInputStreamTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ProxyFactory;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.client.proxy.resource.ProxyInputStreamProxy;
9 import org.jboss.resteasy.test.client.proxy.resource.ProxyInputStreamResource;
10 import org.jboss.resteasy.util.ReadFromStream;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import java.io.InputStream;
22
23 /**
24 * @tpSubChapter Resteasy-client
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Regression test for RESTEASY-351
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class ProxyInputStreamTest {
32
33 static ResteasyClient client;
34
35 @Deployment
36 public static Archive<?> deploy() {
37 WebArchive war = TestUtil.prepareArchive(ProxyInputStreamTest.class.getSimpleName());
38 war.addClass(ProxyInputStreamProxy.class);
39 return TestUtil.finishContainerPrepare(war, null, ProxyInputStreamResource.class);
40 }
41
42 private String generateURL(String path) {
43 return PortProviderUtil.generateURL(path, ProxyInputStreamTest.class.getSimpleName());
44 }
45
46 @Before
47 public void init() {
48 client = new ResteasyClientBuilder().build();
49 }
50
51 @After
52 public void after() throws Exception {
53 client.close();
54 }
55
56 /**
57 * @tpTestDetails Old client version
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testInputStreamOldClient() throws Exception {
62 ProxyInputStreamProxy proxy = ProxyFactory.create(ProxyInputStreamProxy.class, generateURL("/"));
63 InputStream is = proxy.get();
64 byte[] bytes = ReadFromStream.readFromStream(100, is);
65 is.close();
66 String str = new String(bytes);
67 Assert.assertEquals("hello world", str);
68 }
69
70 /**
71 * @tpTestDetails New client version
72 * @tpSince RESTEasy 3.0.16
73 */
74 @Test
75 public void testInputStreamNewClient() throws Exception {
76 ProxyInputStreamProxy proxy = client.target(generateURL("/")).proxy(ProxyInputStreamProxy.class);
77 InputStream is = proxy.get();
78 byte[] bytes = ReadFromStream.readFromStream(100, is);
79 is.close();
80 String str = new String(bytes);
81 Assert.assertEquals("hello world", str);
82 }
83 }
+0
-72
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ProxyJaxbResourceIntfTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.client.proxy.resource.ProxyJaxbCredit;
9 import org.jboss.resteasy.test.client.proxy.resource.ProxyJaxbResource;
10 import org.jboss.resteasy.test.client.proxy.resource.ProxyJaxbResourceIntf;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Test;
19 import org.junit.Before;
20 import org.junit.runner.RunWith;
21 import javax.ws.rs.core.Response;
22
23 /**
24 * @tpSubChapter Resteasy-client
25 * @tpChapter Integration tests
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class ProxyJaxbResourceIntfTest {
31
32 static ResteasyClient client;
33
34 @Deployment
35 public static Archive<?> deploy() {
36 WebArchive war = TestUtil.prepareArchive(ProxyJaxbResourceIntfTest.class.getSimpleName());
37 war.addClass(ProxyJaxbResourceIntfTest.class);
38 war.addClass(ProxyJaxbResourceIntf.class);
39 return TestUtil.finishContainerPrepare(war, null, ProxyJaxbResource.class,
40 ProxyJaxbCredit.class);
41 }
42
43 @Before
44 public void init() {
45 client = new ResteasyClientBuilder().build();
46 }
47
48 @After
49 public void after() throws Exception {
50 client.close();
51 }
52
53 private String generateURL(String path) {
54 return PortProviderUtil.generateURL(path, ProxyJaxbResourceIntfTest.class.getSimpleName());
55 }
56
57 /**
58 * @tpTestDetails Tests client proxy with annotated jaxb resource, RESTEASY-306
59 * @tpSince RESTEasy 3.0.16
60 */
61 @Test
62 public void testIt() throws Exception {
63 ProxyJaxbResourceIntf proxy = ProxyBuilder.builder(ProxyJaxbResourceIntf.class, client.target(generateURL("/"))).build();
64 Response response = proxy.getCredits("xx");
65 Assert.assertEquals(response.getStatus(), HttpResponseCodes.SC_OK);
66 ProxyJaxbCredit cred = response.readEntity(ProxyJaxbCredit.class);
67 Assert.assertEquals("Unexpected response from the server", "foobar", cred.getName());
68 }
69
70
71 }
+0
-80
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ProxyJaxbResourcePostTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.client.proxy.resource.ProxyJaxbResourceMessageResource;
9 import org.jboss.resteasy.test.client.proxy.resource.ProxyJaxbResourcePostMessage;
10 import org.jboss.resteasy.test.client.proxy.resource.ProxyJaxbResourcePostMessageIntf;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.core.Response;
23 import java.math.BigDecimal;
24 import java.util.Date;
25
26
27 /**
28 * @tpSubChapter Resteasy-client
29 * @tpChapter Integration tests
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class ProxyJaxbResourcePostTest {
35
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(ProxyJaxbResourcePostTest.class.getSimpleName());
41 war.addClass(ProxyJaxbResourcePostMessageIntf.class);
42 return TestUtil.finishContainerPrepare(war, null, ProxyJaxbResourcePostMessage.class,
43 ProxyJaxbResourceMessageResource.class);
44 }
45
46 @Before
47 public void init() {
48 client = new ResteasyClientBuilder().build();
49 }
50
51 @After
52 public void after() throws Exception {
53 client.close();
54 }
55
56 private String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, ProxyJaxbResourcePostTest.class.getSimpleName());
58 }
59
60 /**
61 * @tpTestDetails Tests client proxy with annotated jaxb resource, sends jaxb object to the server
62 * @tpSince RESTEasy 3.0.16
63 */
64 @Test
65 public void testClient() throws Exception {
66 ProxyJaxbResourcePostMessage m = new ProxyJaxbResourcePostMessage();
67 m.setMsgId(new BigDecimal(42));
68 m.setCreatedDate(new Date());
69 m.setDestinationId("ABCD1234");
70 m.setMsgComp(new BigDecimal(2));
71 m.setNumLocTfmsProvided(new BigDecimal(14));
72 m.setSourceId("WXYZ6789");
73 m.setVersionMajor("4");
74 m.setVersionMinor("1");
75 ProxyJaxbResourcePostMessageIntf proxy = ProxyBuilder.builder(ProxyJaxbResourcePostMessageIntf.class, client.target(generateURL("/"))).build();
76 Response r = proxy.saveMessage(m);
77 Assert.assertEquals(r.getStatus(), HttpResponseCodes.SC_CREATED);
78 }
79 }
+0
-80
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ProxyWithGenericReturnTypeTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.client.proxy.resource.ProxyWithGenericReturnTypeMessageBodyWriter;
10 import org.jboss.resteasy.test.client.proxy.resource.ProxyWithGenericReturnTypeResource;
11 import org.jboss.resteasy.test.client.proxy.resource.ProxyWithGenericReturnTypeSubResourceIntf;
12 import org.jboss.resteasy.test.client.proxy.resource.ProxyWithGenericReturnTypeSubResourceSubIntf;
13 import org.jboss.resteasy.test.client.proxy.resource.ProxyWithGenericReturnTypeInvocationHandler;
14 import org.jboss.resteasy.util.HttpResponseCodes;
15 import org.jboss.resteasy.utils.PortProviderUtil;
16 import org.jboss.resteasy.utils.TestUtil;
17 import org.jboss.shrinkwrap.api.Archive;
18 import org.jboss.shrinkwrap.api.spec.WebArchive;
19 import org.junit.Assert;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 import javax.ws.rs.client.WebTarget;
24 import javax.ws.rs.core.Response;
25 import java.util.ArrayList;
26 import java.util.List;
27
28 /**
29 * @tpSubChapter Resteasy-client
30 * @tpChapter Client tests
31 * @tpTestCaseDetails Test for generic proxy return type. Proxy is set on server (not on client).
32 * @tpSince RESTEasy 3.0.16
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class ProxyWithGenericReturnTypeTest {
37
38 @Deployment
39 public static Archive<?> deploySimpleResource() {
40 WebArchive war = TestUtil.prepareArchive(ProxyWithGenericReturnTypeTest.class.getSimpleName());
41
42 war.addClass(ProxyWithGenericReturnTypeInvocationHandler.class);
43 war.addClass(ProxyWithGenericReturnTypeSubResourceIntf.class);
44 war.addClass(ProxyWithGenericReturnTypeSubResourceSubIntf.class);
45
46 List<Class<?>> singletons = new ArrayList<>();
47 singletons.add(ProxyWithGenericReturnTypeMessageBodyWriter.class);
48 return TestUtil.finishContainerPrepare(war, null, singletons, ProxyWithGenericReturnTypeResource.class);
49 }
50
51 /**
52 * @tpTestDetails Test for old client
53 * @tpSince RESTEasy 3.0.16
54 */
55 @Test
56 public void oldClientTest() throws Exception {
57 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/test/list/", ProxyWithGenericReturnTypeTest.class.getSimpleName()));
58 ClientResponse<String> response = request.get(String.class);
59 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
60 Assert.assertTrue("Wrong content of response, list was not decoden on server", response.getEntity(String.class).indexOf("List<String>") >= 0);
61 }
62
63 /**
64 * @tpTestDetails Test for new client
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void newClientTest() throws Exception {
69 ResteasyClient client = new ResteasyClientBuilder().build();
70
71 WebTarget base = client.target(PortProviderUtil.generateURL("/test/list/", ProxyWithGenericReturnTypeTest.class.getSimpleName()));
72 Response response = base.request().get();
73
74 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
75 Assert.assertTrue("Wrong content of response, list was not decoden on server", response.readEntity(String.class).indexOf("List<String>") >= 0);
76
77 client.close();
78 }
79 }
+0
-142
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/ResponseObjectTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.ProxyFactory;
8 import org.jboss.resteasy.client.core.executors.InMemoryClientExecutor;
9 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
10 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
11 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
12 import org.jboss.resteasy.spi.ResteasyProviderFactory;
13 import org.jboss.resteasy.test.client.proxy.resource.ResponseObjectBasicObjectIntf;
14 import org.jboss.resteasy.test.client.proxy.resource.ResponseObjectClientIntf;
15 import org.jboss.resteasy.test.client.proxy.resource.ResponseObjectHateoasObject;
16 import org.jboss.resteasy.test.client.proxy.resource.ResponseObjectResource;
17 import org.jboss.resteasy.util.HttpResponseCodes;
18 import org.jboss.resteasy.utils.PortProviderUtil;
19 import org.jboss.resteasy.utils.TestUtil;
20 import org.jboss.shrinkwrap.api.Archive;
21 import org.jboss.shrinkwrap.api.asset.StringAsset;
22 import org.jboss.shrinkwrap.api.spec.WebArchive;
23 import org.junit.Before;
24 import org.junit.BeforeClass;
25 import org.junit.After;
26 import org.junit.Test;
27 import org.junit.Assert;
28 import org.junit.runner.RunWith;
29
30 import javax.ws.rs.ProcessingException;
31
32 /**
33 * @tpSubChapter Resteasy-client
34 * @tpChapter Integration tests
35 * @tpSince RESTEasy 3.0.16
36 */
37 @RunWith(Arquillian.class)
38 @RunAsClient
39 public class ResponseObjectTest {
40
41 protected static final Logger logger = LogManager.getLogger(ResponseObjectTest.class.getName());
42 private static InMemoryClientExecutor executor;
43 private static ResponseObjectClientIntf clientProxyFactory;
44 static ResteasyClient client;
45 ResponseObjectClientIntf responseObjectClientIntf;
46
47 @Deployment
48 public static Archive<?> deploy() {
49 WebArchive war = TestUtil.prepareArchive(ResponseObjectTest.class.getSimpleName());
50 return TestUtil.finishContainerPrepare(war, null, ResponseObjectResource.class);
51 }
52
53 @BeforeClass
54 public static void setup() {
55 ResteasyProviderFactory.setInstance(null);
56 executor = new InMemoryClientExecutor();
57 executor.getRegistry().addPerRequestResource(ResponseObjectResource.class);
58 clientProxyFactory = ProxyFactory.create(ResponseObjectClientIntf.class, "", executor);
59 }
60
61 @Before
62 public void init() {
63 client = new ResteasyClientBuilder().build();
64 responseObjectClientIntf = ProxyBuilder.builder(ResponseObjectClientIntf.class, client.target(generateURL(""))).build();
65 }
66
67 @After
68 public void after() throws Exception {
69 client.close();
70 }
71
72 private String generateURL(String path) {
73 return PortProviderUtil.generateURL(path, ResponseObjectTest.class.getSimpleName());
74 }
75
76 /**
77 * @tpTestDetails Tests ResponseObject annotation on a client interface, invoking the request with deprecated ProxyFactory instance
78 * @tpPassCrit The response contains the expected header
79 * @tpSince RESTEasy 3.0.16
80 */
81 @Test
82 public void testSimpleProxyFactory() {
83 ResponseObjectBasicObjectIntf obj = clientProxyFactory.get();
84 Assert.assertEquals(HttpResponseCodes.SC_OK, obj.status());
85 Assert.assertEquals("The response object doesn't contain the expected string", "ABC", obj.body());
86 Assert.assertEquals("The response object doesn't contain the expected header" , "text/plain;charset=UTF-8",
87 obj.responseDeprecated().getHeaders().getFirst("Content-Type"));
88 Assert.assertEquals("The response object doesn't contain the expected header", "text/plain;charset=UTF-8", obj.contentType());
89 }
90
91 /**
92 * @tpTestDetails Tests ResponseObject annotation on a client interface, and resource containg a Link object,
93 * forwarding to another resource and invoking the request with deprecated ProxyFactory instance
94 * @tpPassCrit The request was forwarded to another resource
95 * @tpSince RESTEasy 3.0.16
96 */
97 @Test
98 public void testLinkFollowProxyFactory() {
99 ResponseObjectHateoasObject obj = clientProxyFactory.performGetBasedOnHeader();
100 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, obj.status());
101 Assert.assertTrue("The resource was not forwarded", obj.nextLink().getPath().endsWith("next-link"));
102 Assert.assertEquals("The resource was not forwarded", "forwarded", obj.followNextLink());
103 }
104
105 /**
106 * @tpTestDetails Tests ResponseObject annotation on a client interface, invoking the request with ProxyBuilder instance
107 * @tpPassCrit The response contains the expected header
108 * @tpSince RESTEasy 3.0.16
109 */
110 @Test
111 public void testSimpleProxyBuilder() {
112 ResponseObjectBasicObjectIntf obj = responseObjectClientIntf.get();
113 Assert.assertEquals(HttpResponseCodes.SC_OK, obj.status());
114 Assert.assertEquals("The response object doesn't contain the expected string", "ABC", obj.body());
115 try {
116 Assert.assertEquals("The response object doesn't contain the expected header",
117 "text/plain;charset=UTF-8", obj.response().getHeaders().getFirst("Content-Type"));
118 } catch (ClassCastException ex) {
119 Assert.fail(TestUtil.getErrorMessageForKnownIssue("JBEAP-2446"));
120 }
121 Assert.assertEquals("The response object doesn't contain the expected header", "text/plain;charset=UTF-8", obj.contentType());
122 }
123
124 /**
125 * @tpTestDetails Tests ResponseObject annotation on a client interface, and resource containg a Link object,
126 * forwarding to another resource and invoking the request with ProxyBuilder instance
127 * @tpPassCrit The request was forwarded to another resource
128 * @tpSince RESTEasy 3.0.16
129 */
130 @Test
131 public void testLinkFollowProxyBuilder() {
132 ResponseObjectHateoasObject obj = responseObjectClientIntf.performGetBasedOnHeader();
133 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, obj.status());
134 Assert.assertTrue("The resource was not forwarded", obj.nextLink().getPath().endsWith("next-link"));
135 try {
136 Assert.assertEquals("The resource was not forwarded", "forwarded", obj.followNextLink());
137 } catch (ProcessingException ex) {
138 Assert.fail(TestUtil.getErrorMessageForKnownIssue("JBEAP-2446"));
139 }
140 }
141 }
+0
-100
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/SubResourceLocatorProxyTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.client.proxy.resource.SubResourceLocatorProxyBookResource;
9 import org.jboss.resteasy.test.client.proxy.resource.SubResourceLocatorProxyChapterResource;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Before;
15 import org.junit.After;
16 import org.junit.Test;
17 import org.junit.Assert;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.GET;
21 import javax.ws.rs.Path;
22 import javax.ws.rs.PathParam;
23 import javax.ws.rs.Produces;
24
25 /**
26 * @tpSubChapter Resteasy-client
27 * @tpChapter Client tests
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class SubResourceLocatorProxyTest {
33
34 public interface Book {
35 @GET
36 @Path("/title")
37 @Produces("text/plain")
38 String getTitle();
39
40 @Path("/ch/{number}")
41 Chapter getChapter(@PathParam("number") int number);
42 }
43
44 public interface Chapter {
45 @GET
46 @Path("title")
47 @Produces("text/plain")
48 String getTitle();
49
50 @GET
51 @Path("body")
52 @Produces("text/plain")
53 String getBody();
54 }
55
56 @Deployment
57 public static Archive<?> deploy() {
58 WebArchive war = TestUtil.prepareArchive(SubResourceLocatorProxyTest.class.getSimpleName());
59 war.addClass(SubResourceLocatorProxyTest.class);
60 return TestUtil.finishContainerPrepare(war, null, SubResourceLocatorProxyBookResource.class,
61 SubResourceLocatorProxyChapterResource.class);
62 }
63
64 static ResteasyClient client;
65
66 @Before
67 public void init() {
68 client = new ResteasyClientBuilder().build();
69 }
70
71 @After
72 public void after() throws Exception {
73 client.close();
74 }
75
76 private String generateURL(String path) {
77 return PortProviderUtil.generateURL(path, SubResourceLocatorProxyTest.class.getSimpleName());
78 }
79
80 /**
81 * @tpTestDetails Client sends request thru client proxy. The processing of the response goes first to the Book
82 * resource which creates Chapter subresource and creates the response.
83 * @tpPassCrit Expected string is returned in the response.
84 * @tpSince RESTEasy 3.0.16
85 */
86 @Test
87 public void testSubresourceProxy() throws Exception {
88 ResteasyWebTarget target = client.target(generateURL("/gulliverstravels"));
89 Book book = target.proxy(Book.class);
90
91 Assert.assertEquals("GET request thru client proxy failed", "Gulliver's Travels", book.getTitle());
92
93 Chapter ch1 = book.getChapter(1);
94 Assert.assertEquals("GET request thru client proxy failed", "Chapter 1", ch1.getTitle());
95
96 Chapter ch2 = book.getChapter(2);
97 Assert.assertEquals("GET request thru client proxy failed", "Chapter 2", ch2.getTitle());
98 }
99 }
+0
-55
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/UnauthorizedHttpCodeTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.client.proxy.resource.UnauthorizedHttpCodeProxy;
8 import org.jboss.resteasy.test.client.proxy.resource.UnauthorizedHttpCodeResource;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Assert;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.NotAuthorizedException;
19
20 /**
21 * @tpSubChapter Resteasy-client
22 * @tpChapter Client tests
23 * @tpSince RESTEasy 3.0.16
24 * @tpTestCaseDetails Regression test for RESTEASY-575
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class UnauthorizedHttpCodeTest {
29
30 @Deployment
31 public static Archive<?> deploy() {
32 WebArchive war = TestUtil.prepareArchive(UnauthorizedHttpCodeTest.class.getSimpleName());
33 return TestUtil.finishContainerPrepare(war, null, UnauthorizedHttpCodeResource.class);
34 }
35
36 /**
37 * @tpTestDetails Get 401 http code via proxy
38 * @tpSince RESTEasy 3.0.16
39 */
40 @Test
41 public void testProxy() throws Exception {
42 ResteasyClient client = new ResteasyClientBuilder().build();
43 UnauthorizedHttpCodeProxy proxy = client.target(PortProviderUtil.generateURL("/", UnauthorizedHttpCodeTest.class.getSimpleName())).proxy(UnauthorizedHttpCodeProxy.class);
44 try {
45 proxy.getFoo();
46 } catch (NotAuthorizedException e) {
47 Assert.assertEquals(e.getResponse().getStatus(), HttpResponseCodes.SC_UNAUTHORIZED);
48 String val = e.getResponse().readEntity(String.class);
49 Assert.assertEquals("Wrong content of response", "hello", val);
50 }
51 client.close();
52 }
53
54 }
+0
-77
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/WhitespaceTest.java less more
0 package org.jboss.resteasy.test.client.proxy;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.client.proxy.resource.WhiteSpaceResource;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.After;
13 import org.junit.Assert;
14 import org.junit.Before;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.GET;
19 import javax.ws.rs.Path;
20 import javax.ws.rs.PathParam;
21 import javax.ws.rs.Produces;
22
23 /**
24 * @tpSubChapter Resteasy-client
25 * @tpChapter Client tests
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class WhitespaceTest {
31
32 static ResteasyClient client;
33 private static final String SPACES_REQUEST = "something something";
34
35 @Deployment
36 public static Archive<?> deploy() {
37 WebArchive war = TestUtil.prepareArchive(WhitespaceTest.class.getSimpleName());
38 war.addClass(WhitespaceTest.class);
39 return TestUtil.finishContainerPrepare(war, null, WhiteSpaceResource.class);
40 }
41
42 @Before
43 public void init() {
44 client = new ResteasyClientBuilder().build();
45 }
46
47 @After
48 public void after() throws Exception {
49 client.close();
50 }
51
52 private String generateURL(String path) {
53 return PortProviderUtil.generateURL(path, WhitespaceTest.class.getSimpleName());
54 }
55
56 @Path(value = "/sayhello")
57 public interface HelloClient {
58
59 @GET
60 @Path("/en/{in}")
61 @Produces("text/plain")
62 String sayHi(@PathParam(value = "in") String in);
63 }
64
65 /**
66 * @tpTestDetails Client sends GET requests thru client proxy. The string parameter passed in the request has white
67 * space in it. The parameter is delivered with white space in the response as well.
68 * @tpPassCrit The response entity contains white space as the original request
69 * @tpSince RESTEasy 3.0.16
70 */
71 @Test
72 public void testEchoWithWhiteSpace() {
73 HelloClient proxy = client.target(generateURL("")).proxy(HelloClient.class);
74 Assert.assertEquals(SPACES_REQUEST, proxy.sayHi(SPACES_REQUEST));
75 }
76 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ClientResponseFailureResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.spi.NoLogWebApplicationException;
3 import org.jboss.resteasy.test.client.proxy.ClientResponseFailureTest;
4
5 import javax.ws.rs.core.Response;
6
7 public class ClientResponseFailureResource implements ClientResponseFailureTest.ClientResponseFailureResourceInterface {
8 public String get() {
9 return "hello world";
10 }
11
12 public String error() {
13 Response r = Response.status(404).type("text/plain").entity("there was an error").build();
14 throw new NoLogWebApplicationException(r);
15 }
16 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ClientSmokeResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2
3 import org.jboss.logging.Logger;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.PUT;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.PathParam;
11 import javax.ws.rs.Produces;
12 import javax.ws.rs.QueryParam;
13 import javax.ws.rs.core.Response;
14
15 @Path("/")
16 public class ClientSmokeResource {
17 private static Logger logger = Logger.getLogger(ClientSmokeResource.class);
18
19 @GET
20 @Path("basic")
21 @Produces("text/plain")
22 public String getBasic() {
23 logger.info("getBasic()");
24 return "basic";
25 }
26
27 @PUT
28 @Path("basic")
29 @Consumes("text/plain")
30 public void putBasic(String body) {
31 logger.info(body);
32 }
33
34 @GET
35 @Path("queryParam")
36 @Produces("text/plain")
37 public String getQueryParam(@QueryParam("param") String param) {
38 logger.info("query param: " + param);
39 return param;
40 }
41
42 @GET
43 @Path("matrixParam")
44 @Produces("text/plain")
45 public String getMatrixParam(@MatrixParam("param") String param) {
46 return param;
47 }
48
49 @GET
50 @Path("uriParam/{param}")
51 @Produces("text/plain")
52 public int getUriParam(@PathParam("param") int param) {
53 return param;
54 }
55
56 @GET
57 @Path("header")
58 public Response getHeader() {
59 return Response.ok().header("header", "headervalue").build();
60 }
61 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ContextTestResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.test.client.proxy.ContextTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.core.UriInfo;
6
7 public class ContextTestResource implements ContextTest.ResourceInterface {
8
9 public String echo(UriInfo info) {
10 Assert.assertNotNull("UriInfo was not injected into methods call", info);
11 return "content";
12 }
13 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/DefaultMediaTypesResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.spi.HttpRequest;
3 import org.jboss.resteasy.test.client.proxy.DefaultMediaTypesTest;
4
5 import javax.ws.rs.Path;
6 import javax.ws.rs.core.Context;
7
8 @Path("foo")
9 public class DefaultMediaTypesResource implements DefaultMediaTypesTest.Foo {
10 @Context
11 HttpRequest request;
12
13 @Override
14 public String getFoo() {
15 return request.getHttpHeaders().getAcceptableMediaTypes().toString();
16 }
17
18 @Override
19 public String setFoo(String value) {
20 return request.getHttpHeaders().getMediaType().toString();
21 }
22 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/GenericProxyBase.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6
7 public interface GenericProxyBase<T> {
8 @POST
9 @Path("/hello")
10 @Produces("text/plain")
11 @Consumes("text/plain")
12 String sayHi(T in);
13 }
+0
-8
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/GenericProxyResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 public class GenericProxyResource implements GenericProxySpecificProxy {
3 @Override
4 public String sayHi(String in) {
5 return in;
6 }
7 }
+0
-8
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/GenericProxySpecificProxy.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path(value = "/say")
5 public interface GenericProxySpecificProxy extends GenericProxyBase<String> {
6
7 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/MediaTypeCaseSensitivityStuff.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 public class MediaTypeCaseSensitivityStuff {
3 private String name;
4
5 public MediaTypeCaseSensitivityStuff(final String name) {
6 this.name = name;
7 }
8
9 public String getName() {
10 return name;
11 }
12 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/MediaTypeCaseSensitivityStuffProvider.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.plugins.providers.ProviderHelper;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyReader;
9 import javax.ws.rs.ext.Provider;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14
15 @Provider
16 @Consumes("appLication/stUff")
17 public class MediaTypeCaseSensitivityStuffProvider implements MessageBodyReader<MediaTypeCaseSensitivityStuff> {
18 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
19 return type.equals(MediaTypeCaseSensitivityStuff.class);
20 }
21
22 public MediaTypeCaseSensitivityStuff readFrom(Class<MediaTypeCaseSensitivityStuff> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
23 return new MediaTypeCaseSensitivityStuff(ProviderHelper.readString(entityStream, mediaType));
24 }
25 }
+0
-30
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/MediaTypeCaseSensitivityStuffResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.spi.ResteasyProviderFactory;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.ext.MessageBodyReader;
10
11 import static org.hamcrest.core.IsNull.notNullValue;
12
13 @Path("/stuff")
14 public class MediaTypeCaseSensitivityStuffResource {
15 @POST
16 public void post(MediaTypeCaseSensitivityStuff stuff) {
17 Assert.assertEquals(stuff.getName(), "bill");
18 }
19
20 @GET
21 public void get() {
22 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
23 MessageBodyReader<MediaTypeCaseSensitivityStuff> messageBodyReader = factory.getMessageBodyReader(MediaTypeCaseSensitivityStuff.class,
24 MediaTypeCaseSensitivityStuff.class, null, new MediaType("ApplIcAtion", "STufF"));
25 Assert.assertThat("RESTEasy generate wrong messageBodyReader", messageBodyReader, notNullValue());
26 Assert.assertThat("RESTEasy generate wrong messageBodyReader", messageBodyReader.getClass(), notNullValue());
27 Assert.assertEquals("RESTEasy generate wrong messageBodyReader", MediaTypeCaseSensitivityStuffProvider.class, messageBodyReader.getClass());
28 }
29 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyCastingInterfaceA.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 public interface ProxyCastingInterfaceA {
7 @GET
8 @Path("foo")
9 @Produces("text/plain")
10 String getFoo();
11 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyCastingInterfaceB.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 public interface ProxyCastingInterfaceB {
7 @GET
8 @Path("bar")
9 @Produces("text/plain")
10 String getBar();
11 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyCastingNothing.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 public interface ProxyCastingNothing {
3 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyCastingResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("/foobar")
5 public class ProxyCastingResource implements ProxyCastingInterfaceA, ProxyCastingInterfaceB, ProxyCastingNothing {
6 @Override
7 public String getFoo() {
8 return "FOO";
9 }
10
11 @Override
12 public String getBar() {
13 return "BAR";
14 }
15 }
+0
-9
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyCastingSimpleFooBar.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.PathParam;
4
5 public interface ProxyCastingSimpleFooBar {
6 @Path("{thing}")
7 ProxyCastingSimpleInterfaceAorB getThing(@PathParam("thing") String thing);
8 }
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyCastingSimpleFooBarImpl.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("/foobar")
5 public class ProxyCastingSimpleFooBarImpl implements ProxyCastingSimpleFooBar {
6 @Override
7 public ProxyCastingSimpleInterfaceAorB getThing(String thing) {
8 if ("a".equalsIgnoreCase(thing)) {
9 return new ProxyCastingSimpleInterfaceA() {
10 @Override
11 public String getFoo() {
12 return "FOO";
13 }
14
15 @Override
16 public <T> T as(Class<T> iface) {
17 return iface.cast(this);
18 }
19 };
20 } else if ("b".equalsIgnoreCase(thing)) {
21 return new ProxyCastingSimpleInterfaceB() {
22 @Override
23 public String getBar() {
24 return "BAR";
25 }
26
27 @Override
28 public <T> T as(Class<T> iface) {
29 return iface.cast(this);
30 }
31 };
32 } else {
33 throw new IllegalArgumentException("Bad arg: " + thing);
34 }
35 }
36 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyCastingSimpleInterfaceA.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 public interface ProxyCastingSimpleInterfaceA extends ProxyCastingSimpleInterfaceAorB {
7 @GET
8 @Path("foo")
9 @Produces("text/plain")
10 String getFoo();
11 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyCastingSimpleInterfaceAorB.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 public interface ProxyCastingSimpleInterfaceAorB {
3 <T> T as(Class<T> iface);
4 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyCastingSimpleInterfaceB.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 public interface ProxyCastingSimpleInterfaceB extends ProxyCastingSimpleInterfaceAorB {
7 @GET
8 @Path("bar")
9 @Produces("text/plain")
10 String getBar();
11 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyInputStreamProxy.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import java.io.InputStream;
6
7 @Path("/test")
8 public interface ProxyInputStreamProxy {
9 @GET
10 @Produces("text/plain")
11 InputStream get();
12
13 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyInputStreamResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/test")
7 public class ProxyInputStreamResource {
8 @GET
9 @Produces("text/plain")
10 public String get() {
11 return "hello world";
12 }
13
14 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyJaxbCredit.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.xml.bind.annotation.XmlElement;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement
6 public class ProxyJaxbCredit {
7 private String name;
8
9 @XmlElement
10 public String getName() {
11 return name;
12 }
13
14 public void setName(String name) {
15 this.name = name;
16 }
17 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyJaxbResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.PathParam;
3 import javax.ws.rs.core.Response;
4
5 public class ProxyJaxbResource implements ProxyJaxbResourceIntf {
6 public Response getCredits(@PathParam("userId") String userId) {
7 ProxyJaxbCredit credit = new ProxyJaxbCredit();
8 credit.setName("foobar");
9 return Response.ok(credit).build();
10 }
11 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyJaxbResourceIntf.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.Response;
7
8 @Path("/user")
9 @Produces("application/xml")
10 public interface ProxyJaxbResourceIntf {
11 @Path("/{userId}/inventory/credits")
12 @GET
13 Response getCredits(@PathParam("userId") String userId);
14 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyJaxbResourceMessageResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.core.Response;
5 import java.net.URI;
6
7 public class ProxyJaxbResourceMessageResource implements ProxyJaxbResourcePostMessageIntf {
8
9 private static Logger logger = Logger.getLogger(ProxyJaxbResourceMessageResource.class.getName());
10
11 @Override
12 public Response saveMessage(ProxyJaxbResourcePostMessage msg) {
13 logger.info("saveMessage");
14 return Response.created(URI.create("/foo/bar")).build();
15 }
16 }
+0
-82
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyJaxbResourcePostMessage.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3 import java.math.BigDecimal;
4 import java.util.Date;
5
6 @XmlRootElement
7 public class ProxyJaxbResourcePostMessage {
8 private BigDecimal msgId;
9 private Date createdDate;
10 private String destinationId;
11 private BigDecimal msgComp;
12 private BigDecimal numLocTfmsProvided;
13 private String sourceId;
14 private String versionMajor;
15 private String versionMinor;
16
17
18 public BigDecimal getMsgId() {
19 return msgId;
20 }
21
22 public void setMsgId(BigDecimal msgId) {
23 this.msgId = msgId;
24 }
25
26 public Date getCreatedDate() {
27 return createdDate;
28 }
29
30 public void setCreatedDate(Date createdDate) {
31 this.createdDate = createdDate;
32 }
33
34 public String getDestinationId() {
35 return destinationId;
36 }
37
38 public void setDestinationId(String destinationId) {
39 this.destinationId = destinationId;
40 }
41
42 public BigDecimal getMsgComp() {
43 return msgComp;
44 }
45
46 public void setMsgComp(BigDecimal msgComp) {
47 this.msgComp = msgComp;
48 }
49
50 public BigDecimal getNumLocTfmsProvided() {
51 return numLocTfmsProvided;
52 }
53
54 public void setNumLocTfmsProvided(BigDecimal numLocTfmsProvided) {
55 this.numLocTfmsProvided = numLocTfmsProvided;
56 }
57
58 public String getSourceId() {
59 return sourceId;
60 }
61
62 public void setSourceId(String sourceId) {
63 this.sourceId = sourceId;
64 }
65
66 public String getVersionMajor() {
67 return versionMajor;
68 }
69
70 public void setVersionMajor(String versionMajor) {
71 this.versionMajor = versionMajor;
72 }
73
74 public String getVersionMinor() {
75 return versionMinor;
76 }
77
78 public void setVersionMinor(String versionMinor) {
79 this.versionMinor = versionMinor;
80 }
81 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyJaxbResourcePostMessageIntf.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.core.Response;
6
7 @Path("/messages/TFM")
8 public interface ProxyJaxbResourcePostMessageIntf {
9
10 @POST
11 @Consumes("application/xml")
12 Response saveMessage(ProxyJaxbResourcePostMessage msg);
13
14 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyWithGenericReturnTypeInvocationHandler.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import java.lang.reflect.InvocationHandler;
3 import java.lang.reflect.Method;
4 import java.util.ArrayList;
5 import java.util.List;
6
7 public class ProxyWithGenericReturnTypeInvocationHandler implements InvocationHandler {
8 @Override
9 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
10 List<String> result = new ArrayList<String>();
11 return result;
12 }
13 }
+0
-58
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyWithGenericReturnTypeMessageBodyWriter.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import javax.ws.rs.ext.MessageBodyWriter;
6 import javax.ws.rs.ext.Provider;
7 import java.io.IOException;
8 import java.io.OutputStream;
9 import java.lang.annotation.Annotation;
10 import java.lang.reflect.GenericArrayType;
11 import java.lang.reflect.ParameterizedType;
12 import java.lang.reflect.Type;
13 import java.lang.reflect.TypeVariable;
14 import java.util.List;
15
16 @Provider
17 public class ProxyWithGenericReturnTypeMessageBodyWriter implements MessageBodyWriter<List<String>> {
18 @Override
19 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
20 return true;
21 }
22
23 @Override
24 public long getSize(List<String> t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
25 return -1;
26 }
27
28 @Override
29 public void writeTo(List<String> t, Class<?> type, Type genericType,
30 Annotation[] annotations, MediaType mediaType,
31 MultivaluedMap<String, Object> httpHeaders,
32 OutputStream entityStream) throws IOException,
33 WebApplicationException {
34 String val;
35 if (genericType == null) {
36 val = "null";
37 } else if (genericType instanceof ParameterizedType) {
38 ParameterizedType parameterizedType = (ParameterizedType) genericType;
39 val = ((Class) parameterizedType.getRawType()).getSimpleName() + "<";
40 Type paramType = parameterizedType.getActualTypeArguments()[0];
41 if (paramType instanceof Class) {
42 val += ((Class) paramType).getSimpleName();
43 } else {
44 val += paramType.toString();
45 }
46 val += ">";
47 } else if (genericType instanceof TypeVariable) {
48 val = "TypeVariable";
49 } else if (genericType instanceof GenericArrayType) {
50 val = "GenericArrayType";
51 } else {
52 val = "Type";
53 }
54
55 entityStream.write(val.getBytes());
56 }
57 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyWithGenericReturnTypeResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.Produces;
4 import java.lang.reflect.Proxy;
5
6 @Path("/")
7 public class ProxyWithGenericReturnTypeResource {
8 @Produces("text/plain")
9 @Path("test")
10 public ProxyWithGenericReturnTypeSubResourceSubIntf resourceLocator() {
11 Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
12 new Class[]{ProxyWithGenericReturnTypeSubResourceSubIntf.class},
13 new ProxyWithGenericReturnTypeInvocationHandler());
14
15 return ProxyWithGenericReturnTypeSubResourceSubIntf.class.cast(proxy);
16 }
17 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyWithGenericReturnTypeSubResourceIntf.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import java.util.List;
6
7 public interface ProxyWithGenericReturnTypeSubResourceIntf<T> {
8 @GET
9 @Path("list")
10 @Produces("text/plain")
11 List<T> resourceMethod();
12 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ProxyWithGenericReturnTypeSubResourceSubIntf.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 public interface ProxyWithGenericReturnTypeSubResourceSubIntf extends ProxyWithGenericReturnTypeSubResourceIntf<String> {
3 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ResponseObjectBasicObjectIntf.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.annotations.Body;
3 import org.jboss.resteasy.annotations.ResponseObject;
4 import org.jboss.resteasy.annotations.Status;
5 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Tests deprecated client proxy)
6
7 import javax.ws.rs.HeaderParam;
8
9 @ResponseObject
10 public interface ResponseObjectBasicObjectIntf {
11 @Status
12 int status();
13
14 @Body
15 String body();
16
17 org.jboss.resteasy.client.jaxrs.internal.ClientResponse response();
18
19 ClientResponse responseDeprecated();
20
21 @HeaderParam("Content-Type")
22 String contentType();
23 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ResponseObjectClientIntf.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 @Path("test")
6 public interface ResponseObjectClientIntf {
7 @GET
8 ResponseObjectBasicObjectIntf get();
9
10 @GET
11 @Path("link-header")
12 ResponseObjectHateoasObject performGetBasedOnHeader();
13 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ResponseObjectHateoasObject.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.annotations.LinkHeaderParam;
3 import org.jboss.resteasy.annotations.ResponseObject;
4 import org.jboss.resteasy.annotations.Status;
5
6 import javax.ws.rs.GET;
7 import java.net.URI;
8
9 @ResponseObject
10 public interface ResponseObjectHateoasObject {
11 @Status
12 int status();
13
14 @LinkHeaderParam(rel = "nextLink")
15 URI nextLink();
16
17 @GET
18 @LinkHeaderParam(rel = "nextLink")
19 String followNextLink();
20 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/ResponseObjectResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.client.Link;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.Context;
8 import javax.ws.rs.core.Response;
9 import javax.ws.rs.core.UriInfo;
10 import java.net.URI;
11
12 @Path("test")
13 public class ResponseObjectResource {
14
15 @GET
16 @Produces("text/plain")
17 public String get() {
18 return "ABC";
19 }
20
21 @GET
22 @Path("/link-header")
23 public Response getWithHeader(@Context UriInfo uri) {
24 URI subUri = uri.getAbsolutePathBuilder().path("next-link").build();
25 Link link = new Link();
26 link.setHref(subUri.toASCIIString());
27 link.setRelationship("nextLink");
28 return Response.noContent().header("Link", link.toString()).build();
29 }
30
31 @GET
32 @Produces("text/plain")
33 @Path("/link-header/next-link")
34 public String getHeaderForward() {
35 return "forwarded";
36 }
37 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/SubResourceLocatorProxyBookResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.test.client.proxy.SubResourceLocatorProxyTest;
3
4 import javax.ws.rs.Path;
5
6 @Path("/gulliverstravels")
7 public class SubResourceLocatorProxyBookResource implements SubResourceLocatorProxyTest.Book {
8 public String getTitle() {
9 return "Gulliver's Travels";
10 }
11
12 @Override
13 public SubResourceLocatorProxyTest.Chapter getChapter(int number) {
14 return new SubResourceLocatorProxyChapterResource(number);
15 }
16 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/SubResourceLocatorProxyChapterResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.resteasy.test.client.proxy.SubResourceLocatorProxyTest;
3
4 public class SubResourceLocatorProxyChapterResource implements SubResourceLocatorProxyTest.Chapter {
5 private final int number;
6
7 public SubResourceLocatorProxyChapterResource(final int number) {
8 this.number = number;
9 }
10
11 public String getTitle() {
12 return "Chapter " + number;
13 }
14
15 public String getBody() {
16 return "This is the content of chapter " + number + ".";
17 }
18 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/UnauthorizedHttpCodeObject.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 public class UnauthorizedHttpCodeObject {
3
4 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/UnauthorizedHttpCodeProxy.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/regression")
7 public interface UnauthorizedHttpCodeProxy {
8 @GET
9 @Produces("application/foo")
10 UnauthorizedHttpCodeObject getFoo();
11 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/UnauthorizedHttpCodeResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5
6 @Path("/regression")
7 public class UnauthorizedHttpCodeResource {
8 @GET
9 public Response get() {
10 return Response.status(401).entity("hello").type("application/error").build();
11 }
12 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/proxy/resource/WhiteSpaceResource.java less more
0 package org.jboss.resteasy.test.client.proxy.resource;
1
2 import org.jboss.logging.Logger;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.Context;
10 import javax.ws.rs.core.UriInfo;
11 import java.util.List;
12
13 @Path(value = "/sayhello")
14 public class WhiteSpaceResource {
15
16 String SPACES_REQUEST = "something something";
17 private static final Logger logger = Logger.getLogger(WhiteSpaceResource.class);
18
19 @Context
20 UriInfo info;
21
22 @GET
23 @Path("/en/{in}")
24 @Produces("text/plain")
25 public String echo(@PathParam(value = "in") String in) {
26 Assert.assertEquals(SPACES_REQUEST, in);
27 List<String> params = info.getPathParameters(true).get("in");
28 logger.info("DECODE" + params.get(0));
29
30 params = info.getPathParameters(false).get("in");
31 logger.info("ENCODE" + params.get(0));
32
33 return in;
34 }
35 }
+0
-51
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/AsyncInvokeResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.test.client.AsyncInvokeTest;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.DELETE;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.Consumes;
10 import javax.ws.rs.Path;
11
12
13 @Path("/test")
14 public class AsyncInvokeResource {
15 @GET
16 @Produces("text/plain")
17 public String get() throws Exception {
18 Thread.sleep(100);
19 return "get";
20 }
21
22 @PUT
23 @Consumes("text/plain")
24 public String put(String str) throws Exception {
25 Thread.sleep(100);
26 return "put " + str;
27 }
28
29 @POST
30 @Consumes("text/plain")
31 public String post(String str) throws Exception {
32 Thread.sleep(100);
33 return "post " + str;
34 }
35
36 @DELETE
37 @Produces("text/plain")
38 public String delete() throws Exception {
39 Thread.sleep(100);
40 return "delete";
41 }
42
43 @AsyncInvokeTest.PATCH
44 @Produces("text/plain")
45 @Consumes("text/plain")
46 public String patch(String str) throws Exception {
47 Thread.sleep(100);
48 return "patch " + str;
49 }
50 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientDynamicFeaturesClientFeature1.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.ConstrainedTo;
3 import javax.ws.rs.RuntimeType;
4 import javax.ws.rs.container.DynamicFeature;
5 import javax.ws.rs.container.ResourceInfo;
6 import javax.ws.rs.core.FeatureContext;
7
8 @ConstrainedTo(RuntimeType.CLIENT)
9 public class ClientDynamicFeaturesClientFeature1 implements DynamicFeature {
10 @Override
11 public void configure(ResourceInfo resourceInfo, FeatureContext context) {
12 }
13 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientDynamicFeaturesClientFeature2.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.ConstrainedTo;
3 import javax.ws.rs.RuntimeType;
4 import javax.ws.rs.container.DynamicFeature;
5 import javax.ws.rs.container.ResourceInfo;
6 import javax.ws.rs.core.FeatureContext;
7
8 @ConstrainedTo(RuntimeType.CLIENT)
9 public class ClientDynamicFeaturesClientFeature2 implements DynamicFeature {
10 @Override
11 public void configure(ResourceInfo resourceInfo, FeatureContext context) {
12 }
13 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientDynamicFeaturesDualFeature1.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.container.DynamicFeature;
3 import javax.ws.rs.container.ResourceInfo;
4 import javax.ws.rs.core.FeatureContext;
5
6 public class ClientDynamicFeaturesDualFeature1 implements DynamicFeature {
7 @Override
8 public void configure(ResourceInfo resourceInfo, FeatureContext context) {
9 }
10 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientDynamicFeaturesDualFeature2.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.container.DynamicFeature;
3 import javax.ws.rs.container.ResourceInfo;
4 import javax.ws.rs.core.FeatureContext;
5
6 public class ClientDynamicFeaturesDualFeature2 implements DynamicFeature {
7 @Override
8 public void configure(ResourceInfo resourceInfo, FeatureContext context) {
9 }
10 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientDynamicFeaturesServerFeature1.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.ConstrainedTo;
3 import javax.ws.rs.RuntimeType;
4 import javax.ws.rs.container.DynamicFeature;
5 import javax.ws.rs.container.ResourceInfo;
6 import javax.ws.rs.core.FeatureContext;
7
8 @ConstrainedTo(RuntimeType.SERVER)
9 public class ClientDynamicFeaturesServerFeature1 implements DynamicFeature {
10 @Override
11 public void configure(ResourceInfo resourceInfo, FeatureContext context) {
12 }
13 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientDynamicFeaturesServerFeature2.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.ConstrainedTo;
3 import javax.ws.rs.RuntimeType;
4 import javax.ws.rs.container.DynamicFeature;
5 import javax.ws.rs.container.ResourceInfo;
6 import javax.ws.rs.core.FeatureContext;
7
8 @ConstrainedTo(RuntimeType.SERVER)
9 public class ClientDynamicFeaturesServerFeature2 implements DynamicFeature {
10 @Override
11 public void configure(ResourceInfo resourceInfo, FeatureContext context) {
12 }
13 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientExceptionsCustomClientRequestFilter.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.client.ClientRequestContext;
3 import javax.ws.rs.client.ClientRequestFilter;
4 import java.io.IOException;
5
6 public class ClientExceptionsCustomClientRequestFilter implements ClientRequestFilter {
7 @Override
8 public void filter(ClientRequestContext requestContext) throws IOException {
9 throw new IOException("client io");
10 }
11 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientExceptionsCustomClientResponseFilter.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.client.ClientRequestContext;
3 import javax.ws.rs.client.ClientResponseContext;
4 import javax.ws.rs.client.ClientResponseFilter;
5 import java.io.IOException;
6
7 public class ClientExceptionsCustomClientResponseFilter implements ClientResponseFilter {
8
9 @Override
10 public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
11 throw new IOException("client io");
12 }
13 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientExceptionsData.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 public class ClientExceptionsData {
3 public final String data;
4 public final String type;
5
6 public ClientExceptionsData(final String data, final String type) {
7 this.data = data;
8 this.type = type;
9 }
10 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientExceptionsIOExceptionReaderInterceptor.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.ext.ReaderInterceptor;
4 import javax.ws.rs.ext.ReaderInterceptorContext;
5 import java.io.IOException;
6
7 public class ClientExceptionsIOExceptionReaderInterceptor implements ReaderInterceptor {
8 @Override
9 public Object aroundReadFrom(final ReaderInterceptorContext context) throws IOException, WebApplicationException {
10 throw new IOException("client io");
11 }
12 }
+0
-58
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientExceptionsResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.util.HttpResponseCodes;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.WebApplicationException;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.HttpHeaders;
10 import javax.ws.rs.core.Response;
11
12 @Path("/")
13 public class ClientExceptionsResource {
14 @POST
15 @Path("post")
16 public Response post(ClientExceptionsData data) {
17 return Response.ok().entity(data).build();
18 }
19
20 @GET
21 @Path("get")
22 public String get() {
23 return "OK";
24 }
25
26 @Path("data")
27 @GET
28 public Response getData(@Context HttpHeaders headers) {
29 Response response = Response.ok()
30 .type(headers.getAcceptableMediaTypes().get(0))
31 .entity(new ClientExceptionsData("test", "test"))
32 .build();
33 return response;
34 }
35
36 @Path("senddata")
37 @POST
38 public ClientExceptionsData postandget(ClientExceptionsData data) {
39 return data;
40 }
41
42 @Path("empty")
43 @GET
44 public Response getEmpty(@Context HttpHeaders headers) {
45 Response response = Response.ok()
46 .type(headers.getAcceptableMediaTypes().get(0))
47 .header(HttpHeaders.CONTENT_LENGTH, 0)
48 .build();
49 return response;
50 }
51
52 @GET
53 @Path("error")
54 public Response error() {
55 throw new WebApplicationException(HttpResponseCodes.SC_FORBIDDEN);
56 }
57 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientExecutorShutdownTestResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6
7 @Path("/test")
8 public class ClientExecutorShutdownTestResource {
9
10 private static final Logger logger = Logger.getLogger(ClientExecutorShutdownTestResource.class);
11
12 @POST
13 public void post() {
14 logger.info("In POST");
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientFormResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.test.client.ClientFormParamTest;
3
4 import javax.ws.rs.core.Form;
5
6 public class ClientFormResource implements ClientFormParamTest.ClientFormResourceInterface {
7
8 public String put(String value) {
9 return value;
10 }
11
12 @Override
13 public Form post(Form form) {
14 return form;
15 }
16 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientProviderStringEntityProviderReader.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.test.client.ClientProviderTest;
3
4 import javax.ws.rs.WebApplicationException;
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.MultivaluedMap;
7 import javax.ws.rs.ext.MessageBodyReader;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.Type;
12
13 public class ClientProviderStringEntityProviderReader implements MessageBodyReader<String> {
14 @Override
15 public boolean isReadable(Class<?> type, Type genericType,
16 Annotation[] annotations, MediaType mediaType) {
17 return type == String.class;
18 }
19
20 @Override
21 public String readFrom(Class<String> type,
22 Type genericType, Annotation[] annotations, MediaType mediaType,
23 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
24 throws IOException, WebApplicationException {
25 String text = ClientProviderTest.readFromStream(entityStream);
26 entityStream.close();
27 String result = "Application defined provider reader: " + text;
28 return result;
29 }
30 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientProviderStringEntityProviderWriter.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import javax.ws.rs.ext.MessageBodyWriter;
6 import java.io.IOException;
7 import java.io.OutputStream;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Type;
10
11 public class ClientProviderStringEntityProviderWriter implements MessageBodyWriter<String> {
12 @Override
13 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
14 return type == String.class;
15 }
16
17 @Override
18 public long getSize(String s, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
19 return s.length();
20 }
21
22 @Override
23 public void writeTo(String s, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
24 entityStream.write(("Application defined provider writer: " + mediaType.toString() + httpHeaders.toString()).getBytes());
25 }
26 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientResponseRedirectClientResponseOld.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6
7 @Path("/redirect")
8 public interface ClientResponseRedirectClientResponseOld {
9 @GET
10 ClientResponse get();
11 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientResponseRedirectIntf.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5
6 @Path("/redirect")
7 public interface ClientResponseRedirectIntf {
8 @GET
9 Response get();
10 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientResponseRedirectResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.test.client.ClientResponseRedirectTest;
3 import org.jboss.resteasy.utils.PortProviderUtil;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.core.Response;
8 import java.net.URI;
9
10 @Path("/redirect")
11 public class ClientResponseRedirectResource {
12 @GET
13 public Response get() {
14 try {
15 return Response.seeOther(URI.create(PortProviderUtil.generateURL("/redirect/data", ClientResponseRedirectTest.class.getSimpleName()))).build();
16 } catch (IllegalArgumentException e) {
17 throw new RuntimeException(e);
18 }
19 }
20
21 @GET
22 @Path("data")
23 public String getData() {
24 return "data";
25 }
26 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/EntityBufferingInFileResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.activation.DataSource;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import java.io.InputStream;
9
10 @Path("/")
11 public class EntityBufferingInFileResource {
12
13 private static final Logger logger = Logger.getLogger(EntityBufferingInFileResource.class);
14
15 @POST
16 @Produces("text/plain")
17 @Path("hello")
18 public InputStream resourceMethod(DataSource ds) throws Exception {
19 logger.info("entered resourceMethod()");
20 return ds.getInputStream();
21 }
22 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/GenericReturnTypeInterface.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 public interface GenericReturnTypeInterface<T> {
6 @GET
7 @Path("t")
8 T t();
9 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/GenericReturnTypeReader.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import javax.ws.rs.ext.MessageBodyReader;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Type;
10
11 public class GenericReturnTypeReader implements MessageBodyReader<Object> {
12 @Override
13 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
14 return true;
15 }
16
17 @Override
18 public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
19 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
20 throws IOException, WebApplicationException {
21 StringBuffer sb = new StringBuffer();
22 int c = entityStream.read();
23 while (c != -1) {
24 sb.append((char) c);
25 c = entityStream.read();
26 }
27 return sb.toString();
28 }
29
30 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/GenericReturnTypeResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("")
7 public class GenericReturnTypeResource implements GenericReturnTypeInterface<String> {
8 @GET
9 @Path("t")
10 @Produces("text/plain")
11 public String t() {
12 return "abc";
13 }
14 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/IndirectInvocationTestResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.QueryParam;
8
9 @Path("/test")
10 public class IndirectInvocationTestResource {
11 @GET
12 @Path("/query")
13 @Produces("text/plain")
14 public String get(@QueryParam("param") String p, @QueryParam("id") String id) {
15 return p + " " + id;
16 }
17
18 @POST
19 @Path("/send")
20 @Consumes("text/plain")
21 public String post(@QueryParam("param") String p, @QueryParam("id") String id, String str) {
22 return str;
23 }
24 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/InputStreamResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/")
7 public class InputStreamResource {
8 @Path("test")
9 @Produces("text/plain")
10 @GET
11 public String get() {
12 return "hello world";
13 }
14 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/InputStreamResourceClient.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import java.io.InputStream;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.GET;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.Response;
10
11 @Path("/inputStream")
12 @Produces("text/plain")
13 @Consumes("text/plain")
14 public interface InputStreamResourceClient {
15
16 @GET
17 String getAsString();
18
19 @GET
20 Response getAsInputStream();
21
22 @POST
23 Response postInputStream(InputStream is);
24
25 @POST
26 Response postString(String s);
27 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/InputStreamResourceService.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import java.io.ByteArrayInputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.GET;
8 import javax.ws.rs.POST;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.Produces;
11
12 import org.jboss.resteasy.util.ReadFromStream;
13
14 @Path("/inputStream")
15 public class InputStreamResourceService {
16 static String result = "hello";
17
18 @GET
19 @Produces("text/plain")
20 public InputStream get()
21 {
22 return new ByteArrayInputStream(result.getBytes());
23 }
24
25 @POST
26 @Consumes("text/plain")
27 public void post(InputStream is) throws IOException
28 {
29 result = new String(ReadFromStream.readFromStream(1024, is));
30 }
31
32 }
+0
-60
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/LinkHeaderService.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.logging.Logger;
3 import org.jboss.resteasy.plugins.delegates.LinkHeaderDelegate;
4 import org.jboss.resteasy.spi.LinkHeader;
5
6 import javax.ws.rs.HEAD;
7 import javax.ws.rs.HeaderParam;
8 import javax.ws.rs.POST;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.core.Context;
11 import javax.ws.rs.core.Response;
12 import javax.ws.rs.core.UriBuilder;
13 import javax.ws.rs.core.UriInfo;
14
15 @Path("/linkheader")
16 public class LinkHeaderService {
17 private static Logger logger = Logger.getLogger(LinkHeaderService.class);
18
19
20 @POST
21 public Response post(@HeaderParam("Link") LinkHeader linkHeader) {
22 logger.info("SERVER LinkHeader: " + new LinkHeaderDelegate().toString(linkHeader));
23 return Response.noContent().header("Link", linkHeader).build();
24 }
25
26 @POST
27 @Path("/str")
28 public Response postStr(@HeaderParam("Link") String linkHeader) {
29 logger.info("SERVER LINK: " + linkHeader);
30 return Response.noContent().header("Link", linkHeader).build();
31 }
32
33 @HEAD
34 @Path("/topic")
35 public Response head(@Context UriInfo uriInfo) {
36 return Response.ok()
37 .header("Link", getSenderLink(uriInfo))
38 .header("Link", getTopLink(uriInfo)).build();
39 }
40
41 protected String getSenderLink(UriInfo info) {
42 String basePath = info.getMatchedURIs().get(0);
43 UriBuilder builder = info.getBaseUriBuilder();
44 builder.path(basePath);
45 builder.path("sender");
46 String link = "<" + builder.build().toString() + ">; rel=\"sender\"; title=\"sender\"";
47 return link;
48 }
49
50 protected String getTopLink(UriInfo info) {
51 String basePath = info.getMatchedURIs().get(0);
52 UriBuilder builder = info.getBaseUriBuilder();
53 builder.path(basePath);
54 builder.path("poller");
55 String link = "<" + builder.build().toString() + ">; rel=\"top-message\"; title=\"top-message\"";
56 return link;
57 }
58
59 }
+0
-58
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/NullEntityResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.annotation.Resource;
3 import javax.ws.rs.Consumes;
4 import javax.ws.rs.FormParam;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8
9 @Resource(name = "NullEntityResource")
10 @Path("")
11 public class NullEntityResource {
12 @POST
13 @Path("null")
14 @Produces("text/plain")
15 public String post(String entity) {
16 return entity;
17 }
18
19 @POST
20 @Path("entity")
21 @Produces("text/plain")
22 public String empty(String entity) {
23 return entity;
24 }
25
26 @POST
27 @Path("form")
28 @Consumes("application/x-www-form-urlencoded")
29 @Produces("text/plain")
30 public String form(@FormParam("s") String s) {
31 return s;
32 }
33
34 @POST
35 @Path("html")
36 @Consumes("text/html")
37 @Produces("text/plain")
38 public String html(String html) {
39 return html;
40 }
41
42 @POST
43 @Path("xhtml")
44 @Consumes("application/xhtml+xml")
45 @Produces("text/plain")
46 public String xhtml(String xhtml) {
47 return xhtml;
48 }
49
50 @POST
51 @Path("xml")
52 @Consumes("application/xml")
53 @Produces("text/plain")
54 public String xml(String xml) {
55 return xml;
56 }
57 }
+0
-53
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ParameterListInterface.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.MatrixParam;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.QueryParam;
8 import javax.ws.rs.core.Response;
9 import java.util.List;
10 import java.util.Set;
11 import java.util.SortedSet;
12
13 public interface ParameterListInterface {
14 @GET
15 @Path("matrix/list")
16 Response matrixList(@MatrixParam("m1") List<String> list);
17
18 @GET
19 @Path("matrix/set")
20 Response matrixSet(@MatrixParam("m1") Set<String> set);
21
22 @GET
23 @Path("matrix/sortedset")
24 Response matrixSortedSet(@MatrixParam("m1") SortedSet<String> set);
25
26 @PUT
27 @Consumes("text/plain")
28 @Path("matrix/entity")
29 Response matrixWithEntity(@MatrixParam("m1") List<String> list, String entity);
30
31 @GET
32 @Path("query/list")
33 Response queryList(@QueryParam("q1") List<String> list);
34
35 @GET
36 @Path("query/set")
37 Response querySet(@QueryParam("q1") Set<String> set);
38
39 @GET
40 @Path("query/sortedset")
41 Response querySortedSet(@QueryParam("q1") SortedSet<String> set);
42
43 @PUT
44 @Consumes("text/plain")
45 @Path("query/entity")
46 Response queryWithEntity(@QueryParam("q1") List<String> list, String entity);
47
48 @PUT
49 @Consumes("text/plain")
50 @Path("matrix/query/entity")
51 Response matrixQueryWithEntity(@MatrixParam("m1") List<String> matrixParams, @QueryParam("q1") List<String> queryParams, String entity);
52 }
+0
-127
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ParameterListResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.MatrixParam;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.QueryParam;
8 import javax.ws.rs.core.Response;
9 import java.util.ArrayList;
10 import java.util.Collections;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Set;
14 import java.util.SortedSet;
15
16 @Path("/")
17 public class ParameterListResource implements ParameterListInterface {
18 @Override
19 @GET
20 @Path("matrix/list")
21 public Response matrixList(@MatrixParam("m1") List<String> list) {
22 StringBuilder sb = new StringBuilder();
23 for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
24 sb.append(it.next()).append(":");
25 }
26 return Response.ok().entity(sb.toString()).build();
27 }
28
29 @Override
30 @GET
31 @Path("matrix/set")
32 public Response matrixSet(@MatrixParam("m1") Set<String> set) {
33 List<String> list = new ArrayList<String>(set);
34 Collections.sort(list);
35 StringBuilder sb = new StringBuilder();
36 for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
37 sb.append(it.next()).append(":");
38 }
39 return Response.ok().entity(sb.toString()).build();
40 }
41
42 @Override
43 @GET
44 @Path("matrix/sortedset")
45 public Response matrixSortedSet(@MatrixParam("m1") SortedSet<String> set) {
46 StringBuilder sb = new StringBuilder();
47 for (Iterator<String> it = set.iterator(); it.hasNext(); ) {
48 sb.append(it.next()).append(":");
49 }
50 return Response.ok().entity(sb.toString()).build();
51 }
52
53 @Override
54 @PUT
55 @Consumes("text/plain")
56 @Path("matrix/entity")
57 public Response matrixWithEntity(@MatrixParam("m1") List<String> list, String entity) {
58 StringBuilder sb = new StringBuilder(entity + ":");
59 for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
60 sb.append(it.next()).append(":");
61 }
62 return Response.ok().entity(sb.toString()).build();
63 }
64
65 @Override
66 @GET
67 @Path("query/list")
68 public Response queryList(@QueryParam("q1") List<String> list) {
69 StringBuilder sb = new StringBuilder();
70 for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
71 sb.append(it.next()).append(":");
72 }
73 return Response.ok().entity(sb.toString()).build();
74 }
75
76 @Override
77 @GET
78 @Path("query/set")
79 public Response querySet(@QueryParam("q1") Set<String> set) {
80 List<String> list = new ArrayList<String>(set);
81 Collections.sort(list);
82 StringBuilder sb = new StringBuilder();
83 for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
84 sb.append(it.next()).append(":");
85 }
86 return Response.ok().entity(sb.toString()).build();
87 }
88
89 @Override
90 @GET
91 @Path("query/sortedset")
92 public Response querySortedSet(@QueryParam("q1") SortedSet<String> set) {
93 StringBuilder sb = new StringBuilder();
94 for (Iterator<String> it = set.iterator(); it.hasNext(); ) {
95 sb.append(it.next()).append(":");
96 }
97 return Response.ok().entity(sb.toString()).build();
98 }
99
100 @Override
101 @PUT
102 @Consumes("text/plain")
103 @Path("query/entity")
104 public Response queryWithEntity(@QueryParam("q1") List<String> list, String entity) {
105 StringBuilder sb = new StringBuilder(entity + ":");
106 for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
107 sb.append(it.next()).append(":");
108 }
109 return Response.ok().entity(sb.toString()).build();
110 }
111
112 @Override
113 @PUT
114 @Consumes("text/plain")
115 @Path("matrix/query/entity")
116 public Response matrixQueryWithEntity(@MatrixParam("m1") List<String> matrixParams, @QueryParam("q1") List<String> queryParams, String entity) {
117 StringBuilder sb = new StringBuilder(entity + ":");
118 for (Iterator<String> it = matrixParams.iterator(); it.hasNext(); ) {
119 sb.append(it.next()).append(":");
120 }
121 for (Iterator<String> it = queryParams.iterator(); it.hasNext(); ) {
122 sb.append(it.next()).append(":");
123 }
124 return Response.ok().entity(sb.toString()).build();
125 }
126 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/PrimitiveResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.Response;
8
9 @Path("/")
10 @Produces("text/plain")
11 @Consumes("text/plain")
12 public class PrimitiveResource {
13 @POST
14 @Path("int")
15 public int postInt(int val) {
16 return val;
17 }
18
19 @POST
20 @Path("boolean")
21 public boolean postInt(boolean val) {
22 return val;
23 }
24
25 @GET
26 @Path("nothing")
27 public Response nothing() {
28 return Response.ok().build();
29 }
30 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/SmokeParamResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.HeaderParam;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9
10 @Path("/foo")
11 public class SmokeParamResource {
12
13 @POST
14 @Produces("text/plain")
15 @Consumes("text/plain")
16 public String create(String cust) {
17 return cust;
18 }
19
20 @GET
21 @Produces("text/plain")
22 public String get(@HeaderParam("a") String a, @QueryParam("b") String b) {
23 return a + " " + b;
24 }
25
26 }
+0
-45
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/SyncInvokeResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.test.client.SyncInvokeTest;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.DELETE;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.Consumes;
10 import javax.ws.rs.Path;
11
12 @Path("/test")
13 public class SyncInvokeResource {
14 @GET
15 @Produces("text/plain")
16 public String get() {
17 return "get";
18 }
19
20 @PUT
21 @Consumes("text/plain")
22 public String put(String str) {
23 return "put " + str;
24 }
25
26 @POST
27 @Consumes("text/plain")
28 public String post(String str) {
29 return "post " + str;
30 }
31
32 @DELETE
33 @Produces("text/plain")
34 public String delete() {
35 return "delete";
36 }
37
38 @SyncInvokeTest.PATCH
39 @Produces("text/plain")
40 @Consumes("text/plain")
41 public String patch(String str) {
42 return "patch " + str;
43 }
44 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/TimeoutResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.resteasy.test.client.TimeoutTest;
3
4 import javax.ws.rs.QueryParam;
5
6 public class TimeoutResource implements TimeoutTest.TimeoutResourceInterface {
7 @Override
8 public String get(@QueryParam("sleep") int sleep) throws Exception {
9 Thread.sleep(sleep * 1000);
10 return "OK";
11 }
12 }
+0
-32
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/TraceResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.test.client.TraceTest;
4
5 import javax.ws.rs.Path;
6 import javax.ws.rs.core.Context;
7 import javax.ws.rs.core.Response;
8 import javax.ws.rs.core.UriInfo;
9
10 @Path("resource")
11 public class TraceResource {
12
13 private static Logger logger = Logger.getLogger(TraceResource.class);
14
15 @Context
16 UriInfo uriInfo;
17
18 @TraceTest.TRACE
19 @Path("trace")
20 public String trace() {
21 logger.info("uriInfo.request: " + uriInfo.getRequestUri().toString());
22 return "trace";
23 }
24
25 @TraceTest.TRACE
26 @Path("tracenotok")
27 public Response traceNotOk() {
28 return Response.status(Response.Status.NOT_ACCEPTABLE).build();
29 }
30
31 }
+0
-47
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/WebTargetResource.java less more
0 package org.jboss.resteasy.test.client.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.MatrixParam;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.PathParam;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.QueryParam;
8 import java.util.List;
9
10 @Path("/")
11 public class WebTargetResource {
12 @GET
13 @Path("/users/{username}/{id}")
14 @Produces("text/plain")
15 public String get(@PathParam("username") String username, @PathParam("id") String id) {
16 return "username: " + username + ", " + id;
17 }
18
19 @GET
20 @Path("/users/{username}/{id}/{question}/{question}")
21 @Produces("text/plain")
22 public String getMultiple(@PathParam("username") String username, @PathParam("id") String id, @PathParam("question") String q) {
23 return "username: " + username + ", " + id + ", " + q;
24 }
25
26 @GET
27 @Path("/users/{username}/param/{id}")
28 @Produces("text/plain")
29 public String getParam(@PathParam("username") String username, @PathParam("id") String id, @QueryParam("q") List<String> q, @QueryParam("k") List<String> k) {
30 return "username: " + username + ", " + id + ", q: " + q.toString() + ", k: " + k.toString();
31 }
32
33 @GET
34 @Path("/users/{username}/matrix/{id}")
35 @Produces("text/plain")
36 public String getParamMatrix(@PathParam("username") String username, @PathParam("id") String id, @MatrixParam("m1") List<String> m1, @MatrixParam("m2") List<String> m2) {
37 return "username: " + username + ", " + id + ", m1: " + m1.toString() + ", m2: " + m2.toString();
38 }
39
40 @GET
41 @Path("/users/{username}/matrix/{id}/path")
42 @Produces("text/plain")
43 public String getParamMatrixPath(@PathParam("username") String username, @PathParam("id") String id, @MatrixParam("m1") List<String> m1, @MatrixParam("m2") List<String> m2) {
44 return "username: " + username + ", " + id + ", m1: " + m1.toString() + ", m2: " + m2.toString();
45 }
46 }
+0
-107
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/ResteasyJAXRSImplTest.java less more
0 package org.jboss.resteasy.test.core;
1
2 import javax.ws.rs.client.ClientBuilder;
3 import javax.ws.rs.ext.RuntimeDelegate;
4
5 import org.jboss.arquillian.container.test.api.Deployment;
6 import org.jboss.arquillian.container.test.api.RunAsClient;
7 import org.jboss.arquillian.junit.Arquillian;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.spi.old.ResteasyProviderFactory;
10 import org.jboss.resteasy.test.core.basic.resource.AcceptLanguagesResource;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Assert;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 @RunWith(Arquillian.class)
19 public class ResteasyJAXRSImplTest
20 {
21
22 @Deployment
23 public static Archive<?> deploy()
24 {
25 WebArchive war = TestUtil.prepareArchive(ResteasyJAXRSImplTest.class.getSimpleName());
26 return TestUtil.finishContainerPrepare(war, null, AcceptLanguagesResource.class);
27 }
28
29 @Test
30 @RunAsClient
31 public void testClientBuilder() throws Exception
32 {
33 testClientBuilderNewBuilder();
34 }
35
36 @Test
37 public void testInContainerClientBuilder() throws Exception
38 {
39 testClientBuilderNewBuilder();
40 }
41
42 @Test
43 @RunAsClient
44 public void testRuntimeDelegate() throws Exception
45 {
46 testRuntimeDelegateGetInstance();
47 testResteasyProviderFactoryGetInstance();
48 testResteasyProviderFactoryNewInstance();
49 }
50
51 @Test
52 public void testInContainerRuntimeDegate() throws Exception
53 {
54 testRuntimeDelegateGetInstance();
55 testResteasyProviderFactoryGetInstance();
56 testResteasyProviderFactoryNewInstance();
57 }
58
59 private void testClientBuilderNewBuilder() {
60 ClientBuilder client = ClientBuilder.newBuilder();
61 Assert.assertEquals(ResteasyClientBuilder.class.getName(), client.getClass().getName());
62 }
63
64 private void testRuntimeDelegateGetInstance() {
65 RuntimeDelegate.setInstance(null);
66 RuntimeDelegate rd = RuntimeDelegate.getInstance();
67 Assert.assertEquals(ResteasyProviderFactory.class.getName(), rd.getClass().getName());
68 RuntimeDelegate.setInstance(null);
69 }
70
71 private void testResteasyProviderFactoryGetInstance() {
72 ResteasyProviderFactory.setInstance(null);
73 ResteasyProviderFactory rpf = resteasyProviderFactoryGetInstance();
74 Assert.assertEquals(rpf, ResteasyProviderFactory.getInstance());
75 ResteasyProviderFactory.setInstance(null);
76 ResteasyProviderFactory rpf2 = resteasyProviderFactoryGetInstance();
77 Assert.assertNotEquals(rpf, rpf2);
78 ResteasyProviderFactory.setInstance(null);
79 }
80
81 private void testResteasyProviderFactoryNewInstance() {
82 ResteasyProviderFactory.setInstance(null);
83 ResteasyProviderFactory rpf = resteasyProviderFactoryNewInstance();
84 ResteasyProviderFactory rpf2 = resteasyProviderFactoryNewInstance();
85 ResteasyProviderFactory rpf3 = resteasyProviderFactoryNewInstance();
86 Assert.assertNotEquals(rpf, rpf2);
87 Assert.assertNotEquals(rpf, rpf3);
88 Assert.assertNotEquals(rpf2, rpf3);
89
90 ResteasyProviderFactory rpfGI = resteasyProviderFactoryGetInstance();
91 Assert.assertNotEquals(rpfGI, rpf3);
92 }
93
94 private static ResteasyProviderFactory resteasyProviderFactoryGetInstance() {
95 Object o = org.jboss.resteasy.spi.ResteasyProviderFactory.getInstance();
96 Assert.assertEquals(ResteasyProviderFactory.class, o.getClass());
97 return (ResteasyProviderFactory)o;
98 }
99
100
101 private static ResteasyProviderFactory resteasyProviderFactoryNewInstance() {
102 Object o = org.jboss.resteasy.spi.ResteasyProviderFactory.newInstance();
103 Assert.assertEquals(ResteasyProviderFactory.class, o.getClass());
104 return (ResteasyProviderFactory)o;
105 }
106 }
+0
-52
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/AcceptLanguagesTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.core.basic.resource.AcceptLanguagesResource;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.PortProviderUtil;
8 import org.jboss.resteasy.utils.TestUtil;
9 import org.jboss.shrinkwrap.api.Archive;
10 import org.jboss.shrinkwrap.api.spec.WebArchive;
11 import org.junit.Assert;
12 import org.junit.Test;
13 import org.junit.runner.RunWith;
14
15 import javax.ws.rs.client.Client;
16 import javax.ws.rs.client.ClientBuilder;
17 import javax.ws.rs.client.WebTarget;
18 import javax.ws.rs.core.Response;
19
20 /**
21 * @tpSubChapter Localization
22 * @tpChapter Integration tests
23 * @tpSince RESTEasy 3.0.16
24 */
25 @RunWith(Arquillian.class)
26 @RunAsClient
27 public class AcceptLanguagesTest {
28
29 @Deployment
30 public static Archive<?> deploy() {
31 WebArchive war = TestUtil.prepareArchive(AcceptLanguagesTest.class.getSimpleName());
32 return TestUtil.finishContainerPrepare(war, null, AcceptLanguagesResource.class);
33 }
34
35 /**
36 * @tpTestDetails Check some languages for accepting
37 * @tpSince RESTEasy 3.0.16
38 */
39 @Test
40 public void testLanguages() throws Exception {
41 Client client = ClientBuilder.newClient();
42 WebTarget base = client.target(PortProviderUtil.generateURL("/lang", AcceptLanguagesTest.class.getSimpleName()));
43 Response response = base.request().header("Accept-Language", "en-US;q=0,en;q=0.8,de-AT,de;q=0.9").get();
44
45 Assert.assertEquals(response.getStatus(), HttpResponseCodes.SC_OK);
46
47 response.close();
48 client.close();
49 }
50
51 }
+0
-80
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/AnnotationInheritanceTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.basic.resource.AnnotationInheritanceNotAResource;
8 import org.jboss.resteasy.test.core.basic.resource.AnnotationInheritanceSomeOtherInterface;
9 import org.jboss.resteasy.test.core.basic.resource.AnnotationInheritanceSomeOtherResource;
10 import org.jboss.resteasy.test.core.basic.resource.AnnotationInheritanceSuperInt;
11 import org.jboss.resteasy.test.core.basic.resource.AnnotationInheritanceSuperIntAbstract;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 /**
23 * @tpSubChapter Configuration
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Test for resource without @Path annotation.
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class AnnotationInheritanceTest {
31 static ResteasyClient client;
32
33 @Deployment
34 public static Archive<?> deploySimpleResource() {
35 WebArchive war = TestUtil.prepareArchive(AnnotationInheritanceTest.class.getSimpleName());
36 war.addClasses(AnnotationInheritanceSuperInt.class, AnnotationInheritanceSuperIntAbstract.class,
37 AnnotationInheritanceNotAResource.class, AnnotationInheritanceSomeOtherInterface.class);
38 return TestUtil.finishContainerPrepare(war, null, AnnotationInheritanceSomeOtherResource.class);
39 }
40
41 @Before
42 public void init() {
43 client = new ResteasyClientBuilder().build();
44 }
45
46 @After
47 public void after() throws Exception {
48 client.close();
49 }
50
51 private String generateURL(String path) {
52 return PortProviderUtil.generateURL(path, AnnotationInheritanceTest.class.getSimpleName());
53 }
54
55 /**
56 * @tpTestDetails Test basic functionality of test resource
57 * @tpSince RESTEasy 3.0.16
58 */
59 @Test
60 public void testSuperclassInterfaceAnnotation() {
61 AnnotationInheritanceSomeOtherInterface proxy = client.target(generateURL("/somewhere")).proxy(AnnotationInheritanceSomeOtherInterface.class);
62 Assert.assertEquals("Foo: Fred", proxy.getSuperInt().getFoo());
63 }
64
65 /**
66 * @tpTestDetails Check wrong resource without @Path annotation
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void testDetectionOfNonResource() {
71 try {
72 AnnotationInheritanceSomeOtherInterface proxy = client.target(generateURL("/somewhere")).proxy(AnnotationInheritanceSomeOtherInterface.class);
73 proxy.getFailure().blah();
74 Assert.fail();
75 } catch (Exception e) {
76 // exception thrown
77 }
78 }
79 }
+0
-79
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/AppConfigTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.apache.http.client.methods.CloseableHttpResponse;
3 import org.apache.http.client.methods.HttpGet;
4 import org.apache.http.impl.client.CloseableHttpClient;
5 import org.apache.http.impl.client.HttpClients;
6 import org.jboss.arquillian.container.test.api.Deployment;
7 import org.jboss.arquillian.container.test.api.RunAsClient;
8 import org.jboss.arquillian.junit.Arquillian;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
10 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
11 import org.jboss.resteasy.test.core.basic.resource.AppConfigApplication;
12 import org.jboss.resteasy.test.core.basic.resource.AppConfigResources;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.ShrinkWrap;
18 import org.jboss.shrinkwrap.api.spec.WebArchive;
19 import org.junit.After;
20 import org.junit.Assert;
21 import org.junit.Before;
22 import org.junit.Test;
23 import org.junit.runner.RunWith;
24
25
26 /**
27 * @tpSubChapter Configuration
28 * @tpChapter Integration tests
29 * @tpTestCaseDetails Test for resource and provider defined in one class together.
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class AppConfigTest {
35
36 private static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploySimpleResource() {
40 WebArchive war = ShrinkWrap.create(WebArchive.class, AppConfigTest.class.getSimpleName() + ".war");
41 war.addClass(AppConfigResources.class);
42 war.addClass(AppConfigApplication.class);
43 war.addAsWebInfResource(AppConfigTest.class.getPackage(), "AppConfigWeb.xml", "web.xml");
44 return war;
45 }
46
47 private String generateURL(String path) {
48 return PortProviderUtil.generateURL(path, AppConfigTest.class.getSimpleName());
49 }
50
51 @Before
52 public void setup() {
53 client = new ResteasyClientBuilder().build();
54 }
55
56 @After
57 public void after() throws Exception {
58 client.close();
59 }
60
61 /**
62 * @tpTestDetails Test for apache client
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void apacheClient() throws Exception {
67 CloseableHttpClient httpclient = HttpClients.createDefault();
68 HttpGet httpGet = new HttpGet(generateURL("/my"));
69 CloseableHttpResponse response1 = httpclient.execute(httpGet);
70
71 try {
72 Assert.assertEquals(HttpResponseCodes.SC_OK, response1.getStatusLine().getStatusCode());
73 Assert.assertEquals("\"hello\"", TestUtil.readString(response1.getEntity().getContent()));
74 } finally {
75 response1.close();
76 }
77 }
78 }
+0
-105
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/ApplicationConfigTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.core.basic.resource.ApplicationConfig;
6 import org.jboss.resteasy.test.core.basic.resource.ApplicationConfigInjectionResource;
7 import org.jboss.resteasy.test.core.basic.resource.ApplicationConfigInterface;
8 import org.jboss.resteasy.test.core.basic.resource.ApplicationConfigQuotedTextWriter;
9 import org.jboss.resteasy.test.core.basic.resource.ApplicationConfigResource;
10 import org.jboss.resteasy.test.core.basic.resource.ApplicationConfigService;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.ShrinkWrap;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.AfterClass;
17 import org.junit.Assert;
18 import org.junit.BeforeClass;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Client;
23 import javax.ws.rs.client.ClientBuilder;
24 import javax.ws.rs.core.Response;
25
26 /**
27 * @tpSubChapter Configuration
28 * @tpChapter Integration tests
29 * @tpTestCaseDetails Test for custom Application class
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class ApplicationConfigTest {
35
36 static Client client;
37
38 @Deployment
39 public static Archive<?> deploySimpleResource() {
40 WebArchive war = ShrinkWrap.create(WebArchive.class, ApplicationConfigTest.class.getSimpleName() + ".war");
41 war.addClasses(ApplicationConfig.class, ApplicationConfigInjectionResource.class, ApplicationConfigInterface.class,
42 ApplicationConfigQuotedTextWriter.class, ApplicationConfigResource.class,
43 ApplicationConfigService.class);
44 return war;
45 }
46
47 @BeforeClass
48 public static void init() {
49 client = ClientBuilder.newClient();
50 }
51
52 @AfterClass
53 public static void after() throws Exception {
54 client.close();
55 }
56
57 private String generateURL(String path) {
58 return PortProviderUtil.generateURL(path, ApplicationConfigTest.class.getSimpleName());
59 }
60
61 private void basicTest(String uri, String body) {
62 Response response = client.target(uri).request().get();
63 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
64 response.close();
65 }
66
67 /**
68 * @tpTestDetails Test base resource
69 * @tpSince RESTEasy 3.0.16
70 */
71 @Test
72 public void testIt() {
73 basicTest(generateURL("/my"), "\"hello\"");
74 basicTest(generateURL("/myinterface"), "hello");
75 }
76
77 /**
78 * @tpTestDetails Injection test
79 * @tpSince RESTEasy 3.0.16
80 */
81 @Test
82 public void testFieldInjection() {
83 basicTest(generateURL("/injection/field"), "true");
84 }
85
86 /**
87 * @tpTestDetails Setter injection test
88 * @tpSince RESTEasy 3.0.16
89 */
90 @Test
91 public void testSetterInjection() {
92 basicTest(generateURL("/injection/setter"), "true");
93 }
94
95 /**
96 * @tpTestDetails Setter injection test
97 * @tpSince RESTEasy 3.0.16
98 */
99 @Test
100 public void testConstructorInjection() {
101 basicTest(generateURL("/injection/constructor"), "true");
102 }
103
104 }
+0
-178
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/ApplicationFilterTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.basic.resource.ApplicationFilterCustomer;
8 import org.jboss.resteasy.test.core.basic.resource.ApplicationFilterCustomerResource;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.asset.UrlAsset;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.Entity;
22 import javax.ws.rs.core.Response;
23 import java.io.BufferedReader;
24 import java.io.InputStreamReader;
25 import java.io.OutputStream;
26 import java.net.HttpURLConnection;
27 import java.net.URL;
28 import java.util.ArrayList;
29 import java.util.List;
30
31 /**
32 * @tpSubChapter Configuration
33 * @tpChapter Integration tests
34 * @tpTestCaseDetails Regression test for RESTEASY-541
35 * @tpSince RESTEasy 3.0.16
36 */
37 @RunWith(Arquillian.class)
38 @RunAsClient
39 public class ApplicationFilterTest {
40
41 private static ResteasyClient client;
42
43 @Deployment
44 public static Archive<?> deploySimpleResource() {
45 WebArchive war = TestUtil.prepareArchive(ApplicationFilterTest.class.getSimpleName());
46 war.addAsWebInfResource(ApplicationFilterTest.class.getPackage(), "ApplicationFilterWeb.xml", "web.xml");
47 war.addClasses(ApplicationFilterCustomer.class, ApplicationFilterCustomerResource.class);
48 war.add(new UrlAsset(ApplicationFilterTest.class.getResource("ApplicationFilter.html")), "foo.html");
49 List<Class<?>> singletons = new ArrayList<>();
50 singletons.add(ApplicationFilterCustomerResource.class);
51 return TestUtil.finishContainerPrepare(war, null, singletons, (Class<?>[]) null);
52 }
53
54 private String generateURL(String path) {
55 return PortProviderUtil.generateURL(path, ApplicationFilterTest.class.getSimpleName());
56 }
57
58 @Before
59 public void setup() {
60 client = new ResteasyClientBuilder().build();
61 }
62
63 @After
64 public void after() throws Exception {
65 client.close();
66 }
67
68 /**
69 * @tpTestDetails Test for not founded method
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test
73 public void testMethodNotFound() throws Exception {
74 String newCustomer = "<customer>"
75 + "<first-name>Bill</first-name>"
76 + "<last-name>Burke</last-name>"
77 + "<street>256 Clarendon Street</street>"
78 + "<city>Boston</city>"
79 + "<state>MA</state>"
80 + "<zip>02115</zip>"
81 + "<country>USA</country>"
82 + "</customer>";
83 Response response = client.target(generateURL("/customers")).request().put(Entity.entity(newCustomer, "application/xml"));
84 Assert.assertEquals(405, response.getStatus());
85 }
86
87 /**
88 * @tpTestDetails Test for getting html file that is not processed by resteasy
89 * @tpSince RESTEasy 3.0.16
90 */
91 @Test
92 public void testStaticResource() throws Exception {
93 String response = client.target(generateURL("/foo.html")).request().get(String.class);
94 Assert.assertNotNull(response);
95 Assert.assertTrue(response.indexOf("hello world") > -1);
96 }
97
98 /**
99 * @tpTestDetails Test common application usage
100 * @tpSince RESTEasy 3.0.16
101 */
102 @Test
103 public void testCustomerResource() throws Exception {
104 // Create a new customer
105 String newCustomer = "<customer>"
106 + "<first-name>Bill</first-name>"
107 + "<last-name>Burke</last-name>"
108 + "<street>256 Clarendon Street</street>"
109 + "<city>Boston</city>"
110 + "<state>MA</state>"
111 + "<zip>02115</zip>"
112 + "<country>USA</country>"
113 + "</customer>";
114
115 URL postUrl = new URL(generateURL("/customers"));
116 HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
117 connection.setDoOutput(true);
118 connection.setInstanceFollowRedirects(false);
119 connection.setRequestMethod("POST");
120 connection.setRequestProperty("Content-Type", "application/xml");
121 OutputStream os = connection.getOutputStream();
122 os.write(newCustomer.getBytes());
123 os.flush();
124 Assert.assertEquals(HttpResponseCodes.SC_CREATED, connection.getResponseCode());
125 connection.disconnect();
126
127
128 // Get the new customer
129 URL getUrl = new URL(generateURL("/customers/1"));
130 connection = (HttpURLConnection) getUrl.openConnection();
131 connection.setRequestMethod("GET");
132
133 BufferedReader reader = new BufferedReader(new
134 InputStreamReader(connection.getInputStream()));
135
136 String line = reader.readLine();
137 while (line != null) {
138 line = reader.readLine();
139 }
140 Assert.assertEquals(HttpResponseCodes.SC_OK, connection.getResponseCode());
141 connection.disconnect();
142
143 // Update the new customer. Change Bill's name to William
144 String updateCustomer = "<customer>"
145 + "<first-name>William</first-name>"
146 + "<last-name>Burke</last-name>"
147 + "<street>256 Clarendon Street</street>"
148 + "<city>Boston</city>"
149 + "<state>MA</state>"
150 + "<zip>02115</zip>"
151 + "<country>USA</country>"
152 + "</customer>";
153 connection = (HttpURLConnection) getUrl.openConnection();
154 connection.setDoOutput(true);
155 connection.setRequestMethod("PUT");
156 connection.setRequestProperty("Content-Type", "application/xml");
157 os = connection.getOutputStream();
158 os.write(updateCustomer.getBytes());
159 os.flush();
160 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, connection.getResponseCode());
161 connection.disconnect();
162
163 // Show the update
164 connection = (HttpURLConnection) getUrl.openConnection();
165 connection.setRequestMethod("GET");
166
167 reader = new BufferedReader(new
168 InputStreamReader(connection.getInputStream()));
169
170 line = reader.readLine();
171 while (line != null) {
172 line = reader.readLine();
173 }
174 Assert.assertEquals(HttpResponseCodes.SC_OK, connection.getResponseCode());
175 connection.disconnect();
176 }
177 }
+0
-66
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/ApplicationPropertiesConfigPropertyApplicationInjectionTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.core.basic.resource.ApplicationPropertiesConfigPropertyApplicationInjection;
6 import org.jboss.resteasy.test.core.basic.resource.ApplicationPropertiesConfigPropertyApplicationInjectionFeature;
7 import org.jboss.resteasy.test.core.basic.resource.ApplicationPropertiesConfigPropertyApplicationInjectionResource;
8 import org.jboss.shrinkwrap.api.Archive;
9 import org.jboss.shrinkwrap.api.ShrinkWrap;
10 import org.jboss.shrinkwrap.api.spec.WebArchive;
11 import org.junit.AfterClass;
12 import org.junit.Assert;
13 import org.junit.BeforeClass;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16 import org.jboss.resteasy.utils.PortProviderUtil;
17
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.client.WebTarget;
21
22 /**
23 * @tpSubChapter Configuration
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Test for custom Application class with overridden getProperties() method
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class ApplicationPropertiesConfigPropertyApplicationInjectionTest {
31 static Client client;
32
33 @Deployment
34 public static Archive<?> deploySimpleResource() {
35 WebArchive war = ShrinkWrap.create(WebArchive.class, ApplicationPropertiesConfigPropertyApplicationInjectionTest.class.getSimpleName() + ".war");
36 war.addClasses(ApplicationPropertiesConfigPropertyApplicationInjection.class, ApplicationPropertiesConfigPropertyApplicationInjectionResource.class,
37 ApplicationPropertiesConfigPropertyApplicationInjectionFeature.class);
38 return war;
39 }
40
41 @BeforeClass
42 public static void init() {
43 client = ClientBuilder.newClient();
44 }
45
46 @AfterClass
47 public static void after() throws Exception {
48 client.close();
49 }
50
51 private String generateURL(String path) {
52 return PortProviderUtil.generateURL(path, ApplicationPropertiesConfigPropertyApplicationInjectionTest.class.getSimpleName());
53 }
54
55 /**
56 * @tpTestDetails Test for custom Application class with overriden getProperties() method
57 * @tpSince RESTEasy 3.0.16
58 */
59 @Test
60 public void testApplicationPropertiesConfigApplicationInjection() {
61 WebTarget target = client.target(generateURL("/getconfigproperty"));
62 String response = target.queryParam("prop", "Prop1").request().get(String.class);
63 Assert.assertEquals("The property is not found in the deployment", "Value1", response);
64 }
65 }
+0
-72
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/ApplicationPropertiesConfigTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.core.basic.resource.ApplicationPropertiesConfig;
6 import org.jboss.resteasy.test.core.basic.resource.ApplicationPropertiesConfigResource;
7 import org.jboss.shrinkwrap.api.Archive;
8 import org.jboss.shrinkwrap.api.ShrinkWrap;
9 import org.jboss.shrinkwrap.api.spec.WebArchive;
10 import org.junit.AfterClass;
11 import org.junit.Assert;
12 import org.junit.BeforeClass;
13 import org.junit.Test;
14 import org.junit.runner.RunWith;
15 import org.jboss.resteasy.utils.PortProviderUtil;
16
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.client.WebTarget;
20
21 /**
22 * @tpSubChapter Configuration
23 * @tpChapter Integration tests
24 * @tpTestCaseDetails Test for custom Application class with overriden getProperties() method, by injecting Configuration into
25 * the resource.
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class ApplicationPropertiesConfigTest {
31 static Client client;
32
33 @Deployment
34 public static Archive<?> deploySimpleResource() {
35 WebArchive war = ShrinkWrap.create(WebArchive.class, ApplicationPropertiesConfigTest.class.getSimpleName() + ".war");
36 war.addClasses(ApplicationPropertiesConfig.class, ApplicationPropertiesConfigResource.class);
37 return war;
38 }
39
40 @BeforeClass
41 public static void init() {
42 client = ClientBuilder.newClient();
43 }
44
45 @AfterClass
46 public static void after() throws Exception {
47 client.close();
48 }
49
50 private String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, ApplicationPropertiesConfigTest.class.getSimpleName());
52 }
53
54 /**
55 * @tpTestDetails Test for custom Application class with overriden getProperties() method, by injecting Configuration
56 * into the resource.
57 * @tpSince RESTEasy 3.0.16
58 */
59 @Test
60 public void testApplicationPropertiesConfig() {
61 String errorMessage = "The property is not found in the deployment";
62 String response;
63 try {
64 WebTarget target = client.target(generateURL("/getconfigproperty"));
65 response = target.queryParam("prop", "Prop1").request().get(String.class);
66 } catch (Exception e) {
67 throw new RuntimeException(errorMessage, e);
68 }
69 Assert.assertEquals(errorMessage, "Value1", response);
70 }
71 }
+0
-120
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/ApplicationTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.core.basic.resource.ApplicationTestAExplicitApplication;
6 import org.jboss.resteasy.test.core.basic.resource.ApplicationTestBExplicitApplication;
7 import org.jboss.resteasy.test.core.basic.resource.ApplicationTestIgnoredApplication;
8 import org.jboss.resteasy.test.core.basic.resource.ApplicationTestMappedApplication;
9 import org.jboss.resteasy.test.core.basic.resource.ApplicationTestResourceA;
10 import org.jboss.resteasy.test.core.basic.resource.ApplicationTestResourceB;
11 import org.jboss.resteasy.test.core.basic.resource.ApplicationTestScannedApplication;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.ShrinkWrap;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.Assert;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.Client;
22 import javax.ws.rs.client.ClientBuilder;
23 import javax.ws.rs.client.WebTarget;
24 import javax.ws.rs.core.Response;
25
26 /**
27 * @tpSubChapter Configuration
28 * @tpChapter Integration tests
29 * @tpTestCaseDetails Test for usage of more application in one deployment
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class ApplicationTest {
35
36 private static final String CONTENT_ERROR_MESSAGE = "Wrong content of response";
37
38 @Deployment
39 public static Archive<?> deploySimpleResource() {
40 WebArchive war = ShrinkWrap.create(WebArchive.class, ApplicationTest.class.getSimpleName() + ".war");
41 war.addAsWebInfResource(ApplicationTest.class.getPackage(), "ApplicationWeb.xml", "web.xml");
42 war.addClasses(ApplicationTestAExplicitApplication.class,
43 ApplicationTestBExplicitApplication.class,
44 ApplicationTestIgnoredApplication.class,
45 ApplicationTestMappedApplication.class,
46 ApplicationTestResourceA.class,
47 ApplicationTestResourceB.class,
48 ApplicationTestScannedApplication.class);
49 return war;
50 }
51
52 private String generateURL(String path) {
53 return PortProviderUtil.generateURL(path, ApplicationTest.class.getSimpleName());
54 }
55
56 /**
57 * @tpTestDetails Test first application in deployment
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testExplicitA() throws Exception {
62 Client client = ClientBuilder.newClient();
63 WebTarget base = client.target(generateURL("/a/explicit"));
64
65 String value = base.path("resources/a").request().get(String.class);
66 Assert.assertEquals(CONTENT_ERROR_MESSAGE, "a", value);
67
68 Response response = base.path("resources/b").request().get();
69 Assert.assertEquals(HttpResponseCodes.SC_NOT_FOUND, response.getStatus());
70 client.close();
71 }
72
73 /**
74 * @tpTestDetails Test second application in deployment
75 * @tpSince RESTEasy 3.0.16
76 */
77 @Test
78 public void testExplicitB() throws Exception {
79 Client client = ClientBuilder.newClient();
80 WebTarget base = client.target(generateURL("/b/explicit"));
81
82 String value = base.path("resources/b").request().get(String.class);
83 Assert.assertEquals(CONTENT_ERROR_MESSAGE, "b", value);
84
85 Response response = base.path("resources/a").request().get();
86 Assert.assertEquals(HttpResponseCodes.SC_NOT_FOUND, response.getStatus());
87 client.close();
88 }
89
90 /**
91 * @tpTestDetails Test scanned application in deployment: getClasses method is not used.
92 * @tpSince RESTEasy 3.0.16
93 */
94 @Test
95 public void testScanned() throws Exception {
96 Client client = ClientBuilder.newClient();
97 WebTarget base = client.target(generateURL("/scanned"));
98
99 String value = base.path("resources/a").request().get(String.class);
100 Assert.assertEquals(CONTENT_ERROR_MESSAGE, "a", value);
101 value = base.path("resources/b").request().get(String.class);
102 Assert.assertEquals(CONTENT_ERROR_MESSAGE, "b", value);
103 }
104
105 /**
106 * @tpTestDetails Test scanned application in deployment: getClasses method is not used. This application is mapped to different location.
107 * @tpSince RESTEasy 3.0.16
108 */
109 @Test
110 public void testMapped() throws Exception {
111 Client client = ClientBuilder.newClient();
112 WebTarget base = client.target(generateURL("/mapped"));
113
114 String value = base.path("resources/a").request().get(String.class);
115 Assert.assertEquals(CONTENT_ERROR_MESSAGE, "a", value);
116 value = base.path("resources/b").request().get(String.class);
117 Assert.assertEquals(CONTENT_ERROR_MESSAGE, "b", value);
118 }
119 }
+0
-91
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/CacheControlAnnotationTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.basic.resource.CacheControlAnnotationResource;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.After;
13 import org.junit.Assert;
14 import org.junit.Before;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.servlet.http.HttpServletResponse;
19 import javax.ws.rs.client.WebTarget;
20 import javax.ws.rs.core.CacheControl;
21 import javax.ws.rs.core.Response;
22
23 /**
24 * @tpSubChapter Configuration
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Test for org.jboss.resteasy.annotations.cache.Cache class
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class CacheControlAnnotationTest {
32
33 private static ResteasyClient client;
34
35 @Deployment
36 public static Archive<?> deploySimpleResource() {
37 WebArchive war = TestUtil.prepareArchive(CacheControlAnnotationTest.class.getSimpleName());
38 return TestUtil.finishContainerPrepare(war, null, CacheControlAnnotationResource.class);
39 }
40
41 private String generateURL(String path) {
42 return PortProviderUtil.generateURL(path, CacheControlAnnotationTest.class.getSimpleName());
43 }
44
45 @Before
46 public void setup() {
47 client = new ResteasyClientBuilder().build();
48 }
49
50 @After
51 public void after() throws Exception {
52 client.close();
53 }
54
55 /**
56 * @tpTestDetails Test for correct value of max-age of cache annotation
57 * @tpSince RESTEasy 3.0.16
58 */
59 @Test
60 public void testResourceValid() {
61 WebTarget base = client.target(generateURL("/maxage"));
62 Response response = base.request().get();
63
64 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
65 CacheControl cc = CacheControl.valueOf(response.getHeaderString("cache-control"));
66 Assert.assertFalse("Cache should not be private", cc.isPrivate());
67 Assert.assertEquals("Wrong age of cache", 3600, cc.getMaxAge());
68
69 response.close();
70 }
71
72 /**
73 * @tpTestDetails Test for no-cache settings
74 * @tpSince RESTEasy 3.0.16
75 */
76 @Test
77 public void testResourceNoCach() {
78 WebTarget base = client.target(generateURL("/nocache"));
79 Response response = base.request().get();
80
81 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
82 String value = response.getHeaderString("cache-control");
83 Assert.assertEquals("Wrong value of cache header", "no-cache", value);
84 CacheControl cc = CacheControl.valueOf(value);
85 Assert.assertTrue("Wrong value of cache header", cc.isNoCache());
86
87 response.close();
88 }
89
90 }
+0
-145
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/ContextTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.basic.resource.ContextAfterEncoderInterceptor;
8 import org.jboss.resteasy.test.core.basic.resource.ContextBeforeEncoderInterceptor;
9 import org.jboss.resteasy.test.core.basic.resource.ContextEncoderInterceptor;
10 import org.jboss.resteasy.test.core.basic.resource.ContextEndInterceptor;
11 import org.jboss.resteasy.test.core.basic.resource.ContextService;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.ShrinkWrap;
16 import org.jboss.shrinkwrap.api.asset.StringAsset;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Resteasy-client
27 * @tpChapter Client tests
28 * @tpSince RESTEasy 3.0.16
29 * @tpTestCaseDetails Regression for RESTEASY-699
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class ContextTest {
34 public static final String WRONG_RESPONSE_ERROR_MSG = "Wrong content of response";
35
36 private static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = ShrinkWrap.create(WebArchive.class, ContextTest.class.getSimpleName() + ".war");
41 war.addClasses(ContextAfterEncoderInterceptor.class, ContextBeforeEncoderInterceptor.class, ContextService.class,
42 ContextEncoderInterceptor.class, ContextEndInterceptor.class);
43 war.addAsWebInfResource(ContextTest.class.getPackage(), "ContextIndex.html", "index.html");
44 war.addAsWebInfResource(ContextTest.class.getPackage(), "ContextWeb.xml", "web.xml");
45 return war;
46 }
47
48 private String generateURL(String path) {
49 return PortProviderUtil.generateURL(path, ContextTest.class.getSimpleName());
50 }
51
52 @Before
53 public void setup() {
54 client = new ResteasyClientBuilder().build();
55 }
56
57 @After
58 public void after() throws Exception {
59 client.close();
60 }
61
62 /**
63 * @tpTestDetails Test for forwarding request to external HTML file
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testForward() throws Exception {
68 Response response = client.target(generateURL("/test/forward")).request().get();
69 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
70 Assert.assertEquals("Wrong content of response", "hello world", response.readEntity(String.class));
71 response.close();
72 }
73
74 /**
75 * @tpTestDetails Base URL should not be affected by URL parameter
76 * @tpSince RESTEasy 3.0.16
77 */
78 @Test
79 public void testRepeat() throws Exception {
80 Response response = client.target(generateURL("/test/test")).request().get();
81 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
82 Assert.assertEquals("Resource get wrong injected URL", generateURL("/test/"), response.readEntity(String.class));
83 response.close();
84 response = client.target(generateURL("/test/")).request().get();
85 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
86 Assert.assertEquals("Resource get wrong injected URL", generateURL("/test/"), response.readEntity(String.class));
87 response.close();
88 }
89
90 /**
91 * @tpTestDetails Test for getting servlet context in REST resource
92 * @tpSince RESTEasy 3.0.16
93 */
94 @Test
95 public void testServletContext() throws Exception {
96 final String HEADER_ERROR_MESSAGE = "Response don't have correct headers";
97 Response response = client.target(generateURL("/test/test/servletcontext")).request().get();
98 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
99 Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "ok", response.readEntity(String.class));
100 Assert.assertNotNull(HEADER_ERROR_MESSAGE, response.getHeaderString("before-encoder"));
101 Assert.assertNotNull(HEADER_ERROR_MESSAGE, response.getHeaderString("after-encoder"));
102 Assert.assertNotNull(HEADER_ERROR_MESSAGE, response.getHeaderString("end"));
103 Assert.assertNotNull(HEADER_ERROR_MESSAGE, response.getHeaderString("encoder"));
104 response.close();
105 }
106
107 /**
108 * @tpTestDetails Test for getting servlet config in REST resource
109 * @tpSince RESTEasy 3.0.16
110 */
111 @Test
112 public void testServletConfig() throws Exception {
113 Response response = client.target(generateURL("/test/test/servletconfig")).request().get();
114 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
115 Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "ok", response.readEntity(String.class));
116 response.close();
117 }
118
119 /**
120 * @tpTestDetails XML extension mapping test
121 * @tpSince RESTEasy 3.0.16
122 */
123 @Test
124 public void testXmlMappings() throws Exception {
125 Response response = client.target(generateURL("/test/stuff.xml")).request().get();
126 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
127 Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "xml", response.readEntity(String.class));
128 response.close();
129
130 }
131
132 /**
133 * @tpTestDetails Json extension mapping test
134 * @tpSince RESTEasy 3.0.16
135 */
136 @Test
137 public void testJsonMappings() throws Exception {
138 Response response = client.target(generateURL("/test/stuff.json")).request().get();
139 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
140 Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "json", response.readEntity(String.class));
141 response.close();
142 }
143 }
144
+0
-58
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/DuplicateDeploymentTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import java.io.IOException;
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import org.jboss.arquillian.container.test.api.Deployment;
7 import org.jboss.arquillian.container.test.api.RunAsClient;
8 import org.jboss.arquillian.junit.Arquillian;
9 import org.jboss.resteasy.category.NotForForwardCompatibility;
10 import org.jboss.resteasy.test.core.basic.resource.DuplicateDeploymentReader;
11 import org.jboss.resteasy.test.core.basic.resource.DuplicateDeploymentResource;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17
18 import org.junit.experimental.categories.Category;
19 import org.junit.runner.RunWith;
20
21 /**
22 * @tpSubChapter Response
23 * @tpChapter Integration tests
24 * @tpSince RESTEasy 3.0.17
25 * @tpTestCaseDetails Regression test for JBEAP-4697
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class DuplicateDeploymentTest {
30 private static int initWarningCount = 0;
31
32 private static int getWarningCount() {
33 return TestUtil.getWarningCount("RESTEASY002172", false);
34 }
35
36 @Deployment
37 public static Archive<?> deploy() {
38 initWarningCount = getWarningCount();
39 WebArchive war = TestUtil.prepareArchive(DuplicateDeploymentTest.class.getSimpleName());
40
41 List<Class<?>> singletons = new ArrayList<>();
42 singletons.add(DuplicateDeploymentResource.class);
43 singletons.add(DuplicateDeploymentReader.class);
44
45 return TestUtil.finishContainerPrepare(war, null, singletons, DuplicateDeploymentResource.class, DuplicateDeploymentReader.class);
46 }
47
48 /**
49 * @tpTestDetails Check number of warning messages: Singleton resource object class "Resource" already deployed. Singleton ignored.
50 * @tpSince RESTEasy 3.0.17
51 */
52 @Test
53 @Category({NotForForwardCompatibility.class})
54 public void testDeploy() throws IOException {
55 Assert.assertEquals("Wrong count of warning messages in logs", 2, getWarningCount() - initWarningCount);
56 }
57 }
+0
-84
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/FileExtensionMappingTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import javax.ws.rs.client.Client;
3 import javax.ws.rs.client.ClientBuilder;
4 import javax.ws.rs.core.Response;
5
6 import org.jboss.arquillian.container.test.api.Deployment;
7 import org.jboss.arquillian.container.test.api.RunAsClient;
8 import org.jboss.arquillian.junit.Arquillian;
9 import org.jboss.resteasy.test.core.basic.resource.FileExtensionMappingApplication;
10 import org.jboss.resteasy.test.core.basic.resource.FileExtensionMappingResource;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.AfterClass;
16 import org.junit.Assert;
17 import org.junit.BeforeClass;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 /**
22 * @tpSubChapter MediaType
23 * @tpChapter Integration tests
24 * @tpTestCaseDetails Mapping file extensions to media types
25 * @tpSince RESTEasy 3.0.20
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class FileExtensionMappingTest
30 {
31 static Client client;
32
33 @BeforeClass
34 public static void setup() {
35 client = ClientBuilder.newClient();
36 }
37
38 @AfterClass
39 public static void close() {
40 client.close();
41 }
42
43 @Deployment
44 public static Archive<?> deploy() {
45 WebArchive war = TestUtil.prepareArchive(FileExtensionMappingTest.class.getSimpleName());
46 war.addClass(FileExtensionMappingApplication.class);
47 war.addAsWebInfResource(FileExtensionMappingTest.class.getPackage(), "FileExtensionMapping.xml", "web.xml");
48 Archive<?> archive = TestUtil.finishContainerPrepare(war, null, FileExtensionMappingResource.class);
49 System.out.println(archive.toString(true));
50 return archive;
51 }
52
53 private String generateURL(String path) {
54 return PortProviderUtil.generateURL(path, FileExtensionMappingTest.class.getSimpleName());
55 }
56
57 /**
58 * @tpTestDetails Map suffix .txt to Accept: text/plain
59 * @tpSince RESTEasy 3.0.20
60 */
61 @Test
62 public void testFileExtensionMappingPlain() throws Exception {
63 System.out.println("url: " + client.target(generateURL("/test.txt")).queryParam("query", "whosOnFirst").getUri());
64 Response response = client.target(generateURL("/test.txt")).queryParam("query", "whosOnFirst").request().get();
65 String entity = response.readEntity(String.class);
66 Assert.assertEquals(200, response.getStatus());
67 Assert.assertEquals("plain: whosOnFirst", entity);
68 }
69
70 /**
71 * @tpTestDetails Map suffix .html to Accept: text/html
72 * @tpSince RESTEasy 3.0.20
73 */
74 @Test
75 public void testFileExtensionMappingHtml() throws Exception
76 {
77 System.out.println("url: " + client.target(generateURL("/test.html")).queryParam("query", "whosOnFirst").getUri());
78 Response response = client.target(generateURL("/test.html")).queryParam("query", "whosOnFirst").request().get();
79 String entity = response.readEntity(String.class);
80 Assert.assertEquals(200, response.getStatus());
81 Assert.assertEquals("html: whosOnFirst", entity);
82 }
83 }
+0
-161
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/InternalDispatcherTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.logging.Logger;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.basic.resource.InternalDispatcherForwardingResource;
8 import org.jboss.resteasy.test.core.basic.resource.InternalDispatcherClient;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestApplication;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.core.Response;
21
22 import java.util.ArrayList;
23 import java.util.Iterator;
24 import java.util.List;
25
26 /**
27 * @tpSubChapter Core
28 * @tpChapter Integration tests
29 * @tpSince RESTEasy 3.0.16
30 * @tpTestCaseDetails Test for InternalDispatcher
31 */
32 @RunWith(Arquillian.class)
33 public class InternalDispatcherTest {
34 private static Logger logger = Logger.getLogger(InternalDispatcherTest.class);
35
36 private static InternalDispatcherForwardingResource forwardingResource;
37 private static ResteasyClient client;
38 public static final String PATH = "/foo/bar";
39
40 @Deployment
41 public static Archive<?> deploy() {
42
43 WebArchive war = TestUtil.prepareArchive(InternalDispatcherTest.class.getSimpleName());
44 war.addClasses(InternalDispatcherClient.class, InternalDispatcherForwardingResource.class);
45 war.addClasses(TestUtil.class, PortProviderUtil.class);
46
47 List<Class<?>> singletons = new ArrayList<>();
48 singletons.add(InternalDispatcherForwardingResource.class);
49
50 return TestUtil.finishContainerPrepare(war, null, singletons, (Class<?>[]) null);
51 }
52
53 private String generateBaseUrl() {
54 return PortProviderUtil.generateBaseUrl(InternalDispatcherTest.class.getSimpleName());
55 }
56
57 @Before
58 public void setup() {
59 client = new ResteasyClientBuilder().build();
60
61 Assert.assertTrue("No singleton founded", TestApplication.singletons.iterator().hasNext());
62 Object objectResource = TestApplication.singletons.iterator().next();
63 Assert.assertTrue("Wrong type of singleton founded", objectResource instanceof InternalDispatcherForwardingResource);
64 forwardingResource = (InternalDispatcherForwardingResource) objectResource;
65 forwardingResource.uriStack.clear();
66 }
67
68 @After
69 public void after() throws Exception {
70 client.close();
71 }
72
73 /**
74 * @tpTestDetails Check response of forwarded reuests.
75 * @tpSince RESTEasy 3.0.16
76 */
77 @Test
78 public void testClientResponse() throws Exception {
79 InternalDispatcherClient proxy = client.target(generateBaseUrl()).proxy(InternalDispatcherClient.class);
80
81 Assert.assertEquals("Wrong response", "basic", proxy.getBasic());
82 Assert.assertEquals("Wrong response", "basic", proxy.getForwardBasic());
83 Assert.assertEquals("Wrong response", "object1", proxy.getObject(1).readEntity(String.class));
84 Assert.assertEquals("Wrong response", "object1", proxy.getForwardedObject(1).readEntity(String.class));
85 Response cr = proxy.getObject(0);
86 Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus());
87 cr.close();
88 cr = proxy.getForwardedObject(0);
89 Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus());
90 cr.close();
91
92 proxy.putForwardBasic("testBasic");
93 Assert.assertEquals("Wrong response", "testBasic", proxy.getBasic());
94 proxy.postForwardBasic("testBasic1");
95 Assert.assertEquals("Wrong response", "testBasic1", proxy.getBasic());
96 proxy.deleteForwardBasic();
97 Assert.assertEquals("Wrong response", "basic", proxy.getBasic());
98
99 }
100
101 /**
102 * @tpTestDetails assert that even though there were infinite forwards, there still was
103 * only 1 level of "context" data and that clean up occurred correctly.
104 * This should not spin forever, since RESTEasy stops the recursive loop
105 * after 20 internal dispatches
106 * @tpSince RESTEasy 3.0.16
107 */
108 @Test
109 public void testInfinitForward() {
110 InternalDispatcherClient proxy = client.target(generateBaseUrl()).proxy(InternalDispatcherClient.class);
111 Assert.assertEquals("Cleanup was not correctly performed", 1, proxy.infiniteForward());
112 }
113
114 /**
115 * @tpTestDetails Check UriInfo information without forwarding
116 * @tpSince RESTEasy 3.0.16
117 */
118 @Test
119 public void testUriInfoBasic() {
120 InternalDispatcherClient proxy = client.target(generateBaseUrl()).proxy(InternalDispatcherClient.class);
121 proxy.getBasic();
122 Assert.assertEquals("Wrong UriInfo information without forwarding", generateBaseUrl() + "/basic", forwardingResource.uriStack.pop());
123 Assert.assertTrue("Wrong UriInfo information without forwarding", forwardingResource.uriStack.isEmpty());
124
125 }
126
127 /**
128 * @tpTestDetails Check UriInfo information with forwarding. This is also regression test for JBEAP-2476
129 * @tpSince RESTEasy 3.0.16
130 */
131 @Test
132 public void testUriInfoForwardBasic() throws Exception {
133 InternalDispatcherClient proxy = client.target(generateBaseUrl()).proxy(InternalDispatcherClient.class);
134
135 logger.info("return value: " + proxy.getForwardBasic());
136 int i = 0;
137 for (Iterator<String> it = forwardingResource.uriStack.iterator(); it.hasNext(); i++) {
138 logger.info(String.format("%d. item in uriStack: %s", i, it.next()));
139 }
140
141 Assert.assertEquals("Wrong first URI in stack", generateBaseUrl() + "/basic", forwardingResource.uriStack.pop());
142 Assert.assertEquals("Wrong second URI in stack", generateBaseUrl() + "/forward/basic", forwardingResource.uriStack.pop());
143 Assert.assertTrue("Only two uri should be in stack", forwardingResource.uriStack.isEmpty());
144 }
145
146 /**
147 * @tpTestDetails Regression test for JBEAP-2476
148 * @tpSince RESTEasy 3.0.16
149 */
150 @Test
151 public void testUriInfoForwardBasicComplexUri() {
152 String baseUrl = generateBaseUrl();
153 InternalDispatcherClient proxy = client.target(generateBaseUrl()).proxy(InternalDispatcherClient.class);
154
155 proxy.getComplexForwardBasic();
156 Assert.assertEquals("Wrong first URI in stack", baseUrl + PATH + "/basic", forwardingResource.uriStack.pop());
157 Assert.assertEquals("Wrong second URI in stack", baseUrl + PATH + "/forward/basic", forwardingResource.uriStack.pop());
158 Assert.assertTrue("Only two uri should be in stack", forwardingResource.uriStack.isEmpty());
159 }
160 }
+0
-89
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/InvalidMediaTypeTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.core.basic.resource.InvalidMediaTypeResource;
10 import org.jboss.resteasy.util.HttpResponseCodes;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Invocation;
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Resteasy-client
24 * @tpChapter Client tests
25 * @tpSince RESTEasy 3.0.16
26 * @tpTestCaseDetails Regression for RESTEASY-699
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class InvalidMediaTypeTest {
31
32 protected static final Logger logger = LogManager.getLogger(InvalidMediaTypeTest.class.getName());
33
34 @Deployment
35 public static Archive<?> deploy() {
36 WebArchive war = TestUtil.prepareArchive(InvalidMediaTypeTest.class.getSimpleName());
37 return TestUtil.finishContainerPrepare(war, null, InvalidMediaTypeResource.class);
38 }
39
40 private String generateURL(String path) {
41 return PortProviderUtil.generateURL(path, InvalidMediaTypeTest.class.getSimpleName());
42 }
43
44 /**
45 * @tpTestDetails Check various wrong media type
46 * @tpSince RESTEasy 3.0.16
47 */
48 @Test
49 public void testInvalidMediaTypes() throws Exception {
50 ResteasyClient client = new ResteasyClientBuilder().build();
51 Invocation.Builder request = client.target(generateURL("/test")).request();
52
53 // Missing type or subtype
54 doTest(request, "/");
55 doTest(request, "/*");
56 doTest(request, "*/");
57 doTest(request, "text/");
58 doTest(request, "/plain");
59
60 // Illegal white space
61 doTest(request, " /*");
62 doTest(request, "/* ");
63 doTest(request, " /* ");
64 doTest(request, "/ *");
65 doTest(request, "* /");
66 doTest(request, " / *");
67 doTest(request, "* / ");
68 doTest(request, "* / *");
69 doTest(request, " * / *");
70 doTest(request, "* / * ");
71 doTest(request, "text/ plain");
72 doTest(request, "text /plain");
73 doTest(request, " text/plain");
74 doTest(request, "text/plain ");
75 doTest(request, " text/plain ");
76 doTest(request, " text / plain ");
77 client.close();
78 }
79
80 private void doTest(Invocation.Builder request, String mediaType) {
81 request.accept(mediaType);
82 Response response = request.get();
83 logger.info("mediaType: " + mediaType + "");
84 logger.info("status: " + response.getStatus());
85 Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus());
86 response.close();
87 }
88 }
+0
-50
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/PrivateConstructorTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.basic.resource.PrivateConstructorServiceResource;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.Assert;
13 import org.junit.Test;
14 import org.junit.runner.RunWith;
15
16 import javax.ws.rs.client.WebTarget;
17 import javax.ws.rs.core.Response;
18
19
20 /**
21 * @tpSubChapter Constructors
22 * @tpChapter Integration tests
23 * @tpTestCaseDetails Regression test for RESTEASY-489
24 * @tpSince RESTEasy 3.0.16
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class PrivateConstructorTest {
29
30 @Deployment
31 public static Archive<?> deploySimpleResource() {
32 WebArchive war = TestUtil.prepareArchive(PrivateConstructorTest.class.getSimpleName());
33 return TestUtil.finishContainerPrepare(war, null, PrivateConstructorServiceResource.class);
34 }
35
36 /**
37 * @tpTestDetails Exception should not be thrown on WS with a non-public constructor
38 * @tpSince RESTEasy 3.0.16
39 */
40 @Test
41 public void testMapper() throws Exception {
42 ResteasyClient client = new ResteasyClientBuilder().build();
43 WebTarget base = client.target(PortProviderUtil.generateURL("/test", PrivateConstructorTest.class.getSimpleName()));
44 Response response = base.request().get();
45 Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
46 response.close();
47 client.close();
48 }
49 }
+0
-78
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/ProviderInjectionTest.java less more
0 package org.jboss.resteasy.test.core.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.basic.resource.ProviderInjectionSimpleMessageBodyWriter;
8 import org.jboss.resteasy.test.core.basic.resource.ProviderInjectionSimpleResource;
9 import org.jboss.resteasy.test.core.basic.resource.ProviderInjectionSimpleResourceImpl;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Before;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertTrue;
21
22 /**
23 * @tpSubChapter Providers
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails This test verifies that Providers instance can be injected into a Provider
26 * using constructor or field injection.
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class ProviderInjectionTest {
32 static ResteasyClient client;
33
34 @Deployment
35 public static Archive<?> deploySimpleResource() {
36 WebArchive war = TestUtil.prepareArchive(ProviderInjectionTest.class.getSimpleName());
37 war.addClass(ProviderInjectionSimpleResource.class);
38 war.addClass(PortProviderUtil.class);
39 return TestUtil.finishContainerPrepare(war, null, ProviderInjectionSimpleMessageBodyWriter.class, ProviderInjectionSimpleResourceImpl.class);
40 }
41
42 @Before
43 public void setUp() throws Exception {
44 // do a request (force provider instantiation if providers were created lazily)
45 client = new ResteasyClientBuilder().build();
46 ProviderInjectionSimpleResource proxy = client.target(PortProviderUtil.generateBaseUrl(ProviderInjectionTest.class.getSimpleName())).proxyBuilder(ProviderInjectionSimpleResource.class).build();
47 assertEquals(proxy.foo(), "bar");
48 }
49
50 @After
51 public void after() throws Exception {
52 client.close();
53 }
54
55 /**
56 * @tpTestDetails Getting constructor
57 * @tpSince RESTEasy 3.0.16
58 */
59 @Test
60 public void testConstructorInjection() {
61 for (ProviderInjectionSimpleMessageBodyWriter writer : ProviderInjectionSimpleMessageBodyWriter.getInstances()) {
62 assertTrue(writer.getConstructorProviders() != null);
63 }
64 }
65
66 /**
67 * @tpTestDetails Getting field
68 * @tpSince RESTEasy 3.0.16
69 */
70 @Test
71 public void testFieldInjection() {
72 for (ProviderInjectionSimpleMessageBodyWriter writer : ProviderInjectionSimpleMessageBodyWriter.getInstances()) {
73 assertTrue(writer.getFieldProviders() != null);
74 }
75 }
76
77 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/AcceptLanguagesResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.HttpHeaders;
10 import java.util.List;
11 import java.util.Locale;
12
13 @Path("/lang")
14 public class AcceptLanguagesResource {
15
16 private static Logger logger = Logger.getLogger(AcceptLanguagesResource.class);
17
18 @GET
19 @Produces("text/plain")
20 public String get(@Context HttpHeaders headers) {
21 // en-US;q=0,en;q=0.8,de-AT,de;q=0.9
22 List<Locale> accepts = headers.getAcceptableLanguages();
23
24 StringBuilder locales = new StringBuilder("Locales for accepting: ");
25 for (Locale locale : accepts) {
26 locales.append(locale);
27 locales.append(", ");
28 }
29 logger.info(locales.toString());
30
31 Assert.assertEquals(accepts.get(0).toString(), "de_AT");
32 Assert.assertEquals(accepts.get(1).toString(), "de");
33 Assert.assertEquals(accepts.get(2).toString(), "en");
34 Assert.assertEquals(accepts.get(3).toString(), "en_US");
35
36 return "hello";
37 }
38 }
+0
-6
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/AnnotationInheritanceNotAResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 public interface AnnotationInheritanceNotAResource {
3 // no annotation here!
4 String blah();
5 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/AnnotationInheritanceSomeOtherInterface.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.Path;
3
4 public interface AnnotationInheritanceSomeOtherInterface {
5 @Path("superint")
6 AnnotationInheritanceSuperInt getSuperInt();
7
8 @Path("failure")
9 AnnotationInheritanceNotAResource getFailure();
10 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/AnnotationInheritanceSomeOtherResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("/somewhere")
5 public class AnnotationInheritanceSomeOtherResource implements AnnotationInheritanceSomeOtherInterface {
6 public AnnotationInheritanceSuperInt getSuperInt() {
7 return new AnnotationInheritanceSuperIntAbstract() {
8 @Override
9 protected String getName() {
10 return "Fred";
11 }
12 };
13 }
14
15 public AnnotationInheritanceNotAResource getFailure() {
16 return new AnnotationInheritanceNotAResource() {
17 @Override
18 public String blah() {
19 return "Nothing";
20 }
21 };
22 }
23 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/AnnotationInheritanceSuperInt.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 public interface AnnotationInheritanceSuperInt {
7 @Path("foo")
8 @GET
9 @Produces("application/json")
10 String getFoo();
11 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/AnnotationInheritanceSuperIntAbstract.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 public abstract class AnnotationInheritanceSuperIntAbstract implements AnnotationInheritanceSuperInt {
3 @Override
4 public String getFoo() {
5 return "Foo: " + getName();
6 }
7
8 protected abstract String getName();
9 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/AppConfigApplication.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.core.Application;
3 import java.util.HashSet;
4 import java.util.Set;
5
6 public class AppConfigApplication extends Application {
7 private Set<Class<?>> classes = new HashSet<Class<?>>();
8 private Set<Object> singletons = new HashSet<Object>();
9
10 public AppConfigApplication() {
11 classes.add(AppConfigResources.MyResource.class);
12 singletons.add(new AppConfigResources.QuotedTextWriter());
13 }
14
15 public Set<Class<?>> getClasses() {
16 return classes;
17 }
18
19 @Override
20 public Set<Object> getSingletons() {
21 return singletons;
22 }
23
24 }
+0
-43
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/AppConfigResources.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.Provider;
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14
15 public class AppConfigResources {
16 @Path("/my")
17 public static class MyResource {
18 @GET
19 @Produces("text/quoted")
20 public String get() {
21 return "hello";
22 }
23 }
24
25 @Provider
26 @Produces("text/quoted")
27 public static class QuotedTextWriter implements MessageBodyWriter<String> {
28 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
29 return type.equals(String.class);
30 }
31
32 public long getSize(String s, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
33 return -1;
34 }
35
36 public void writeTo(String s, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
37 s = "\"" + s + "\"";
38 entityStream.write(s.getBytes());
39 }
40 }
41
42 }
+0
-55
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationConfig.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4 import javax.ws.rs.core.Context;
5 import javax.ws.rs.core.UriInfo;
6 import java.util.HashSet;
7 import java.util.Set;
8
9 @ApplicationPath("/")
10 public class ApplicationConfig extends Application {
11 private static ApplicationConfig instance;
12
13 private Set<Class<?>> classes = new HashSet<Class<?>>();
14
15 @Context
16 private UriInfo field;
17 private UriInfo setter;
18 private UriInfo constructor;
19
20 public ApplicationConfig(@Context final UriInfo uriInfo) {
21 this.constructor = uriInfo;
22 classes.add(ApplicationConfigResource.class);
23 classes.add(ApplicationConfigService.class);
24 classes.add(ApplicationConfigQuotedTextWriter.class);
25 classes.add(ApplicationConfigInjectionResource.class);
26 instance = this;
27 }
28
29 public static ApplicationConfig getInstance() {
30 return instance;
31 }
32
33 @Override
34 public Set<Class<?>> getClasses() {
35 return classes;
36 }
37
38 @Context
39 public void setSetter(UriInfo setter) {
40 this.setter = setter;
41 }
42
43 public boolean isFieldInjected() {
44 return field != null;
45 }
46
47 public boolean isSetterInjected() {
48 return setter != null;
49 }
50
51 public boolean isConstructorInjected() {
52 return constructor != null;
53 }
54 }
+0
-40
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationConfigInjectionResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Application;
6 import javax.ws.rs.core.Context;
7
8 @Path("/injection")
9 @Produces("text/plain")
10 public class ApplicationConfigInjectionResource {
11 private ApplicationConfig application;
12
13 @Path("/field")
14 @GET
15 public boolean fieldInjection() {
16 return getApplication().isFieldInjected();
17 }
18
19 @Path("/setter")
20 @GET
21 public boolean setterInjection() {
22 return getApplication().isSetterInjected();
23 }
24
25 @Path("/constructor")
26 @GET
27 public boolean constructorInjection() {
28 return getApplication().isConstructorInjected();
29 }
30
31 private ApplicationConfig getApplication() {
32 return application;
33 }
34
35 @Context
36 public void setApplication(Application app) {
37 this.application = (ApplicationConfig) app;
38 }
39 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationConfigInterface.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/myinterface")
7 public interface ApplicationConfigInterface {
8 @GET
9 @Produces("text/plain")
10 String hello();
11
12 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationConfigQuotedTextWriter.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.Produces;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import javax.ws.rs.ext.Provider;
8 import java.io.IOException;
9 import java.io.OutputStream;
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.Type;
12
13 @Provider
14 @Produces("text/quoted")
15 public class ApplicationConfigQuotedTextWriter implements MessageBodyWriter<String> {
16 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
17 return type.equals(String.class);
18 }
19
20 public long getSize(String s, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
21 return -1;
22 }
23
24 public void writeTo(String s, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
25 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException,
26 WebApplicationException {
27 s = String.format("\"%s\"", s);
28 entityStream.write(s.getBytes());
29 }
30 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationConfigResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/my")
7 public class ApplicationConfigResource {
8 @GET
9 @Produces("text/quoted")
10 public String get() {
11 return "hello";
12 }
13 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationConfigService.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 public class ApplicationConfigService implements ApplicationConfigInterface {
3 public String hello() {
4 return "hello";
5 }
6 }
+0
-89
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationFilterCustomer.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.xml.bind.annotation.XmlAttribute;
3 import javax.xml.bind.annotation.XmlElement;
4 import javax.xml.bind.annotation.XmlRootElement;
5
6 @XmlRootElement(name = "customer")
7 public class ApplicationFilterCustomer {
8 private int id;
9 private String firstName;
10 private String lastName;
11 private String street;
12 private String city;
13 private String state;
14 private String zip;
15 private String country;
16
17 @XmlAttribute
18 public int getId() {
19 return id;
20 }
21
22 public void setId(int id) {
23 this.id = id;
24 }
25
26 @XmlElement(name = "first-name")
27 public String getFirstName() {
28 return firstName;
29 }
30
31 public void setFirstName(String firstName) {
32 this.firstName = firstName;
33 }
34
35 @XmlElement(name = "last-name")
36 public String getLastName() {
37 return lastName;
38 }
39
40 public void setLastName(String lastName) {
41 this.lastName = lastName;
42 }
43
44 @XmlElement
45 public String getStreet() {
46 return street;
47 }
48
49 public void setStreet(String street) {
50 this.street = street;
51 }
52
53 @XmlElement
54 public String getCity() {
55 return city;
56 }
57
58 public void setCity(String city) {
59 this.city = city;
60 }
61
62 @XmlElement
63 public String getState() {
64 return state;
65 }
66
67 public void setState(String state) {
68 this.state = state;
69 }
70
71 @XmlElement
72 public String getZip() {
73 return zip;
74 }
75
76 public void setZip(String zip) {
77 this.zip = zip;
78 }
79
80 @XmlElement
81 public String getCountry() {
82 return country;
83 }
84
85 public void setCountry(String country) {
86 this.country = country;
87 }
88 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationFilterCustomerResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.WebApplicationException;
10 import javax.ws.rs.core.Response;
11 import java.net.URI;
12 import java.util.Map;
13 import java.util.concurrent.ConcurrentHashMap;
14 import java.util.concurrent.atomic.AtomicInteger;
15
16 @Path("/customers")
17 public class ApplicationFilterCustomerResource {
18 private Map<Integer, ApplicationFilterCustomer> customerDB = new ConcurrentHashMap<Integer, ApplicationFilterCustomer>();
19 private AtomicInteger idCounter = new AtomicInteger();
20
21 public ApplicationFilterCustomerResource() {
22 }
23
24 @POST
25 @Consumes("application/xml")
26 public Response createCustomer(ApplicationFilterCustomer customer) {
27 customer.setId(idCounter.incrementAndGet());
28 customerDB.put(customer.getId(), customer);
29 return Response.created(URI.create("/customers/" + customer.getId())).build();
30
31 }
32
33 @GET
34 @Path("{id}")
35 @Produces("application/xml")
36 public ApplicationFilterCustomer getCustomer(@PathParam("id") int id) {
37 ApplicationFilterCustomer customer = customerDB.get(id);
38 if (customer == null) {
39 throw new WebApplicationException(Response.Status.NOT_FOUND);
40 }
41 return customer;
42 }
43
44 @PUT
45 @Path("{id}")
46 @Consumes("application/xml")
47 public void updateCustomer(@PathParam("id") int id, ApplicationFilterCustomer update) {
48 ApplicationFilterCustomer current = customerDB.get(id);
49 if (current == null) {
50 throw new WebApplicationException(Response.Status.NOT_FOUND);
51 }
52
53 current.setFirstName(update.getFirstName());
54 current.setLastName(update.getLastName());
55 current.setStreet(update.getStreet());
56 current.setState(update.getState());
57 current.setZip(update.getZip());
58 current.setCountry(update.getCountry());
59 }
60 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationPropertiesConfig.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4 import java.util.Collections;
5 import java.util.Map;
6
7 @ApplicationPath("/")
8 public class ApplicationPropertiesConfig extends Application {
9
10 @Override
11 public Map<String, Object> getProperties() {
12 return Collections.<String, Object>singletonMap("Prop1", "Value1");
13 }
14 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationPropertiesConfigPropertyApplicationInjection.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2
3 import javax.ws.rs.ApplicationPath;
4 import javax.ws.rs.core.Application;
5 import java.util.Collections;
6 import java.util.Map;
7
8 @ApplicationPath("/")
9 public class ApplicationPropertiesConfigPropertyApplicationInjection extends Application {
10
11 @Override
12 public Map<String, Object> getProperties() {
13 return Collections.<String, Object>singletonMap("Prop1", "Value1");
14 }
15 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationPropertiesConfigPropertyApplicationInjectionFeature.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.container.DynamicFeature;
3 import javax.ws.rs.container.ResourceInfo;
4 import javax.ws.rs.core.FeatureContext;
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 public class ApplicationPropertiesConfigPropertyApplicationInjectionFeature implements DynamicFeature {
9
10 @Override
11 public void configure(ResourceInfo resourceInfo, FeatureContext context) {
12 boolean propertyPresent = context.getConfiguration().getProperties().containsKey("Prop1");
13 }
14 }
+0
-30
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationPropertiesConfigPropertyApplicationInjectionResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.QueryParam;
7 import javax.ws.rs.core.Application;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.Response;
10
11 @Path("/")
12 public class ApplicationPropertiesConfigPropertyApplicationInjectionResource {
13
14 @Context
15 private Application application;
16
17 @GET
18 @Path("/getconfigproperty")
19 public Response getProperty(@QueryParam("prop") String prop) {
20 String response = "false";
21 boolean containskey = application.getProperties().containsKey(prop);
22 if (containskey) {
23 response = "true";
24 }
25 Assert.assertEquals("The injected application doesn't contain property \"Prop1\"", "true", response);
26 String value = (String) application.getProperties().get("Prop1");
27 return Response.ok(value).build();
28 }
29 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationPropertiesConfigResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.QueryParam;
5 import javax.ws.rs.core.Configuration;
6 import javax.ws.rs.core.Context;
7
8 @Path("/")
9 public class ApplicationPropertiesConfigResource {
10
11 @Context
12 private Configuration configuration;
13
14 @GET
15 @Path("/getconfigproperty")
16 public String getProperty(@QueryParam("prop") String prop) {
17 String value = (String) configuration.getProperty(prop);
18 return value;
19 }
20 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationTestAExplicitApplication.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4 import java.util.HashSet;
5 import java.util.Set;
6
7 @ApplicationPath("a/explicit")
8 public class ApplicationTestAExplicitApplication extends Application {
9 @Override
10 public Set<Class<?>> getClasses() {
11 HashSet<Class<?>> set = new HashSet<Class<?>>();
12 set.add(ApplicationTestResourceA.class);
13 return set;
14 }
15 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationTestBExplicitApplication.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4 import java.util.HashSet;
5 import java.util.Set;
6
7 @ApplicationPath("b/explicit")
8 public class ApplicationTestBExplicitApplication extends Application {
9 @Override
10 public Set<Class<?>> getClasses() {
11 HashSet<Class<?>> set = new HashSet<Class<?>>();
12 set.add(ApplicationTestResourceB.class);
13 return set;
14 }
15 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationTestIgnoredApplication.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.core.Application;
3
4
5 public class ApplicationTestIgnoredApplication extends Application {
6 }
+0
-6
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationTestMappedApplication.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.core.Application;
3
4 public class ApplicationTestMappedApplication extends Application {
5 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationTestResourceA.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 @Path("/resources")
6 public class ApplicationTestResourceA {
7 @Path("a")
8 @GET
9 public String get() {
10 return "a";
11 }
12 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationTestResourceB.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 @Path("/resources")
6 public class ApplicationTestResourceB {
7 @Path("b")
8 @GET
9 public String get() {
10 return "b";
11 }
12 }
+0
-8
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ApplicationTestScannedApplication.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4
5 @ApplicationPath("scanned")
6 public class ApplicationTestScannedApplication extends Application {
7 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/CacheControlAnnotationResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.jboss.resteasy.annotations.cache.Cache;
3 import org.jboss.resteasy.annotations.cache.NoCache;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7
8 @Path("/")
9 public class CacheControlAnnotationResource {
10 @GET
11 @Cache(maxAge = 3600)
12 @Path("/maxage")
13 public String getMaxAge() {
14 return "maxage";
15 }
16
17 @GET
18 @NoCache
19 @Path("nocache")
20 public String getNoCache() {
21 return "nocache";
22 }
23
24 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ContextAfterEncoderInterceptor.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
6 import org.junit.Assert;
7
8 import javax.ws.rs.WebApplicationException;
9 import java.io.IOException;
10
11 @Precedence("AFTER_ENCODER")
12 @ServerInterceptor
13 public class ContextAfterEncoderInterceptor implements MessageBodyWriterInterceptor {
14 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
15 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextAfterEncoderInterceptor don't have correct headers";
16 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("before-encoder"));
17 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("encoder"));
18 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("end"));
19 context.getHeaders().add("after-encoder", "true");
20 context.proceed();
21 }
22 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ContextBeforeEncoderInterceptor.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
6 import org.junit.Assert;
7
8 import javax.ws.rs.WebApplicationException;
9 import java.io.IOException;
10
11 @Precedence("BEFORE_ENCODER")
12 @ServerInterceptor
13 public class ContextBeforeEncoderInterceptor implements MessageBodyWriterInterceptor {
14 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
15 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextBeforeEncoderInterceptor don't have correct headers";
16 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("after-encoder"));
17 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("encoder"));
18 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("end"));
19 context.getHeaders().add("before-encoder", "true");
20 context.proceed();
21 }
22 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ContextEncoderInterceptor.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.jboss.resteasy.annotations.interception.EncoderPrecedence;
3 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
6 import org.junit.Assert;
7
8 import javax.ws.rs.WebApplicationException;
9 import java.io.IOException;
10
11 @EncoderPrecedence
12 @ServerInterceptor
13 public class ContextEncoderInterceptor implements MessageBodyWriterInterceptor {
14 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
15 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextEncoderInterceptor don't have correct headers";
16 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("before-encoder"));
17 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("after-encoder"));
18 Assert.assertFalse(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("end"));
19 context.getHeaders().add("encoder", "true");
20 context.proceed();
21 }
22 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ContextEndInterceptor.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.jboss.resteasy.annotations.interception.Precedence;
3 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
4 import org.jboss.resteasy.spi.interception.MessageBodyWriterContext;
5 import org.jboss.resteasy.spi.interception.MessageBodyWriterInterceptor;
6 import org.junit.Assert;
7
8 import javax.ws.rs.WebApplicationException;
9 import java.io.IOException;
10
11 @Precedence("END")
12 @ServerInterceptor
13 public class ContextEndInterceptor implements MessageBodyWriterInterceptor {
14 public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
15 final String HEADER_ERROR_MESSAGE = "MessageBodyWriterContext in ContextEndInterceptor don't have correct headers";
16 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("before-encoder"));
17 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("after-encoder"));
18 Assert.assertTrue(HEADER_ERROR_MESSAGE, context.getHeaders().containsKey("encoder"));
19 context.getHeaders().add("end", "true");
20 context.proceed();
21 }
22 }
+0
-66
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ContextService.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.jboss.resteasy.spi.HttpRequest;
3 import org.junit.Assert;
4
5 import javax.servlet.ServletConfig;
6 import javax.servlet.ServletContext;
7 import javax.ws.rs.GET;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.core.Context;
11 import javax.ws.rs.core.UriInfo;
12
13 @Path("/")
14 public class ContextService {
15 @GET
16 @Path("/forward")
17 public void forward(@Context HttpRequest request) {
18 request.forward("/WEB-INF/index.html");
19 }
20
21 @GET
22 @Path("/test")
23 @Produces("text/plain")
24 public String get(@Context UriInfo uri) {
25 return uri.getBaseUri().toString();
26 }
27
28 @GET
29 @Produces("text/plain")
30 public String getBase(@Context UriInfo uri) {
31 return uri.getBaseUri().toString();
32 }
33
34 @GET
35 @Path("/test/servletcontext")
36 @Produces("text/plain")
37 public String get(@Context ServletContext context) {
38 Assert.assertNotNull("ServletConfig was not injected", context);
39 return "ok";
40 }
41
42 @GET
43 @Path("/test/servletconfig")
44 @Produces("text/plain")
45 public String get(@Context ServletConfig config) {
46 Assert.assertNotNull("ServletConfig was not injected", config);
47 Assert.assertNotNull("ServletConfig don't contain servlet.greeting parameter", config.getInitParameter("servlet.greeting"));
48 Assert.assertTrue("ServletConfig has some unexpected parameters", config.getInitParameterNames().hasMoreElements());
49 return "ok";
50 }
51
52 @GET
53 @Produces("application/json")
54 @Path("stuff")
55 public String getJson() {
56 return "json";
57 }
58
59 @GET
60 @Produces("application/xml")
61 @Path("stuff")
62 public String getXml() {
63 return "xml";
64 }
65 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/FileExtensionMappingApplication.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.core.Application;
3 import java.util.HashSet;
4 import java.util.Set;
5
6 public class FileExtensionMappingApplication extends Application {
7 private Set<Class<?>> classes = new HashSet<Class<?>>();
8 private Set<Object> singletons = new HashSet<Object>();
9
10 public FileExtensionMappingApplication() {
11 classes.add(FileExtensionMappingResource.class);
12 }
13
14 public Set<Class<?>> getClasses() {
15 return classes;
16 }
17
18 @Override
19 public Set<Object> getSingletons() {
20 return singletons;
21 }
22 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/FileExtensionMappingResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.QueryParam;
6 import javax.ws.rs.core.Context;
7 import javax.ws.rs.core.UriInfo;
8
9 @Path("/test")
10 public class FileExtensionMappingResource {
11 @GET
12 @Produces("text/plain")
13 public String testPlain(@Context UriInfo uriInfo, @QueryParam("query") String query) {
14 System.out.println(uriInfo.getRequestUri());
15 return "plain: " + query;
16 }
17
18 @GET
19 @Produces("text/html")
20 public String testHtml(@Context UriInfo uriInfo, @QueryParam("query") String query) {
21 System.out.println(uriInfo.getRequestUri());
22 return "html: " + query;
23 }
24 }
+0
-70
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/InternalDispatcherClient.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.jboss.resteasy.test.core.basic.InternalDispatcherTest;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.DELETE;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.PUT;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.PathParam;
11 import javax.ws.rs.Produces;
12 import javax.ws.rs.core.Response;
13
14 @Path("/")
15 public interface InternalDispatcherClient {
16 @GET
17 @Path("basic")
18 @Produces("text/plain")
19 String getBasic();
20
21 @PUT
22 @Path("basic")
23 @Consumes("text/plain")
24 void putBasic(String body);
25
26 @GET
27 @Path("forward/basic")
28 @Produces("text/plain")
29 String getForwardBasic();
30
31 @PUT
32 @Path("forward/basic")
33 @Consumes("text/plain")
34 void putForwardBasic(String body);
35
36 @POST
37 @Path("forward/basic")
38 @Consumes("text/plain")
39 void postForwardBasic(String body);
40
41 @DELETE
42 @Path("/forward/basic")
43 void deleteForwardBasic();
44
45 @GET
46 @Produces("text/plain")
47 @Path("/forward/object/{id}")
48 Response getForwardedObject(@PathParam("id") Integer id);
49
50 @GET
51 @Produces("text/plain")
52 @Path("/object/{id}")
53 Response getObject(@PathParam("id") Integer id);
54
55 @GET
56 @Produces("text/plain")
57 @Path("/infinite-forward")
58 int infiniteForward();
59
60 @GET
61 @Path(InternalDispatcherTest.PATH + "/basic")
62 @Produces("text/plain")
63 String getComplexBasic();
64
65 @GET
66 @Path(InternalDispatcherTest.PATH + "/forward/basic")
67 @Produces("text/plain")
68 String getComplexForwardBasic();
69 }
+0
-144
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/InternalDispatcherForwardingResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import org.jboss.resteasy.core.MessageBodyParameterInjector;
3 import org.jboss.resteasy.spi.BadRequestException;
4 import org.jboss.resteasy.spi.InternalDispatcher;
5 import org.jboss.resteasy.spi.ResteasyProviderFactory;
6 import org.jboss.resteasy.test.core.basic.InternalDispatcherTest;
7 import org.junit.Assert;
8
9 import javax.ws.rs.Consumes;
10 import javax.ws.rs.DELETE;
11 import javax.ws.rs.DefaultValue;
12 import javax.ws.rs.GET;
13 import javax.ws.rs.POST;
14 import javax.ws.rs.PUT;
15 import javax.ws.rs.Path;
16 import javax.ws.rs.PathParam;
17 import javax.ws.rs.Produces;
18 import javax.ws.rs.QueryParam;
19 import javax.ws.rs.core.Context;
20 import javax.ws.rs.core.Response;
21 import javax.ws.rs.core.UriInfo;
22 import java.util.Stack;
23
24 @Path("/")
25 public class InternalDispatcherForwardingResource {
26 public Stack<String> uriStack = new Stack<String>();
27 String basic = "basic";
28 @Context
29 UriInfo uriInfo;
30
31 @GET
32 @Produces("text/plain")
33 @Path("/basic")
34 public String getBasic() {
35 uriStack.push(uriInfo.getAbsolutePath().toString());
36 return basic;
37 }
38
39 @GET
40 @Produces("text/plain")
41 @Path("/forward/basic")
42 public String forwardBasic(@Context InternalDispatcher dispatcher) {
43 uriStack.push(uriInfo.getAbsolutePath().toString());
44 return (String) dispatcher.getEntity("/basic");
45 }
46
47 @PUT
48 @POST
49 @Consumes("text/plain")
50 @Path("/basic")
51 public void putBasic(String basic) {
52 uriStack.push(uriInfo.getAbsolutePath().toString());
53 this.basic = basic;
54 }
55
56 @DELETE
57 @Path("/basic")
58 public void deleteBasic() {
59 uriStack.push(uriInfo.getAbsolutePath().toString());
60 this.basic = "basic";
61 }
62
63 @PUT
64 @Consumes("text/plain")
65 @Path("/forward/basic")
66 public void putForwardBasic(String basic,
67 @Context InternalDispatcher dispatcher) {
68 uriStack.push(uriInfo.getAbsolutePath().toString());
69 dispatcher.putEntity("/basic", basic);
70 }
71
72 @POST
73 @Consumes("text/plain")
74 @Path("/forward/basic")
75 public void postForwardBasic(String basic,
76 @Context InternalDispatcher dispatcher) {
77 uriStack.push(uriInfo.getAbsolutePath().toString());
78 dispatcher.postEntity("/basic", basic);
79 }
80
81 @DELETE
82 @Path("/forward/basic")
83 public void deleteForwardBasic(@Context InternalDispatcher dispatcher) {
84 uriStack.push(uriInfo.getAbsolutePath().toString());
85 dispatcher.delete("/basic");
86 }
87
88 @GET
89 @Produces("text/plain")
90 @Path("/object/{id}")
91 public Response getObject(@PathParam("id") Integer id) {
92 uriStack.push(uriInfo.getAbsolutePath().toString());
93 if (id == 0) {
94 return Response.noContent().build();
95 } else {
96 return Response.ok("object" + id).build();
97 }
98 }
99
100 @GET
101 @Path("/forward/object/{id}")
102 public Response forwardObject(@PathParam("id") Integer id,
103 @Context InternalDispatcher dispatcher) {
104 uriStack.push(uriInfo.getAbsolutePath().toString());
105 return dispatcher.getResponse("/object/" + id);
106 }
107
108 @GET
109 @Path("/infinite-forward")
110 @Produces("text/plain")
111 public int infinitFoward(@Context InternalDispatcher dispatcher,
112 @QueryParam("count") @DefaultValue("0") int count) {
113 uriStack.push(uriInfo.getAbsolutePath().toString());
114 try {
115 dispatcher.getEntity("/infinite-forward?count=" + (count + 1));
116 // we'll never reach 20, since the max count of times through the
117 // system is 20, and first time through is 0
118 Assert.assertNotSame(20, count);
119 } catch (BadRequestException e) {
120
121 } finally {
122 Assert.assertEquals(count, MessageBodyParameterInjector.bodyCount());
123 Assert.assertEquals(count + 1, ResteasyProviderFactory.getContextDataLevelCount());
124 }
125 return ResteasyProviderFactory.getContextDataLevelCount();
126 }
127
128 @GET
129 @Path(InternalDispatcherTest.PATH + "/basic")
130 @Produces("text/plain")
131 public String getComplexBasic() {
132 uriStack.push(uriInfo.getAbsolutePath().toString());
133 return InternalDispatcherTest.PATH + basic;
134 }
135
136 @GET
137 @Produces("text/plain")
138 @Path(InternalDispatcherTest.PATH + "/forward/basic")
139 public String complexForwardBasic(@Context InternalDispatcher dispatcher) {
140 uriStack.push(uriInfo.getAbsolutePath().toString());
141 return (String) dispatcher.getEntity(InternalDispatcherTest.PATH + "/basic");
142 }
143 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/InvalidMediaTypeResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Response;
6
7 @Path("test")
8 public class InvalidMediaTypeResource {
9 @GET
10 @Produces("*/*")
11 public Response test() {
12 return Response.ok().entity("ok").build();
13 }
14 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/MyFilter.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.servlet.Filter;
3 import javax.servlet.FilterChain;
4 import javax.servlet.FilterConfig;
5 import javax.servlet.ServletException;
6 import javax.servlet.ServletRequest;
7 import javax.servlet.ServletResponse;
8 import java.io.IOException;
9
10 public class MyFilter implements Filter {
11 public void init(FilterConfig filterConfig) throws ServletException {
12 }
13
14 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
15 // test that form parameters still work even if a filter cause error in the input stream by calling servletRequest.getParameterMap()
16 servletRequest.getParameterMap();
17 filterChain.doFilter(servletRequest, servletResponse);
18 }
19
20 public void destroy() {
21 }
22 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/PrivateConstructorServiceResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.servlet.http.HttpServletRequest;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.Context;
7
8 @Path("/test")
9 public class PrivateConstructorServiceResource {
10 PrivateConstructorServiceResource() {
11
12 }
13
14 public PrivateConstructorServiceResource(@Context final javax.servlet.ServletContext context, @Context final HttpServletRequest request) {
15
16 }
17
18 @GET
19 @Produces("text/plain")
20 public String get() {
21 return "hello";
22 }
23 }
+0
-60
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ProviderInjectionSimpleMessageBodyWriter.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2 import javax.ws.rs.Produces;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.Context;
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.MultivaluedMap;
7 import javax.ws.rs.ext.MessageBodyWriter;
8 import javax.ws.rs.ext.Provider;
9 import javax.ws.rs.ext.Providers;
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.io.OutputStreamWriter;
13 import java.io.Writer;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.util.HashSet;
17 import java.util.Set;
18
19 @Provider
20 @Produces("text/plain")
21 public class ProviderInjectionSimpleMessageBodyWriter implements MessageBodyWriter<String> {
22
23 // just in case there was a pool of instances - we want to test all of them
24 private static Set<ProviderInjectionSimpleMessageBodyWriter> instances = new HashSet<ProviderInjectionSimpleMessageBodyWriter>();
25 @Context
26 private Providers fieldProviders = null;
27 private Providers constructorProviders = null;
28
29 public ProviderInjectionSimpleMessageBodyWriter(@Context final Providers providers) {
30 constructorProviders = providers;
31 instances.add(this);
32 }
33
34 public static Set<ProviderInjectionSimpleMessageBodyWriter> getInstances() {
35 return instances;
36 }
37
38 public long getSize(String t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
39 return 3;
40 }
41
42 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
43 return true;
44 }
45
46 public void writeTo(String t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
47 Writer writer = new OutputStreamWriter(entityStream);
48 writer.write("bar");
49 writer.flush();
50 }
51
52 public Providers getFieldProviders() {
53 return fieldProviders;
54 }
55
56 public Providers getConstructorProviders() {
57 return constructorProviders;
58 }
59 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ProviderInjectionSimpleResource.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2
3 import javax.ws.rs.GET;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6
7 @Path("/test")
8 public interface ProviderInjectionSimpleResource {
9 @GET
10 @Produces("text/plain")
11 String foo();
12 }
+0
-8
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/basic/resource/ProviderInjectionSimpleResourceImpl.java less more
0 package org.jboss.resteasy.test.core.basic.resource;
1
2
3 public class ProviderInjectionSimpleResourceImpl implements ProviderInjectionSimpleResource {
4 public String foo() {
5 return "foo";
6 }
7 }
+0
-88
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/CorsFiltersTest.java less more
0 package org.jboss.resteasy.test.core.interceptors;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
6 import org.jboss.resteasy.plugins.interceptors.CorsFilter;
7 import org.jboss.resteasy.spi.CorsHeaders;
8 import org.jboss.resteasy.test.core.interceptors.resource.CorsFiltersResource;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestApplication;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.WebTarget;
20 import javax.ws.rs.core.Response;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import static org.hamcrest.core.Is.is;
25
26 /**
27 * @tpSubChapter Interceptors
28 * @tpChapter Integration tests
29 * @tpTestCaseDetails Test CorsFilter usage
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 public class CorsFiltersTest {
34
35 @Deployment
36 public static Archive<?> deploySimpleResource() {
37 WebArchive war = TestUtil.prepareArchive(CorsFiltersTest.class.getSimpleName());
38 war.addClass(PortProviderUtil.class);
39 List<Class<?>> singletons = new ArrayList<>();
40 singletons.add(CorsFilter.class);
41 return TestUtil.finishContainerPrepare(war, null, singletons, CorsFiltersResource.class);
42 }
43
44 private String generateURL(String path) {
45 return PortProviderUtil.generateURL(path, CorsFiltersTest.class.getSimpleName());
46 }
47
48 /**
49 * @tpTestDetails Check different options of Cors headers.
50 * CorsFilter is created as singleton in TestApplication instance.
51 * In this test is CorsFilter get from static set from TestApplication class.
52 * @tpSince RESTEasy 3.0.16
53 */
54 @Test
55 public void testPreflight() throws Exception {
56 String testedURL = "http://" + PortProviderUtil.getHost();
57
58 ResteasyClient client = new ResteasyClientBuilder().build();
59 WebTarget target = client.target(generateURL("/test"));
60 Response response = target.request().header(CorsHeaders.ORIGIN, testedURL)
61 .options();
62 Assert.assertEquals(HttpResponseCodes.SC_FORBIDDEN, response.getStatus());
63 response.close();
64 response = target.request().header(CorsHeaders.ORIGIN, testedURL)
65 .get();
66 Assert.assertEquals(HttpResponseCodes.SC_FORBIDDEN, response.getStatus());
67 response.close();
68
69 Assert.assertThat("Wrong count of singletons were created", TestApplication.singletons.size(), is(1));
70 CorsFilter corsFilter = (CorsFilter) TestApplication.singletons.iterator().next();
71
72 corsFilter.getAllowedOrigins().add(testedURL);
73 response = target.request().header(CorsHeaders.ORIGIN, testedURL)
74 .options();
75 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
76 response.close();
77 response = target.request().header(CorsHeaders.ORIGIN, testedURL)
78 .get();
79 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
80 Assert.assertEquals(response.getHeaderString(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN), testedURL);
81 Assert.assertEquals("Wrong response", "hello", response.readEntity(String.class));
82 response.close();
83
84 client.close();
85 }
86
87 }
+0
-69
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/FilteredCookieTest.java less more
0 package org.jboss.resteasy.test.core.interceptors;
1
2 import javax.ws.rs.client.Client;
3 import javax.ws.rs.client.ClientBuilder;
4 import javax.ws.rs.client.Invocation.Builder;
5 import javax.ws.rs.client.WebTarget;
6 import javax.ws.rs.core.Cookie;
7 import javax.ws.rs.core.NewCookie;
8 import javax.ws.rs.core.Response;
9
10 import org.jboss.arquillian.container.test.api.Deployment;
11 import org.jboss.arquillian.container.test.api.RunAsClient;
12 import org.jboss.arquillian.junit.Arquillian;
13 import org.jboss.resteasy.test.core.interceptors.resource.FilteredCookieContainerRequestFilter;
14 import org.jboss.resteasy.test.core.interceptors.resource.FilteredCookieResource;
15 import org.jboss.resteasy.utils.PortProviderUtil;
16 import org.jboss.resteasy.utils.TestUtil;
17 import org.jboss.shrinkwrap.api.Archive;
18 import org.jboss.shrinkwrap.api.spec.WebArchive;
19 import org.junit.Assert;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 /**
24 * @tpSubChapter Cookies and filters
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Regression test for RESTEASY-1266
27 * @tpSince RESTEasy 3.1.0.Final
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class FilteredCookieTest {
32
33 private static final String OLD_COOKIE_NAME = "old-cookie";
34 private static final String NEW_COOKIE_NAME = "new-cookie";
35
36 @Deployment
37 public static Archive<?> deploySimpleResource() {
38 WebArchive war = TestUtil.prepareArchive(FilteredCookieTest.class.getSimpleName());
39 return TestUtil.finishContainerPrepare(war, null, FilteredCookieResource.class, FilteredCookieContainerRequestFilter.class);
40 }
41
42 private String generateURL(String path) {
43 return PortProviderUtil.generateURL(path, FilteredCookieTest.class.getSimpleName());
44 }
45
46 @Test
47 public void testServerHeaders() {
48
49 Client client = ClientBuilder.newClient();
50 WebTarget target = client.target(generateURL("/test/get"));
51 Response response = target.request().get();
52 NewCookie cookie = response.getCookies().get(OLD_COOKIE_NAME);
53 Assert.assertEquals(200, response.getStatus());
54 Assert.assertNotNull(cookie);
55 client.close();
56
57 client = ClientBuilder.newClient();
58 target = client.target(generateURL("/test/return"));
59 Builder builder = target.request();
60 response = builder.cookie(cookie).get();
61 NewCookie oldCookie = response.getCookies().get(OLD_COOKIE_NAME);
62 NewCookie newCookie = response.getCookies().get(NEW_COOKIE_NAME);
63 Assert.assertEquals(200, response.getStatus());
64 Assert.assertNotNull(oldCookie);
65 Assert.assertNotNull(newCookie);
66 client.close();
67 }
68 }
+0
-119
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/GzipSizeTest.java less more
0 package org.jboss.resteasy.test.core.interceptors;
1
2 import java.util.HashMap;
3 import java.util.Map;
4
5 import javax.ws.rs.ProcessingException;
6 import javax.ws.rs.client.Entity;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.Response;
9 import javax.ws.rs.core.Variant;
10
11 import org.apache.logging.log4j.LogManager;
12 import org.apache.logging.log4j.Logger;
13 import org.jboss.arquillian.container.test.api.Deployment;
14 import org.jboss.arquillian.container.test.api.RunAsClient;
15 import org.jboss.arquillian.junit.Arquillian;
16 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
17 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
18 import org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter;
19 import org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor;
20 import org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor;
21 import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
22 import org.jboss.resteasy.test.core.interceptors.resource.GzipIGZIP;
23 import org.jboss.resteasy.test.core.interceptors.resource.GzipResource;
24 import org.jboss.resteasy.test.core.interceptors.resource.Pair;
25 import org.jboss.resteasy.util.HttpResponseCodes;
26 import org.jboss.resteasy.utils.PortProviderUtil;
27 import org.jboss.resteasy.utils.TestUtil;
28 import org.jboss.shrinkwrap.api.Archive;
29 import org.jboss.shrinkwrap.api.spec.WebArchive;
30 import org.junit.After;
31 import org.junit.Assert;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.junit.runner.RunWith;
35
36 import com.google.common.net.HttpHeaders;
37
38 /**
39 * @tpSubChapter GZIP interceptors
40 * @tpChapter Integration tests
41 * @tpTestCaseDetails Gzip compression tests
42 * @tpSince RESTEasy 3.1.0.Final
43 */
44 @RunWith(Arquillian.class)
45 @RunAsClient
46 public class GzipSizeTest {
47
48 static ResteasyClient client;
49 protected static final Logger logger = LogManager.getLogger(GzipSizeTest.class.getName());
50
51 @Deployment
52 public static Archive<?> deploySimpleResource() {
53 WebArchive war = TestUtil.prepareArchive(GzipSizeTest.class.getSimpleName());
54 war.addClasses(GzipIGZIP.class, Pair.class);
55 // Activate gzip compression on server:
56 war.addAsManifestResource("org/jboss/resteasy/test/client/javax.ws.rs.ext.Providers", "services/javax.ws.rs.ext.Providers");
57 Map<String, String> contextParam = new HashMap<>();
58 contextParam.put(ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT, "16");
59 return TestUtil.finishContainerPrepare(war, contextParam, GzipResource.class);
60 }
61
62 private String generateURL(String path) {
63 return PortProviderUtil.generateURL(path, GzipSizeTest.class.getSimpleName());
64 }
65
66 @Before
67 public void init() {
68 client = new ResteasyClientBuilder() // Activate gzip compression on client:
69 .register(AcceptEncodingGZIPFilter.class)
70 .register(new GZIPDecodingInterceptor(16))
71 .register(GZIPEncodingInterceptor.class)
72 .build();
73 }
74
75 @After
76 public void after() throws Exception {
77 client.close();
78 }
79
80 /**
81 * @tpTestDetails Test exceeding configured maximum size on server
82 * @tpSince RESTEasy 3.1.0.Final
83 */
84 @Test
85 public void testMaxConfiguredSizeSending() throws Exception {
86 byte[] b = new byte[17];
87 Variant variant = new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, "", "gzip");
88 Response response = client.target(generateURL("/big/send")).request().post(Entity.entity(b, variant));
89 Assert.assertEquals(HttpResponseCodes.SC_REQUEST_ENTITY_TOO_LARGE, response.getStatus());
90 String message = response.readEntity(String.class);
91 Assert.assertTrue(message.contains("RESTEASY003357"));
92 Assert.assertTrue(message.contains("16"));
93 }
94
95 /**
96 * @tpTestDetails Test exceeding configured maximum size on client
97 * @tpSince RESTEasy 3.1.0.Final
98 */
99 @Test
100 public void testMaxConfiguredSizeReceiving() throws Exception {
101 Response response = client.target(generateURL("/big/receive")).request().header(HttpHeaders.ACCEPT_ENCODING, "gzip").post(Entity.entity(17, "text/plain"));
102 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
103 try
104 {
105 byte[] b = response.readEntity(byte[].class);
106 Assert.fail("Expecting ProcessingException, not " + b);
107 }
108 catch (ProcessingException e)
109 {
110 Assert.assertTrue(e.getMessage().contains("RESTEASY003357"));
111 Assert.assertTrue(e.getMessage().contains("16"));
112 }
113 catch (Exception e)
114 {
115 Assert.fail("Expecting ProcessingException, not " + e);
116 }
117 }
118 }
+0
-295
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/GzipTest.java less more
0 package org.jboss.resteasy.test.core.interceptors;
1
2 import org.apache.http.HttpResponse;
3 import org.apache.http.client.methods.HttpGet;
4 import org.apache.http.impl.client.CloseableHttpClient;
5 import org.apache.http.impl.client.HttpClientBuilder;
6 import org.apache.http.util.EntityUtils;
7 import org.apache.logging.log4j.LogManager;
8 import org.apache.logging.log4j.Logger;
9 import org.jboss.arquillian.container.test.api.Deployment;
10 import org.jboss.arquillian.container.test.api.RunAsClient;
11 import org.jboss.arquillian.junit.Arquillian;
12 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
13 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
14 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
15 import org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter;
16 import org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor;
17 import org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor;
18 import org.jboss.resteasy.test.core.interceptors.resource.GzipProxy;
19 import org.jboss.resteasy.test.core.interceptors.resource.GzipResource;
20 import org.jboss.resteasy.test.core.interceptors.resource.GzipIGZIP;
21 import org.jboss.resteasy.test.core.interceptors.resource.Pair;
22 import org.jboss.resteasy.util.HttpResponseCodes;
23 import org.jboss.resteasy.util.ReadFromStream;
24 import org.jboss.resteasy.utils.PortProviderUtil;
25 import org.jboss.resteasy.utils.TestUtil;
26 import org.jboss.shrinkwrap.api.Archive;
27 import org.jboss.shrinkwrap.api.spec.WebArchive;
28 import org.junit.After;
29 import org.junit.Assert;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.junit.runner.RunWith;
33
34 import javax.ws.rs.InternalServerErrorException;
35 import javax.ws.rs.client.Entity;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
38 import javax.ws.rs.core.Variant;
39
40 import java.io.ByteArrayInputStream;
41 import java.io.ByteArrayOutputStream;
42
43 /**
44 * @tpSubChapter Interceptors
45 * @tpChapter Integration tests
46 * @tpTestCaseDetails Gzip compression tests
47 * @tpSince RESTEasy 3.0.16
48 */
49 @RunWith(Arquillian.class)
50 @RunAsClient
51 public class GzipTest {
52
53 static ResteasyClient client;
54 protected static final Logger logger = LogManager.getLogger(GzipTest.class.getName());
55
56 @Deployment
57 public static Archive<?> deploySimpleResource() {
58 WebArchive war = TestUtil.prepareArchive(GzipTest.class.getSimpleName());
59 war.addClasses(GzipIGZIP.class, Pair.class);
60 // Activate gzip compression:
61 war.addAsManifestResource("org/jboss/resteasy/test/client/javax.ws.rs.ext.Providers", "services/javax.ws.rs.ext.Providers");
62 return TestUtil.finishContainerPrepare(war, null, GzipResource.class);
63 }
64
65 private String generateURL(String path) {
66 return PortProviderUtil.generateURL(path, GzipTest.class.getSimpleName());
67 }
68
69 @Before
70 public void init() {
71 client = new ResteasyClientBuilder()
72 .register(AcceptEncodingGZIPFilter.class)
73 .register(GZIPDecodingInterceptor.class)
74 .register(GZIPEncodingInterceptor.class)
75 .build();
76 }
77
78 @After
79 public void after() throws Exception {
80 client.close();
81 }
82
83 /**
84 * @tpTestDetails Check ByteArrayOutputStream of gzip data
85 * @tpSince RESTEasy 3.0.16
86 */
87 @Test
88 public void testRawStreams() throws Exception {
89 ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
90 GZIPEncodingInterceptor.EndableGZIPOutputStream outputStream = new GZIPEncodingInterceptor.EndableGZIPOutputStream(byteStream);
91 outputStream.write("hello world".getBytes());
92 outputStream.finish();
93 outputStream.close();
94
95 byte[] bytes1 = byteStream.toByteArray();
96 logger.info("Output stream length: " + bytes1.length);
97 logger.info("Output stream value:" + new String(bytes1));
98 ByteArrayInputStream bis = new ByteArrayInputStream(bytes1);
99 GZIPDecodingInterceptor.FinishableGZIPInputStream is = new GZIPDecodingInterceptor.FinishableGZIPInputStream(bis, false);
100 byte[] bytes = ReadFromStream.readFromStream(1024, is);
101 is.finish();
102 String str = new String(bytes);
103 Assert.assertEquals("Output stream has wrong content", "hello world", str);
104
105
106 }
107
108 /**
109 * @tpTestDetails Check ProxyFactory
110 * @tpSince RESTEasy 3.0.16
111 */
112 @Test
113 public void testProxy() throws Exception {
114 GzipIGZIP proxy = client.target(generateURL("")).proxy(GzipIGZIP.class);
115 Assert.assertEquals("Proxy return wrong content", "HELLO WORLD", proxy.getText());
116 Assert.assertEquals("Proxy return wrong content", "HELLO WORLD", proxy.getGzipText());
117
118 // resteasy-651
119 try {
120 proxy.getGzipErrorText();
121 Assert.fail("Proxy is unreachable");
122 } catch (InternalServerErrorException failure) {
123 Assert.assertEquals(HttpResponseCodes.SC_INTERNAL_SERVER_ERROR, failure.getResponse().getStatus());
124 String txt = failure.getResponse().readEntity(String.class);
125 Assert.assertEquals("Response contain wrong content", "Hello", txt);
126 }
127 }
128
129 /**
130 * @tpTestDetails Check length of content. Gzip data should have at least 11 bytes
131 * @tpSince RESTEasy 3.0.16
132 */
133 @Test
134 public void testContentLength() throws Exception {
135 {
136 Response response = client.target(generateURL("/text")).request().get();
137 Assert.assertEquals("Response has wrong content", "HELLO WORLD", response.readEntity(String.class));
138 String cl = response.getHeaderString("Content-Length");
139 if (cl != null) {
140 // make sure the content length is greater than 11 because this will be a gzipped encoding
141 Assert.assertTrue("Content length should be greater than 11 because this will be a gzipped encoding", Integer.parseInt(cl) > 11);
142 }
143 }
144 {
145 Response response = client.target(generateURL("/bytes")).request().get();
146 String cl = response.getHeaderString("Content-Length");
147 if (cl != null) {
148 // make sure the content length is greater than 11 because this will be a gzipped encoding
149 int integerCl = Integer.parseInt(cl);
150 logger.info("Content-Length: " + integerCl);
151 Assert.assertTrue("Content length should be greater than 11 because this will be a gzipped encoding", integerCl > 11);
152 }
153 Assert.assertEquals("Response contains wrong content", "HELLO WORLD", response.readEntity(String.class));
154 }
155 }
156
157 /**
158 * @tpTestDetails Check wrong URL
159 * @tpSince RESTEasy 3.0.16
160 */
161 @Test
162 public void testRequestError() throws Exception {
163 Response response = client.target(generateURL("/error")).request().get();
164 Assert.assertEquals(HttpResponseCodes.SC_METHOD_NOT_ALLOWED, response.getStatus());
165 response.close();
166 }
167
168 /**
169 * @tpTestDetails Check stream from PUT request
170 * @tpSince RESTEasy 3.0.16
171 */
172 @Test
173 public void testPutStream() throws Exception {
174 Response response = client.target(generateURL("/stream")).request().header("Content-Encoding", "gzip")
175 .put(Entity.entity("hello world", "text/plain"));
176 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
177 response.close();
178 }
179
180 /**
181 * @tpTestDetails Check text from PUT request
182 * @tpSince RESTEasy 3.0.16
183 */
184 @Test
185 public void testPutText() throws Exception {
186 Response response = client.target(generateURL("/text")).request().header("Content-Encoding", "gzip")
187 .put(Entity.entity("hello world", "text/plain"));
188 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
189 response.close();
190 }
191
192 /**
193 * @tpTestDetails Check plain text response
194 * @tpSince RESTEasy 3.0.16
195 */
196 @Test
197 public void testRequestPlain() throws Exception {
198 Response response = client.target(generateURL("/text")).request().get();
199 Assert.assertEquals("HELLO WORLD", response.readEntity(String.class));
200
201 }
202
203 /**
204 * @tpTestDetails Check encoded text response
205 * @tpSince RESTEasy 3.0.16
206 */
207 @Test
208 public void testRequestEncoded() throws Exception {
209 Response response = client.target(generateURL("/encoded/text")).request().get();
210 Assert.assertEquals("Response contains wrong content", "HELLO WORLD", response.readEntity(String.class));
211 }
212
213 /**
214 * @tpTestDetails Test that it was zipped by running it through Apache HTTP Client which does not automatically unzip
215 * @tpSince RESTEasy 3.0.16
216 */
217 @Test
218 public void testWasZipped() throws Exception {
219 CloseableHttpClient client = HttpClientBuilder.create().disableContentCompression().build();
220 {
221 HttpGet get = new HttpGet(generateURL("/encoded/text"));
222 get.addHeader("Accept-Encoding", "gzip, deflate");
223 HttpResponse response = client.execute(get);
224 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode());
225 Assert.assertEquals("Wrong encoding format", "gzip", response.getFirstHeader("Content-Encoding").getValue());
226
227 // test that it is actually zipped
228 String entity = EntityUtils.toString(response.getEntity());
229 logger.info("Entity: " + entity);
230 Assert.assertNotSame("Wrong entity content", entity, "HELLO WORLD");
231 }
232
233 {
234 HttpGet get = new HttpGet(generateURL("/text"));
235 get.addHeader("Accept-Encoding", "gzip, deflate");
236 HttpResponse response = client.execute(get);
237 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode());
238 Assert.assertEquals("Wrong encoding format", "gzip", response.getFirstHeader("Content-Encoding").getValue());
239
240 // test that it is actually zipped
241 String entity = EntityUtils.toString(response.getEntity());
242 Assert.assertNotSame("Wrong entity content", entity, "HELLO WORLD");
243 }
244 }
245
246 /**
247 * @tpTestDetails Test that if there is no accept-encoding: gzip header that result isn't encoded
248 * @tpSince RESTEasy 3.0.16
249 */
250 @Test
251 public void testWithoutAcceptEncoding() throws Exception {
252 CloseableHttpClient client = HttpClientBuilder.create().build();
253 HttpGet get = new HttpGet(generateURL("/encoded/text"));
254 HttpResponse response = client.execute(get);
255 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode());
256 Assert.assertNull(response.getFirstHeader("Content-Encoding"));
257
258 // test that it is actually zipped
259 String entity = EntityUtils.toString(response.getEntity());
260 Assert.assertEquals("Response contains wrong content", entity, "HELLO WORLD");
261 }
262
263 /**
264 * @tpTestDetails Send POST request with gzip encoded data using @GZIP annotation and client proxy framework
265 * @tpInfo RESTEASY-1499
266 * @tpSince RESTEasy 3.1.0
267 */
268 @Test
269 public void testGzipPost() {
270 GzipProxy gzipProxy = ProxyBuilder.builder(GzipProxy.class, client.target(generateURL(""))).build();
271 Pair data = new Pair();
272 data.setP1("first");
273 data.setP2("second");
274
275 Response response = gzipProxy.post(data);
276 Assert.assertEquals("gzip", response.getHeaderString("Content-Encoding"));
277 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
278 }
279
280 /**
281 * @tpTestDetails Test exceeding default maximum size
282 * @tpSince RESTEasy 3.1.0.Final
283 */
284 @Test
285 public void testMaxDefaultSizeSending() throws Exception {
286 byte[] b = new byte[10000001];
287 Variant variant = new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, "", "gzip");
288 Response response = client.target(generateURL("/big/send")).request().post(Entity.entity(b, variant));
289 Assert.assertEquals(HttpResponseCodes.SC_REQUEST_ENTITY_TOO_LARGE, response.getStatus());
290 String message = response.readEntity(String.class);
291 Assert.assertTrue(message.contains("RESTEASY003357"));
292 Assert.assertTrue(message.contains("10000000"));
293 }
294 }
+0
-60
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/PreProcessorExceptionMapperTest.java less more
0 package org.jboss.resteasy.test.core.interceptors;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.interceptors.resource.PreProcessorExceptionMapperCandlepinException;
8 import org.jboss.resteasy.test.core.interceptors.resource.PreProcessorExceptionMapperCandlepinUnauthorizedException;
9 import org.jboss.resteasy.test.core.interceptors.resource.PreProcessorExceptionMapperPreProcessSecurityInterceptor;
10 import org.jboss.resteasy.test.core.interceptors.resource.PreProcessorExceptionMapperResource;
11 import org.jboss.resteasy.test.core.interceptors.resource.PreProcessorExceptionMapperRuntimeExceptionMapper;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.asset.StringAsset;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.Assert;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.core.Response;
22
23 import static org.jboss.resteasy.utils.PortProviderUtil.generateURL;
24
25 /**
26 * @tpSubChapter Interceptors
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Regression test for RESTEASY-433
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class PreProcessorExceptionMapperTest {
34
35 @Deployment
36 public static Archive<?> deploySimpleResource() {
37 WebArchive war = TestUtil.prepareArchive(GzipTest.class.getSimpleName());
38 war.addClass(PreProcessorExceptionMapperCandlepinException.class);
39 war.addClass(PreProcessorExceptionMapperCandlepinUnauthorizedException.class);
40 return TestUtil.finishContainerPrepare(war, null, PreProcessorExceptionMapperPreProcessSecurityInterceptor.class,
41 PreProcessorExceptionMapperRuntimeExceptionMapper.class,
42 PreProcessorExceptionMapperResource.class);
43 }
44
45 /**
46 * @tpTestDetails Generate PreProcessorExceptionMapperCandlepinUnauthorizedException
47 * @tpPassCrit SC_PRECONDITION_FAILED (412) HTTP code is excepted
48 * @tpSince RESTEasy 3.0.16
49 */
50 @Test
51 public void testMapper() throws Exception {
52 ResteasyClient client = new ResteasyClientBuilder().build();
53 Response response = client.target(generateURL("/interception", GzipTest.class.getSimpleName())).request().get();
54 Assert.assertEquals(HttpResponseCodes.SC_PRECONDITION_FAILED, response.getStatus());
55 response.close();
56 client.close();
57 }
58
59 }
+0
-100
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/ReaderContextTest.java less more
0 package org.jboss.resteasy.test.core.interceptors;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.core.interceptors.resource.ReaderContextArrayListEntityProvider;
6 import org.jboss.resteasy.test.core.interceptors.resource.ReaderContextFirstReaderInterceptor;
7 import org.jboss.resteasy.test.core.interceptors.resource.ReaderContextFirstWriterInterceptor;
8 import org.jboss.resteasy.test.core.interceptors.resource.ReaderContextLinkedListEntityProvider;
9 import org.jboss.resteasy.test.core.interceptors.resource.ReaderContextResource;
10 import org.jboss.resteasy.test.core.interceptors.resource.ReaderContextSecondReaderInterceptor;
11 import org.jboss.resteasy.test.core.interceptors.resource.ReaderContextSecondWriterInterceptor;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.AfterClass;
17 import org.junit.Assert;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.Client;
22 import javax.ws.rs.client.ClientBuilder;
23 import javax.ws.rs.client.Entity;
24 import javax.ws.rs.client.WebTarget;
25 import javax.ws.rs.core.Response;
26 import java.io.BufferedReader;
27 import java.io.IOException;
28 import java.io.Reader;
29 import java.util.ArrayList;
30 import java.util.List;
31
32 /**
33 * @tpSubChapter Interceptors
34 * @tpChapter Integration tests
35 * @tpTestCaseDetails Basic test for reated context
36 * @tpSince RESTEasy 3.0.16
37 */
38 @RunWith(Arquillian.class)
39 @RunAsClient
40 public class ReaderContextTest {
41
42 public static final String readFromReader(Reader reader) throws IOException {
43 BufferedReader br = new BufferedReader(reader);
44 String entity = br.readLine();
45 br.close();
46 return entity;
47 }
48
49
50 static Client client;
51
52 @Deployment
53 public static Archive<?> deploySimpleResource() {
54 WebArchive war = TestUtil.prepareArchive(ReaderContextTest.class.getSimpleName());
55 return TestUtil.finishContainerPrepare(war, null, ReaderContextResource.class,
56 ReaderContextArrayListEntityProvider.class,
57 ReaderContextLinkedListEntityProvider.class,
58 ReaderContextFirstReaderInterceptor.class,
59 ReaderContextFirstWriterInterceptor.class,
60 ReaderContextSecondReaderInterceptor.class,
61 ReaderContextSecondWriterInterceptor.class);
62 }
63
64 private String generateURL(String path) {
65 return PortProviderUtil.generateURL(path, ReaderContextTest.class.getSimpleName());
66 }
67
68 @AfterClass
69 public static void cleanup() {
70 client.close();
71 }
72
73 /**
74 * @tpTestDetails Check post request.
75 * @tpSince RESTEasy 3.0.16
76 */
77 @Test
78 public void readerContextOnClientTest() {
79 client = ClientBuilder.newClient();
80
81 WebTarget target = client.target(generateURL("/resource/poststring"));
82 target.register(ReaderContextFirstReaderInterceptor.class);
83 target.register(ReaderContextSecondReaderInterceptor.class);
84 target.register(ReaderContextArrayListEntityProvider.class);
85 target.register(ReaderContextLinkedListEntityProvider.class);
86 Response response = target.request().post(Entity.text("plaintext"));
87 response.getHeaders().add(ReaderContextResource.HEADERNAME,
88 ReaderContextFirstReaderInterceptor.class.getName());
89 @SuppressWarnings("unchecked")
90 List<String> list = response.readEntity(List.class);
91 Assert.assertTrue("Returned list in not instance of ArrayList", ArrayList.class.isInstance(list));
92 String entity = list.get(0);
93 Assert.assertTrue("Wrong interceptor type in response", entity.contains(ReaderContextSecondReaderInterceptor.class.getName()));
94 Assert.assertTrue("Wrong interceptor annotation in response", entity.contains(ReaderContextSecondReaderInterceptor.class.getAnnotations()[0]
95 .annotationType().getName()));
96
97 client.close();
98 }
99 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/CorsFiltersResource.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/")
7 public class CorsFiltersResource {
8 @Path("test")
9 @GET
10 @Produces("text/plain")
11 public String get() {
12 return "hello";
13 }
14 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/FilteredCookieContainerRequestFilter.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import java.io.IOException;
3
4 import javax.ws.rs.container.ContainerRequestContext;
5 import javax.ws.rs.container.ContainerRequestFilter;
6 import javax.ws.rs.container.PreMatching;
7 import javax.ws.rs.core.Cookie;
8 import javax.ws.rs.core.HttpHeaders;
9 import javax.ws.rs.ext.Provider;
10
11 @Provider
12 @PreMatching
13 public class FilteredCookieContainerRequestFilter implements ContainerRequestFilter {
14
15 private static final String OLD_COOKIE_NAME = "old-cookie";
16 private static final String NEW_COOKIE_NAME = "new-cookie";
17
18 @Override
19 public void filter(ContainerRequestContext requestContext) throws IOException {
20
21 final Cookie cookie = requestContext.getCookies().get(OLD_COOKIE_NAME);
22 if (cookie != null) {
23 requestContext.getHeaders().add(HttpHeaders.COOKIE, new Cookie(NEW_COOKIE_NAME, cookie.getValue()).toString());
24 }
25 }
26 }
+0
-35
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/FilteredCookieResource.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Context;
5 import javax.ws.rs.core.Cookie;
6 import javax.ws.rs.core.HttpHeaders;
7 import javax.ws.rs.core.NewCookie;
8 import javax.ws.rs.core.Response;
9 import javax.ws.rs.core.Response.ResponseBuilder;
10
11 @Path("test")
12 public class FilteredCookieResource {
13 private static final String OLD_COOKIE_NAME = "old-cookie";
14 private static final String NEW_COOKIE_NAME = "new-cookie";
15 private @Context HttpHeaders headers;
16
17 @GET
18 @Path("get")
19 public Response getCookie() {
20 NewCookie cookie = new NewCookie(OLD_COOKIE_NAME, "value");
21 return Response.ok().cookie(cookie).build();
22 }
23
24 @GET
25 @Path("return")
26 public Response returnCookie() {
27 Cookie oldCookie = headers.getCookies().get(OLD_COOKIE_NAME);
28 Cookie newCookie = headers.getCookies().get(NEW_COOKIE_NAME);
29 ResponseBuilder builder = Response.ok();
30 builder.cookie(new NewCookie(oldCookie.getName(), oldCookie.getValue()));
31 builder.cookie(new NewCookie(newCookie.getName(), newCookie.getValue()));
32 return builder.build();
33 }
34 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/GzipIGZIP.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import org.jboss.resteasy.annotations.GZIP;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7
8 @Path("/")
9 public interface GzipIGZIP {
10 @GET
11 @Path("text")
12 @Produces("text/plain")
13 String getText();
14
15 @GET
16 @Path("encoded/text")
17 @GZIP
18 String getGzipText();
19
20 @GET
21 @Path("encoded/text/error")
22 @GZIP
23 String getGzipErrorText();
24
25 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/GzipProxy.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2
3 import org.jboss.resteasy.annotations.GZIP;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.PUT;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.core.Response;
10
11 @Path("/gzippost")
12 public interface GzipProxy {
13
14 @Consumes("application/json")
15 @POST
16 @GZIP
17 public Response post(@GZIP Pair pair);
18 }
+0
-124
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/GzipResource.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2
3 import org.jboss.logging.Logger;
4 import org.jboss.resteasy.annotations.GZIP;
5 import org.jboss.resteasy.util.ReadFromStream;
6 import org.junit.Assert;
7
8 import javax.ws.rs.GET;
9 import javax.ws.rs.POST;
10 import javax.ws.rs.PUT;
11 import javax.ws.rs.Path;
12 import javax.ws.rs.Produces;
13 import javax.ws.rs.Consumes;
14 import javax.ws.rs.WebApplicationException;
15 import javax.ws.rs.core.Context;
16 import javax.ws.rs.core.HttpHeaders;
17 import javax.ws.rs.core.Response;
18 import javax.ws.rs.core.StreamingOutput;
19 import javax.ws.rs.core.Variant;
20 import javax.ws.rs.core.MultivaluedMap;
21 import javax.ws.rs.core.MediaType;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.util.Locale;
26
27 @Path("/")
28 public class GzipResource {
29
30 private static Logger logger = Logger.getLogger(GzipResource.class);
31 @GET
32 @Path("text")
33 @Produces("text/plain")
34 public Response getText(@Context HttpHeaders headers) {
35 String acceptEncoding = headers.getRequestHeaders().getFirst(HttpHeaders.ACCEPT_ENCODING);
36 logger.info(acceptEncoding);
37 Assert.assertEquals("gzip, deflate", acceptEncoding);
38 return Response.ok("HELLO WORLD").header("Content-Encoding", "gzip").build();
39 }
40
41 @GET
42 @Path("encoded/text")
43 @GZIP
44 public String getGzipText() {
45 return "HELLO WORLD";
46 }
47
48 @GET
49 @Path("bytes")
50 @GZIP
51 @Produces("text/plain")
52 public byte[] getBytes() {
53 return "HELLO WORLD".getBytes();
54 }
55
56 @GET
57 @Path("error")
58 @GZIP
59 @Produces({"application/json;charset=UTF-8"})
60 public StreamingOutput getTest() {
61 return new StreamingOutput() {
62 @Override
63 public void write(OutputStream outputStream) throws IOException, WebApplicationException {
64 throw new WebApplicationException(405);
65 }
66 };
67 }
68
69 @GET
70 @Path("encoded/text/error")
71 @GZIP
72 public String getGzipErrorText() {
73 throw new WebApplicationException(
74 Response.status(500).entity("Hello").type("text/plain").build()
75 );
76 }
77
78 @PUT
79 @Consumes("text/plain")
80 @Path("stream")
81 public void putStream(InputStream is) throws Exception {
82 byte[] bytes = ReadFromStream.readFromStream(1024, is);
83 String str = new String(bytes);
84 Assert.assertEquals("hello world", str);
85 }
86
87 @PUT
88 @Consumes("text/plain")
89 @Path("text")
90 public void putText(String text) throws Exception {
91 Assert.assertEquals("hello world", text);
92 }
93
94 @POST
95 @Path("/gzippost")
96 @Produces(MediaType.APPLICATION_JSON)
97 public Response postGZipped(@GZIP Pair pair, @Context HttpHeaders headers) {
98 MultivaluedMap<String, String> requestHeaders = headers.getRequestHeaders();
99 for (String key : requestHeaders.keySet()) {
100 logger.info(key + ": " + requestHeaders.get(key));
101 }
102 Assert.assertEquals("gzip", headers.getRequestHeaders().getFirst(HttpHeaders.CONTENT_ENCODING));
103 Assert.assertEquals("first", pair.getP1());
104 Assert.assertEquals("second", pair.getP2());
105
106 return Response.ok().type(MediaType.TEXT_PLAIN).encoding("gzip").build();
107 }
108
109 @POST
110 @Path("big/send")
111 public Response sendBig(byte[] b)
112 {
113 return Response.ok().build();
114 }
115
116 @POST
117 @Path("big/receive")
118 public Response receiveBig(int n)
119 {
120 Variant variant = new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, Locale.ENGLISH, "gzip");
121 return Response.ok(new byte[n]).variant(variant).header("xyz", "abc").build();
122 }
123 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/Pair.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import java.io.Serializable;
3
4 public class Pair implements Serializable {
5
6 private static final long serialVersionUID = 1L;
7 private String P1;
8 private String P2;
9
10 public String getP1() {
11 return this.P1;
12 }
13
14 public String getP2() {
15 return this.P2;
16 }
17
18 public void setP1(String p1) {
19 this.P1 = p1;
20 }
21
22 public void setP2(String p2) {
23 this.P2 = p2;
24 }
25 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/PreProcessorExceptionMapperCandlepinException.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 public class PreProcessorExceptionMapperCandlepinException extends RuntimeException {
3 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/PreProcessorExceptionMapperCandlepinUnauthorizedException.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 public class PreProcessorExceptionMapperCandlepinUnauthorizedException extends PreProcessorExceptionMapperCandlepinException {
3 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/PreProcessorExceptionMapperPreProcessSecurityInterceptor.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import org.jboss.resteasy.core.ResourceMethodInvoker;
3 import org.jboss.resteasy.core.ServerResponse;
4 import org.jboss.resteasy.spi.Failure;
5 import org.jboss.resteasy.spi.HttpRequest;
6 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
7
8 import javax.ws.rs.WebApplicationException;
9 import javax.ws.rs.ext.Provider;
10
11 @Provider
12 public class PreProcessorExceptionMapperPreProcessSecurityInterceptor implements PreProcessInterceptor {
13 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
14 throw new PreProcessorExceptionMapperCandlepinUnauthorizedException();
15 }
16 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/PreProcessorExceptionMapperResource.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/interception")
7 public class PreProcessorExceptionMapperResource {
8 @GET
9 @Produces("text/plain")
10 public String get() {
11 return "hello world";
12 }
13 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/PreProcessorExceptionMapperRuntimeExceptionMapper.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class PreProcessorExceptionMapperRuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {
8 public Response toResponse(RuntimeException exception) {
9 return Response.status(412).build();
10 }
11 }
+0
-73
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/ReaderContextArrayListEntityProvider.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import org.jboss.resteasy.utils.TestUtil;
3
4 import javax.ws.rs.WebApplicationException;
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.MultivaluedMap;
7 import javax.ws.rs.ext.MessageBodyReader;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.Provider;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.OutputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.Type;
15 import java.util.ArrayList;
16
17 @Provider
18 public class ReaderContextArrayListEntityProvider implements
19 MessageBodyReader<ArrayList<String>>,
20 MessageBodyWriter<ArrayList<String>> {
21
22 @Override
23 public boolean isWriteable(Class<?> type, Type genericType,
24 Annotation[] annotations, MediaType mediaType) {
25 return type == ArrayList.class;
26 }
27
28 @Override
29 public long getSize(ArrayList<String> t, Class<?> type, Type genericType,
30 Annotation[] annotations, MediaType mediaType) {
31 int annlen = annotations.length > 0 ? annotations[0].annotationType()
32 .getName().length() : 0;
33 return t.iterator().next().length() + annlen
34 + mediaType.toString().length();
35 }
36
37 @Override
38 public void writeTo(ArrayList<String> t, Class<?> type, Type genericType,
39 Annotation[] annotations, MediaType mediaType,
40 MultivaluedMap<String, Object> httpHeaders,
41 OutputStream entityStream) throws IOException,
42 WebApplicationException {
43 String ann = "";
44 if (annotations.length > 0) {
45 ann = annotations[0].annotationType().getName();
46 }
47 entityStream.write((t.iterator().next() + ann + mediaType.toString())
48 .getBytes());
49 }
50
51 @Override
52 public boolean isReadable(Class<?> type, Type genericType,
53 Annotation[] annotations, MediaType mediaType) {
54 return type == ArrayList.class;
55 }
56
57 @Override
58 public ArrayList<String> readFrom(Class<ArrayList<String>> type,
59 Type genericType, Annotation[] annotations, MediaType mediaType,
60 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
61 throws IOException, WebApplicationException {
62 String text = TestUtil.readString(entityStream);
63 entityStream.close();
64 String ann = "";
65 if (annotations.length > 0) {
66 ann = annotations[0].annotationType().getName();
67 }
68 ArrayList<String> list = new ArrayList<String>();
69 list.add(text + ann + mediaType.toString());
70 return list;
71 }
72 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/ReaderContextFirstReaderInterceptor.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.Provider;
7 import javax.ws.rs.ext.ReaderInterceptor;
8 import javax.ws.rs.ext.ReaderInterceptorContext;
9 import java.io.ByteArrayInputStream;
10 import java.io.IOException;
11 import java.util.LinkedList;
12
13 @Provider
14 @Priority(100)
15 public class ReaderContextFirstReaderInterceptor implements ReaderInterceptor {
16
17 @Override
18 public Object aroundReadFrom(ReaderInterceptorContext context)
19 throws IOException, WebApplicationException {
20 MultivaluedMap<String, String> headers = context.getHeaders();
21 String header = headers.getFirst(ReaderContextResource.HEADERNAME);
22 if (header != null && header.equals(getClass().getName())) {
23 context.setAnnotations(ReaderContextResource.class.getAnnotations());
24 context.setInputStream(new ByteArrayInputStream(getClass()
25 .getName().getBytes()));
26 context.setMediaType(MediaType.TEXT_HTML_TYPE);
27 context.setType(LinkedList.class);
28 }
29 return context.proceed();
30 }
31
32 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/ReaderContextFirstWriterInterceptor.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.Provider;
7 import javax.ws.rs.ext.WriterInterceptor;
8 import javax.ws.rs.ext.WriterInterceptorContext;
9 import java.io.IOException;
10 import java.util.LinkedList;
11
12 @Provider
13 @Priority(100)
14 public class ReaderContextFirstWriterInterceptor implements WriterInterceptor {
15
16 @Override
17 public void aroundWriteTo(WriterInterceptorContext context)
18 throws IOException, WebApplicationException {
19 MultivaluedMap<String, Object> headers = context.getHeaders();
20 String header = (String) headers.getFirst(ReaderContextResource.HEADERNAME);
21 if (header != null && header.equals(getClass().getName())) {
22 context.setAnnotations(ReaderContextResource.class.getAnnotations());
23 context.setEntity(toList(getClass().getName()));
24 context.setMediaType(MediaType.TEXT_HTML_TYPE);
25 context.setType(LinkedList.class);
26 }
27 context.proceed();
28 }
29
30 private static <T> LinkedList<T> toList(T o) {
31 LinkedList<T> list = new LinkedList<T>();
32 list.add(o);
33 return list;
34 }
35 }
+0
-60
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/ReaderContextLinkedListEntityProvider.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import javax.ws.rs.ext.MessageBodyReader;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import javax.ws.rs.ext.Provider;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.OutputStream;
11 import java.lang.annotation.Annotation;
12 import java.lang.reflect.Type;
13 import java.util.LinkedList;
14
15 @Provider
16 public class ReaderContextLinkedListEntityProvider implements
17 MessageBodyReader<LinkedList<String>>,
18 MessageBodyWriter<LinkedList<String>> {
19
20 public static final String ERROR = "This LinkedList provider should never be used";
21
22 @Override
23 public boolean isWriteable(Class<?> type, Type genericType,
24 Annotation[] annotations, MediaType mediaType) {
25 return type == LinkedList.class;
26 }
27
28 @Override
29 public long getSize(LinkedList<String> t, Class<?> type, Type genericType,
30 Annotation[] annotations, MediaType mediaType) {
31 return ERROR.length();
32 }
33
34 @Override
35 public void writeTo(LinkedList<String> t, Class<?> type, Type genericType,
36 Annotation[] annotations, MediaType mediaType,
37 MultivaluedMap<String, Object> httpHeaders,
38 OutputStream entityStream) throws IOException,
39 WebApplicationException {
40 entityStream.write(ERROR.getBytes());
41 }
42
43 @Override
44 public boolean isReadable(Class<?> type, Type genericType,
45 Annotation[] annotations, MediaType mediaType) {
46 return isWriteable(type, genericType, annotations, mediaType);
47 }
48
49 @Override
50 public LinkedList<String> readFrom(Class<LinkedList<String>> type,
51 Type genericType, Annotation[] annotations, MediaType mediaType,
52 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
53 throws IOException, WebApplicationException {
54 LinkedList<String> list = new LinkedList<String>();
55 list.add(ERROR);
56 return list;
57 }
58
59 }
+0
-71
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/ReaderContextResource.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.core.Context;
6 import javax.ws.rs.core.GenericEntity;
7 import javax.ws.rs.core.HttpHeaders;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Response;
10 import java.util.ArrayList;
11 import java.util.List;
12
13 @Path("resource")
14 public class ReaderContextResource {
15
16 public static final String HEADERNAME = "FILTER_HEADER";
17
18 public static final String getName() {
19 // make this long enough to let entity provider getSize()
20 // be enough to let our interceptor name fit in
21 return "<resource>" + ReaderContextResource.class.getName() + "</resource>";
22 }
23
24 @POST
25 @Path("postlist")
26 public String postList(List<String> list) {
27 return list.iterator().next();
28 }
29
30 @GET
31 @Path("getlist")
32 public Response getList() {
33 ArrayList<String> list = new ArrayList<String>();
34 list.add(getName());
35 GenericEntity<ArrayList<String>> entity = new GenericEntity<ArrayList<String>>(
36 list) {
37 };
38 return buildResponse(entity);
39 }
40
41 @POST
42 @Path("poststring")
43 public Response postString(String string) {
44 return buildResponse(string);
45 }
46
47 // ///////////////////////////////////////////////////////////////////////////
48 // Send header that would have the power to enable filter / interceptor
49 // The header is passed from client request
50 @Context
51 private HttpHeaders headers;
52
53 private Response buildResponse(Object content) {
54 return buildResponse(content, MediaType.WILDCARD_TYPE);
55 }
56
57 private Response buildResponse(Object content, MediaType type) {
58 List<String> list = headers.getRequestHeader(HEADERNAME);
59 String name = null;
60 if (list != null && list.size() != 0) {
61 name = list.iterator().next();
62 }
63 Response.ResponseBuilder builder = Response.ok(content, type).type(type);
64 if (name != null) {
65 builder.header(HEADERNAME, name);
66 }
67 return builder.build();
68 }
69
70 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/ReaderContextSecondReaderInterceptor.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.ReaderInterceptor;
7 import javax.ws.rs.ext.ReaderInterceptorContext;
8 import java.io.ByteArrayInputStream;
9 import java.io.IOException;
10 import java.util.ArrayList;
11
12 @Priority(200)
13 public class ReaderContextSecondReaderInterceptor implements ReaderInterceptor {
14
15 @Override
16 public Object aroundReadFrom(ReaderInterceptorContext context)
17 throws IOException, WebApplicationException {
18 MultivaluedMap<String, String> headers = context.getHeaders();
19 String header = headers.getFirst(ReaderContextResource.HEADERNAME);
20 if (header != null
21 && header.equals(ReaderContextFirstReaderInterceptor.class.getName())) {
22 context.setAnnotations(getClass().getAnnotations());
23 context.setInputStream(new ByteArrayInputStream(getClass()
24 .getName().getBytes()));
25 context.setMediaType(MediaType.TEXT_PLAIN_TYPE);
26 context.setType(ArrayList.class);
27 }
28 return context.proceed();
29 }
30 }
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/interceptors/resource/ReaderContextSecondWriterInterceptor.java less more
0 package org.jboss.resteasy.test.core.interceptors.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.WriterInterceptor;
7 import javax.ws.rs.ext.WriterInterceptorContext;
8 import java.io.IOException;
9 import java.util.ArrayList;
10
11 @Priority(200)
12 public class ReaderContextSecondWriterInterceptor implements WriterInterceptor {
13
14 @Override
15 public void aroundWriteTo(WriterInterceptorContext context)
16 throws IOException, WebApplicationException {
17 MultivaluedMap<String, Object> headers = context.getHeaders();
18 String header = (String) headers.getFirst(ReaderContextResource.HEADERNAME);
19 if (header != null
20 && header.equals(ReaderContextFirstWriterInterceptor.class.getName())) {
21 context.setAnnotations(getClass().getAnnotations());
22 context.setEntity(toList(getClass().getName()));
23 context.setGenericType(String.class);
24 context.setMediaType(MediaType.TEXT_PLAIN_TYPE);
25 context.setType(ArrayList.class);
26 }
27 context.proceed();
28 }
29
30 private static <T> ArrayList<T> toList(T o) {
31 ArrayList<T> list = new ArrayList<T>();
32 list.add(o);
33 return list;
34 }
35
36 }
+0
-56
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/FilterTest.java less more
0 package org.jboss.resteasy.test.core.servlet;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.servlet.resource.FilterForwardServlet;
8 import org.jboss.resteasy.test.core.servlet.resource.FilterResource;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.Invocation;
18 import javax.ws.rs.core.Response;
19
20 import static org.junit.Assert.assertEquals;
21
22 /**
23 * @tpSubChapter Configuration
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Regression test for RESTEASY-1049
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class FilterTest {
31 @Deployment
32 public static Archive<?> createTestArchive() {
33 WebArchive war = TestUtil.prepareArchive(FilterTest.class.getSimpleName())
34 .addClasses(FilterForwardServlet.class)
35 .addAsWebInfResource(ServletConfigTest.class.getPackage(), "FilterWeb.xml", "web.xml");
36 return TestUtil.finishContainerPrepare(war, null, FilterResource.class);
37 }
38
39 private String generateURL(String path) {
40 return PortProviderUtil.generateURL(path, FilterTest.class.getSimpleName());
41 }
42
43 /**
44 * @tpTestDetails Test for dynamic dispatching in servlet.
45 * @tpSince RESTEasy 3.0.16
46 */
47 @Test
48 public void testDispatchDynamic() throws Exception {
49 ResteasyClient client = new ResteasyClientBuilder().build();
50 Invocation.Builder request = client.target(generateURL("/test/dispatch/dynamic")).request();
51 Response response = request.get();
52 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
53 assertEquals("Wrong content of response", "forward", response.readEntity(String.class));
54 }
55 }
+0
-95
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/ServletConfigTest.java less more
0 package org.jboss.resteasy.test.core.servlet;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.core.servlet.resource.ServletConfigApplication;
8 import org.jboss.resteasy.test.core.servlet.resource.ServletConfigException;
9 import org.jboss.resteasy.test.core.servlet.resource.ServletConfigExceptionMapper;
10 import org.jboss.resteasy.test.core.servlet.resource.ServletConfigResource;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.ShrinkWrap;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Configuration
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Regression test for RESTEASY-381, RESTEASY-518 and RESTEASY-582. Check ServletConfig instance.
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class ServletConfigTest {
34 private static ResteasyClient client;
35
36 @Deployment
37 public static Archive<?> deploySimpleResource() {
38 WebArchive war = ShrinkWrap.create(WebArchive.class, ServletConfigTest.class.getSimpleName() + ".war");
39 war.addAsWebInfResource(ServletConfigTest.class.getPackage(), "ServletConfigWeb.xml", "web.xml");
40 war.addClasses(ServletConfigException.class, ServletConfigExceptionMapper.class,
41 ServletConfigApplication.class, ServletConfigResource.class);
42 return war;
43 }
44
45 private String generateURL(String path) {
46 return PortProviderUtil.generateURL(path, ServletConfigTest.class.getSimpleName());
47 }
48
49 @Before
50 public void setup() {
51 client = new ResteasyClientBuilder().build();
52 }
53
54 @After
55 public void after() throws Exception {
56 client.close();
57 }
58
59 /**
60 * @tpTestDetails Regression test for RESTEASY-381
61 * @tpSince RESTEasy 3.0.16
62 */
63 @Test
64 public void testCount() throws Exception {
65 String count = client.target(generateURL("/my/application/count")).request().get(String.class);
66 Assert.assertEquals("Wrong count of RESTEasy application", "1", count);
67 }
68
69 /**
70 * @tpTestDetails Regression test for RESTEASY-518
71 * @tpSince RESTEasy 3.0.16
72 */
73 @Test
74 public void testNullJaxb() throws Exception {
75 Response response = client.target(generateURL("/my/null")).request().header("Content-Type", "application/xml").post(Entity.text(""));
76 Assert.assertEquals(HttpResponseCodes.SC_UNSUPPORTED_MEDIA_TYPE, response.getStatus());
77 response.close();
78 }
79
80 /**
81 * @tpTestDetails Regression test for RESTEASY-582
82 * @tpSince RESTEasy 3.0.16
83 */
84 @Test
85 public void testBadMediaTypeNoSubtype() throws Exception {
86 Response response = client.target(generateURL("/my/application/count")).request().accept("text").get();
87 Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus());
88 response.close();
89
90 response = client.target(generateURL("/my/application/count")).request().accept("text/plain; q=bad").get();
91 Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus());
92 response.close();
93 }
94 }
+0
-120
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/ServletMappingTest.java less more
0 package org.jboss.resteasy.test.core.servlet;
1
2 import org.apache.http.client.methods.CloseableHttpResponse;
3 import org.apache.http.client.methods.HttpGet;
4 import org.apache.http.impl.client.CloseableHttpClient;
5 import org.apache.http.impl.client.HttpClients;
6 import org.jboss.arquillian.container.test.api.Deployment;
7 import org.jboss.arquillian.container.test.api.RunAsClient;
8 import org.jboss.arquillian.junit.Arquillian;
9 import org.jboss.resteasy.client.ProxyFactory;
10 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
11 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
12 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
13 import org.jboss.resteasy.test.core.servlet.resource.ServletMappingProxy;
14 import org.jboss.resteasy.test.core.basic.resource.MyFilter;
15 import org.jboss.resteasy.test.core.servlet.resource.ServletMappingResource;
16 import org.jboss.resteasy.util.HttpResponseCodes;
17 import org.jboss.resteasy.utils.PortProviderUtil;
18 import org.jboss.resteasy.utils.TestUtil;
19 import org.jboss.shrinkwrap.api.Archive;
20 import org.jboss.shrinkwrap.api.spec.WebArchive;
21 import org.junit.After;
22 import org.junit.Assert;
23 import org.junit.Before;
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26
27 import javax.ws.rs.client.WebTarget;
28 import javax.ws.rs.core.Response;
29
30 /**
31 * @tpSubChapter Configuration
32 * @tpChapter Integration tests
33 * @tpTestCaseDetails Test for servlet mapping. This settings is in web.xml
34 * @tpSince RESTEasy 3.0.16
35 */
36 @RunWith(Arquillian.class)
37 @RunAsClient
38 public class ServletMappingTest {
39 public static final String WRONG_RESPONSE_ERROR_MSG = "Wrong content of response";
40
41 private static ResteasyClient client;
42
43 @Deployment
44 public static Archive<?> deploySimpleResource() {
45 WebArchive war = TestUtil.prepareArchive(ServletMappingTest.class.getSimpleName());
46 war.addAsWebInfResource(ServletMappingTest.class.getPackage(), "ServletMappingWeb.xml", "web.xml");
47 war.addAsWebInfResource(ServletMappingTest.class.getPackage(), "ServletMappingJbossWeb.xml", "jboss-web.xml");
48 war.addClass(MyFilter.class);
49 return TestUtil.finishContainerPrepare(war, null, ServletMappingResource.class, ServletMappingProxy.class);
50 }
51
52 private String generateURL(String path) {
53 return PortProviderUtil.generateURL(path, "");
54 }
55
56 @Before
57 public void setup() {
58 client = new ResteasyClientBuilder().build();
59 }
60
61 @After
62 public void after() throws Exception {
63 client.close();
64 }
65
66 /**
67 * @tpTestDetails Test for new resteasy client without proxy
68 * @tpSince RESTEasy 3.0.16
69 */
70 @Test
71 public void testNoDefaultsResourceNewRESTEasyClient() throws Exception {
72 WebTarget target = client.target(generateURL("/resteasy/rest/basic"));
73 Response response = target.request().get();
74 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
75 Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "basic", response.readEntity(String.class));
76 response.close();
77 }
78
79 /**
80 * @tpTestDetails Test for apache client
81 * @tpSince RESTEasy 3.0.16
82 */
83 @Test
84 public void testNoDefaultsResourceApacheClient() throws Exception {
85 CloseableHttpClient httpclient = HttpClients.createDefault();
86 HttpGet httpGet = new HttpGet(generateURL("/resteasy/rest/basic"));
87 CloseableHttpResponse response1 = httpclient.execute(httpGet);
88
89 try {
90 Assert.assertEquals(HttpResponseCodes.SC_OK, response1.getStatusLine().getStatusCode());
91 Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "basic", TestUtil.readString(response1.getEntity().getContent()));
92 } finally {
93 response1.close();
94 }
95 }
96
97 /**
98 * @tpTestDetails Test for old resteasy client with proxy
99 * @tpSince RESTEasy 3.0.16
100 */
101 @Test
102 public void testFormParamOldRESTEasyClient() {
103 final ServletMappingProxy client = ProxyFactory.create(ServletMappingProxy.class, generateURL("/resteasy/rest"));
104 final String result = client.postForm("value");
105 Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, result, "value");
106 }
107
108 /**
109 * @tpTestDetails Test for new resteasy client with proxy
110 * @tpSince RESTEasy 3.0.16
111 */
112 @Test
113 public void testFormParamNewRESTEasyClient() {
114 ResteasyWebTarget target = client.target(generateURL("/resteasy/rest"));
115 ServletMappingProxy client = target.proxyBuilder(ServletMappingProxy.class).build();
116 final String result = client.postForm("value");
117 Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, result, "value");
118 }
119 }
+0
-56
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/UndertowTest.java less more
0 package org.jboss.resteasy.test.core.servlet;
1
2 import org.hamcrest.CoreMatchers;
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.core.servlet.resource.FilterForwardServlet;
6 import org.jboss.resteasy.test.core.servlet.resource.UndertowServlet;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.ShrinkWrap;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import java.net.HttpURLConnection;
18 import java.net.URL;
19
20 /**
21 * @tpSubChapter Configuration
22 * @tpChapter Integration tests
23 * @tpTestCaseDetails Regression test for RESTEASY-903
24 * @tpSince RESTEasy 3.0.16
25 */
26 @RunWith(Arquillian.class)
27 public class UndertowTest {
28 @Deployment
29 public static Archive<?> createTestArchive() {
30 WebArchive war = ShrinkWrap.create(WebArchive.class, "RESTEASY-903.war")
31 .addClasses(UndertowServlet.class, FilterForwardServlet.class, UndertowTest.class, TestUtil.class, PortProviderUtil.class)
32 .addAsWebInfResource(ServletConfigTest.class.getPackage(), "UndertowWeb.xml", "web.xml");
33 return war;
34 }
35
36 private String generateURL(String path) {
37 return PortProviderUtil.generateURL(path, "RESTEASY-903");
38 }
39
40 /**
41 * @tpTestDetails Redirection in one servlet to other servlet.
42 * @tpSince RESTEasy 3.0.16
43 */
44 @Test
45 public void testUndertow() throws Exception {
46 URL url = new URL(generateURL("/test"));
47 HttpURLConnection conn = HttpURLConnection.class.cast(url.openConnection());
48 conn.connect();
49 byte[] b = new byte[16];
50 conn.getInputStream().read(b);
51 Assert.assertThat("Wrong content of response", new String(b), CoreMatchers.startsWith("forward"));
52 Assert.assertEquals(HttpResponseCodes.SC_OK, conn.getResponseCode());
53 conn.disconnect();
54 }
55 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/FilterForwardServlet.java less more
0 package org.jboss.resteasy.test.core.servlet.resource;
1
2 import javax.servlet.ServletException;
3 import javax.servlet.ServletRequest;
4 import javax.servlet.ServletResponse;
5 import javax.servlet.http.HttpServlet;
6 import java.io.IOException;
7
8 public class FilterForwardServlet extends HttpServlet {
9 private static final long serialVersionUID = 1L;
10
11 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
12 res.getOutputStream().write("forward".getBytes());
13 }
14 }
+0
-41
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/FilterResource.java less more
0 package org.jboss.resteasy.test.core.servlet.resource;
1
2 import javax.servlet.ServletContext;
3 import javax.servlet.ServletRequestWrapper;
4 import javax.servlet.ServletResponseWrapper;
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7
8 @Path("test")
9 public class FilterResource {
10 @javax.ws.rs.core.Context
11 javax.servlet.http.HttpServletRequest request;
12 @javax.ws.rs.core.Context
13 javax.servlet.http.HttpServletResponse response;
14 @javax.ws.rs.core.Context
15 ServletContext context;
16
17 @GET
18 @Path("dispatch/static")
19 public void dispatchStatic() {
20 javax.servlet.RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/test.html");
21
22 try {
23 dispatcher.forward(request, response);
24 } catch (Exception e) {
25 throw new RuntimeException(e);
26 }
27 }
28
29 @GET
30 @Path("dispatch/dynamic")
31 public void dispatchDynamic() {
32 javax.servlet.RequestDispatcher dispatcher = request.getRequestDispatcher("/forward");
33
34 try {
35 dispatcher.forward(new ServletRequestWrapper(request), new ServletResponseWrapper(response));
36 } catch (Exception e) {
37 throw new RuntimeException(e);
38 }
39 }
40 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/ServletConfigApplication.java less more
0 package org.jboss.resteasy.test.core.servlet.resource;
1
2 import javax.ws.rs.core.Application;
3 import java.util.HashSet;
4 import java.util.Set;
5
6 public class ServletConfigApplication extends Application {
7 public static int num_instantiations = 0;
8
9 protected Set<Object> singletons = new HashSet<Object>();
10 protected Set<Class<?>> clazzes = new HashSet<Class<?>>();
11
12 public ServletConfigApplication() {
13 num_instantiations++;
14 singletons.add(new ServletConfigResource());
15 clazzes.add(ServletConfigExceptionMapper.class);
16
17 }
18
19 @Override
20 public Set<Class<?>> getClasses() {
21 return clazzes;
22 }
23
24 @Override
25 public Set<Object> getSingletons() {
26 return singletons;
27 }
28
29 public String getHello() {
30 return "hello";
31 }
32 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/ServletConfigException.java less more
0 package org.jboss.resteasy.test.core.servlet.resource;
1
2 public class ServletConfigException extends RuntimeException {
3 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/ServletConfigExceptionMapper.java less more
0 package org.jboss.resteasy.test.core.servlet.resource;
1
2 import org.jboss.resteasy.util.HttpResponseCodes;
3 import org.junit.Assert;
4
5 import javax.servlet.ServletConfig;
6 import javax.servlet.ServletContext;
7 import javax.ws.rs.core.Application;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.Response;
10 import javax.ws.rs.ext.ExceptionMapper;
11 import javax.ws.rs.ext.Provider;
12
13 @Provider
14 public class ServletConfigExceptionMapper implements ExceptionMapper<ServletConfigException> {
15 private ServletConfigApplication application;
16 private ServletConfig servletConfig;
17 private ServletContext context;
18
19 public ServletConfigExceptionMapper(@Context final Application application,
20 @Context final ServletConfig servletConfig, @Context final ServletContext context) {
21 this.application = (ServletConfigApplication) application;
22 this.servletConfig = servletConfig;
23 this.context = context;
24 Assert.assertEquals("hello", this.application.getHello());
25 Assert.assertEquals("servlet hello", this.servletConfig.getInitParameter("servlet.greeting"));
26 Assert.assertEquals("context hello", this.context.getInitParameter("context.greeting"));
27 }
28
29 public Response toResponse(ServletConfigException exception) {
30 return Response.status(HttpResponseCodes.SC_PRECONDITION_FAILED).build();
31 }
32 }
+0
-57
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/ServletConfigResource.java less more
0 package org.jboss.resteasy.test.core.servlet.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.GET;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.xml.bind.annotation.XmlRootElement;
10
11 @Path("my")
12 public class ServletConfigResource {
13 @XmlRootElement
14 public static class Foo {
15 private String name;
16
17 public String getName() {
18 return name;
19 }
20
21 public void setName(String name) {
22 this.name = name;
23 }
24
25 }
26
27 public static int num_instatiations = 0;
28
29 @Path("count")
30 @GET
31 @Produces("text/plain")
32 public String getCount() {
33 return Integer.toString(num_instatiations);
34 }
35
36 @Path("application/count")
37 @GET
38 @Produces("text/plain")
39 public String getApplicationCount() {
40 return Integer.toString(ServletConfigApplication.num_instantiations);
41 }
42
43 @Path("exception")
44 @GET
45 @Produces("text/plain")
46 public String getException() {
47 throw new ServletConfigException();
48 }
49
50 @Path("null")
51 @POST
52 @Consumes("application/xml")
53 public void nullFoo(Foo foo) {
54 Assert.assertNull(foo);
55 }
56 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/ServletMappingProxy.java less more
0 package org.jboss.resteasy.test.core.servlet.resource;
1
2 import javax.ws.rs.FormParam;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5
6 @Path("/")
7 public interface ServletMappingProxy {
8 @POST
9 @Path("formtestit")
10 String postForm(@FormParam("value") String value);
11 }
+0
-69
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/ServletMappingResource.java less more
0 package org.jboss.resteasy.test.core.servlet.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.FormParam;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.POST;
9 import javax.ws.rs.PUT;
10 import javax.ws.rs.Path;
11 import javax.ws.rs.PathParam;
12 import javax.ws.rs.Produces;
13 import javax.ws.rs.QueryParam;
14 import javax.ws.rs.core.Context;
15 import javax.ws.rs.core.HttpHeaders;
16 import javax.ws.rs.core.UriInfo;
17 import java.net.URI;
18
19 @Path("/")
20 public class ServletMappingResource {
21
22 @GET
23 @Path("basic")
24 @Produces("text/plain")
25 public String getBasic(@Context UriInfo uriInfo) throws Exception {
26 URI uri = uriInfo.getBaseUriBuilder().path(ServletMappingResource.class, "getBasic").build();
27 Assert.assertEquals(uri.getPath(), "/resteasy/rest/basic");
28 return "basic";
29 }
30
31 @PUT
32 @Path("basic")
33 @Consumes("text/plain")
34 public void putBasic(String body) {
35 }
36
37 @GET
38 @Path("queryParam")
39 @Produces("text/plain")
40 public String getQueryParam(@QueryParam("param") String param) {
41 return param;
42 }
43
44 @GET
45 @Path("matrixParam")
46 @Produces("text/plain")
47 public String getMatrixParam(@MatrixParam("param") String param) {
48 return param;
49 }
50
51 @GET
52 @Path("uriParam/{param}")
53 @Produces("text/plain")
54 public int getUriParam(@PathParam("param") int param) {
55 return param;
56 }
57
58
59 @POST
60 @Path("formtestit")
61 @Produces("text/plain")
62 public String postForm(@FormParam("value") String value, @Context HttpHeaders headers) {
63 if (value == null) {
64 throw new RuntimeException("VALUE WAS NULL");
65 }
66 return value;
67 }
68 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/UndertowServlet.java less more
0 package org.jboss.resteasy.test.core.servlet.resource;
1
2 import javax.servlet.RequestDispatcher;
3 import javax.servlet.ServletException;
4 import javax.servlet.ServletRequest;
5 import javax.servlet.ServletResponse;
6 import javax.servlet.http.HttpServlet;
7 import java.io.IOException;
8
9 public class UndertowServlet extends HttpServlet {
10 private static final long serialVersionUID = 1L;
11
12 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
13 RequestDispatcher dispatcher = req.getRequestDispatcher("/forward");
14 try {
15 dispatcher.forward(req, res);
16 } catch (Exception e) {
17 throw new RuntimeException(e);
18 }
19 }
20 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/core/smoke/resource/ResourceWithInterfaceSimpleClient.java less more
0 package org.jboss.resteasy.test.core.smoke.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.MatrixParam;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/")
12 public interface ResourceWithInterfaceSimpleClient {
13 @GET
14 @Path("basic")
15 @Produces("text/plain")
16 String getBasic();
17
18 @PUT
19 @Path("basic")
20 @Consumes("text/plain")
21 void putBasic(String body);
22
23 @GET
24 @Path("queryParam")
25 @Produces("text/plain")
26 String getQueryParam(@QueryParam("param") String param);
27
28 @GET
29 @Path("matrixParam")
30 @Produces("text/plain")
31 String getMatrixParam(@MatrixParam("param") String param);
32
33 @GET
34 @Path("uriParam/{param}")
35 @Produces("text/plain")
36 int getUriParam(@PathParam("param") int param);
37 }
+0
-73
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/AbstractExceptionMapperTest.java less more
0 package org.jboss.resteasy.test.exception;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.test.exception.resource.AbstractMapper;
5 import org.jboss.resteasy.test.exception.resource.AbstractMapperDefault;
6 import org.jboss.resteasy.test.exception.resource.AbstractMapperException;
7 import org.jboss.resteasy.test.exception.resource.AbstractMapperMyCustom;
8 import org.jboss.resteasy.test.exception.resource.AbstractMapperResource;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.util.Types;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.Client;
22 import javax.ws.rs.client.ClientBuilder;
23 import javax.ws.rs.core.Response;
24 import javax.ws.rs.ext.ExceptionMapper;
25 import java.lang.reflect.Type;
26
27 /**
28 * @tpSubChapter Resteasy-client
29 * @tpChapter Integration tests
30 * @tpSince RESTEasy 3.0.16
31 * @tpTestCaseDetails Regression test for RESTEASY-666
32 */
33 @RunWith(Arquillian.class)
34 public class AbstractExceptionMapperTest {
35
36 private Client client;
37
38 @Deployment
39 public static Archive<?> createTestArchive() {
40 WebArchive war = TestUtil.prepareArchive(AbstractExceptionMapperTest.class.getSimpleName());
41 war.addClass(PortProviderUtil.class);
42 war.addClasses(AbstractMapper.class, AbstractMapperException.class);
43 return TestUtil.finishContainerPrepare(war, null, AbstractMapperDefault.class,
44 AbstractMapperMyCustom.class, AbstractMapperResource.class);
45 }
46
47
48 @Before
49 public void setup() {
50 client = ClientBuilder.newClient();
51 }
52
53 @After
54 public void cleanup() {
55 client.close();
56 }
57
58 /**
59 * @tpTestDetails Correct exception mapper should be chosen when ExceptionMapper implement statement is in abstract class.
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void testCustomUsed() {
64 Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(AbstractMapperMyCustom.class, ExceptionMapper.class)[0];
65 Assert.assertEquals(AbstractMapperException.class, exceptionType);
66
67 Response response = client.target(PortProviderUtil.generateURL("/resource/custom",
68 AbstractExceptionMapperTest.class.getSimpleName())).request().get();
69 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
70 Assert.assertEquals("custom", response.readEntity(String.class));
71 }
72 }
+0
-85
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/ExceptionHandlingTest.java less more
0 package org.jboss.resteasy.test.exception;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.exception.resource.ExceptionHandlingProvider;
8 import org.jboss.resteasy.test.exception.resource.ExceptionHandlingResource;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Test;
14 import org.junit.Before;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.InternalServerErrorException;
20 import javax.ws.rs.core.Response;
21 import javax.ws.rs.POST;
22 import javax.ws.rs.Path;
23
24 /**
25 * @tpSubChapter Resteasy-client
26 * @tpChapter Client tests
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class ExceptionHandlingTest {
32
33 static ResteasyClient client;
34
35 @Deployment
36 public static Archive<?> deploy() {
37 WebArchive war = TestUtil.prepareArchive(ExceptionHandlingTest.class.getSimpleName());
38 war.addClass(ExceptionHandlingTest.class);
39 return TestUtil.finishContainerPrepare(war, null, ExceptionHandlingResource.class, ExceptionHandlingProvider.class);
40 }
41
42 @Before
43 public void init() {
44 client = new ResteasyClientBuilder().build();
45 }
46
47 @After
48 public void after() throws Exception {
49 client.close();
50 client = null;
51 }
52
53 private String generateURL(String path) {
54 return PortProviderUtil.generateURL(path, ExceptionHandlingTest.class.getSimpleName());
55 }
56
57 @Path("/")
58 public interface ThrowsExceptionInterface {
59 @Path("test")
60 @POST
61 void post() throws Exception;
62 }
63
64 /**
65 * @tpTestDetails POST request is sent by client via client proxy. The resource on the server throws exception,
66 * which is handled by ExceptionMapper.
67 * @tpPassCrit The response with expected Exception text is returned
68 * @tpSince RESTEasy 3.0.16
69 */
70 @Test
71 public void testThrowsException() throws Exception {
72
73 ThrowsExceptionInterface proxy = client.target(generateURL("/")).proxy(ThrowsExceptionInterface.class);
74 try {
75 proxy.post();
76 } catch (InternalServerErrorException e) {
77 Response response = e.getResponse();
78 String errorText = response.readEntity(String.class);
79 Assert.assertNotNull("Missing the expected exception text", errorText);
80 }
81
82 }
83
84 }
+0
-57
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/ExceptionMapperApplicationRuntimeExceptionTest.java less more
0 package org.jboss.resteasy.test.exception;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.exception.resource.ExceptionMapperApplicationRuntimeCustomMapper;
8 import org.jboss.resteasy.test.exception.resource.ExceptionMapperApplicationRuntimeMapper;
9 import org.jboss.resteasy.test.exception.resource.ExceptionMapperApplicationRuntimeResource;
10 import org.jboss.resteasy.test.exception.resource.ExceptionMapperCustomRuntimeException;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.WebTarget;
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Resteasy-client
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.0.16
26 * @tpTestCaseDetails Regression test for RESTEASY-421
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class ExceptionMapperApplicationRuntimeExceptionTest {
31
32 @Deployment
33 public static Archive<?> createTestArchive() {
34 WebArchive war = TestUtil.prepareArchive(ExceptionMapperApplicationRuntimeExceptionTest.class.getSimpleName());
35 war.addClass(ExceptionMapperCustomRuntimeException.class);
36 return TestUtil.finishContainerPrepare(war, null, ExceptionMapperApplicationRuntimeCustomMapper.class,
37 ExceptionMapperApplicationRuntimeMapper.class, ExceptionMapperApplicationRuntimeResource.class);
38 }
39
40 /**
41 * @tpTestDetails Check ExceptionMapper for ApplicationException
42 * @tpSince RESTEasy 3.0.16
43 */
44 @Test
45 public void testMapper() throws Exception {
46 ResteasyClient client = new ResteasyClientBuilder().build();
47 WebTarget base = client.target(PortProviderUtil.generateURL("/test", ExceptionMapperApplicationRuntimeExceptionTest.class.getSimpleName()));
48 Response response = base.request().get();
49
50 Assert.assertEquals(Response.Status.PRECONDITION_FAILED.getStatusCode(), response.getStatus());
51
52 response.close();
53 client.close();
54 }
55
56 }
+0
-78
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/ExceptionMapperCustomRuntimeExceptionTest.java less more
0 package org.jboss.resteasy.test.exception;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.exception.resource.ExceptionMapperCustomRuntimeCustomMapper;
10 import org.jboss.resteasy.test.exception.resource.ExceptionMapperCustomRuntimeException;
11 import org.jboss.resteasy.test.exception.resource.ExceptionMapperCustomRuntimeMapper;
12 import org.jboss.resteasy.test.exception.resource.ExceptionMapperCustomRuntimeResource;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.Assert;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.WebTarget;
22 import javax.ws.rs.core.Response;
23
24 /**
25 * @tpSubChapter Resteasy-client
26 * @tpChapter Integration tests
27 * @tpSince RESTEasy 3.0.16
28 * @tpTestCaseDetails Regression test for RESTEASY-421
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class ExceptionMapperCustomRuntimeExceptionTest {
33
34 @Deployment
35 public static Archive<?> createTestArchive() {
36 WebArchive war = TestUtil.prepareArchive(ExceptionMapperCustomRuntimeExceptionTest.class.getSimpleName());
37 war.addClass(ExceptionMapperCustomRuntimeException.class);
38 return TestUtil.finishContainerPrepare(war, null, ExceptionMapperCustomRuntimeCustomMapper.class,
39 ExceptionMapperCustomRuntimeResource.class, ExceptionMapperCustomRuntimeMapper.class);
40 }
41
42 /**
43 * @tpTestDetails Check ExceptionMapper for Custom RuntimeException. Check the response contains headers and entity
44 * from custom exception mapper. Using Resteasy client.
45 * @tpSince RESTEasy 3.0.16
46 */
47 @Test
48 public void testMapperWithResteasyClient() throws Exception {
49 ResteasyClient client = new ResteasyClientBuilder().build();
50 WebTarget base = client.target(PortProviderUtil.generateURL("/test", ExceptionMapperCustomRuntimeExceptionTest.class.getSimpleName()));
51 Response response = base.request().get();
52 Assert.assertEquals(Response.Status.PRECONDITION_FAILED.getStatusCode(), response.getStatus());
53 Assert.assertEquals("Wrong headers", response.getHeaders().getFirst("custom"), "header");
54 Assert.assertEquals("The response doesn't contain the entity from custom exception mapper",
55 "My custom message", response.readEntity(String.class));
56
57 response.close();
58 client.close();
59 }
60
61 /**
62 * @tpTestDetails Check ExceptionMapper for Custom RuntimeException. Check the response contains headers and entity
63 * from custom exception mapper. Using ClientRequest/ClientResponse.
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testMapperWithClientRequest() throws Exception {
68 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/test" , ExceptionMapperCustomRuntimeExceptionTest.class.getSimpleName()));
69 ClientResponse<String> response = request.get(String.class);
70 Assert.assertEquals(Response.Status.PRECONDITION_FAILED.getStatusCode(), response.getStatus());
71 Assert.assertEquals("Wrong headers", response.getHeaders().getFirst("custom"), "header");
72 Assert.assertEquals("The response doesn't contain the entity from custom exception mapper",
73 "My custom message", response.getEntity());
74
75 response.close();
76 }
77 }
+0
-106
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/ExceptionMapperInjectionTest.java less more
0 package org.jboss.resteasy.test.exception;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.exception.resource.ExceptionMapperCustomRuntimeException;
8 import org.jboss.resteasy.test.exception.resource.ExceptionMapperInjectionCustomMapper;
9 import org.jboss.resteasy.test.exception.resource.ExceptionMapperInjectionCustomSimpleMapper;
10 import org.jboss.resteasy.test.exception.resource.ExceptionMapperInjectionException;
11 import org.jboss.resteasy.test.exception.resource.ExceptionMapperInjectionNotFoundMapper;
12 import org.jboss.resteasy.test.exception.resource.ExceptionMapperInjectionResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.AfterClass;
19 import org.junit.Assert;
20 import org.junit.BeforeClass;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.WebTarget;
25 import javax.ws.rs.core.Response;
26
27 /**
28 * @tpSubChapter Resteasy-client
29 * @tpChapter Integration tests
30 * @tpSince RESTEasy 3.0.16
31 * @tpTestCaseDetails ExceptionMapper testing. Regression test for RESTEASY-300 and RESTEASY-396
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class ExceptionMapperInjectionTest {
36
37 static ResteasyClient client;
38
39 @Deployment
40 public static Archive<?> createTestArchive() {
41 WebArchive war = TestUtil.prepareArchive(ExceptionMapperInjectionTest.class.getSimpleName());
42 war.addClass(ExceptionMapperCustomRuntimeException.class);
43 war.addClass(ExceptionMapperInjectionException.class);
44 return TestUtil.finishContainerPrepare(war, null, ExceptionMapperInjectionCustomMapper.class,
45 ExceptionMapperInjectionCustomSimpleMapper.class, ExceptionMapperInjectionNotFoundMapper.class,
46 ExceptionMapperInjectionResource.class);
47 }
48
49 @BeforeClass
50 public static void init() {
51 client = new ResteasyClientBuilder().build();
52 }
53
54 @AfterClass
55 public static void after() throws Exception {
56 client.close();
57 }
58
59 public String generateUrl(String path) {
60 return PortProviderUtil.generateURL(path, ExceptionMapperInjectionTest.class.getSimpleName());
61 }
62
63 /**
64 * @tpTestDetails Check non-existent path
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testNotFound() throws Exception {
69 WebTarget base = client.target(generateUrl("/test/nonexistent"));
70 Response response = base.request().get();
71
72 Assert.assertEquals(HttpResponseCodes.SC_HTTP_VERSION_NOT_SUPPORTED, response.getStatus());
73
74 response.close();
75 }
76
77 /**
78 * @tpTestDetails Check correct path
79 * @tpSince RESTEasy 3.0.16
80 */
81 @Test
82 public void testMapper() throws Exception {
83 WebTarget base = client.target(generateUrl("/test"));
84 Response response = base.request().get();
85
86 Assert.assertEquals(Response.Status.PRECONDITION_FAILED.getStatusCode(), response.getStatus());
87
88 response.close();
89 }
90
91 /**
92 * @tpTestDetails Check correct path, no content is excepted
93 * @tpSince RESTEasy 3.0.16
94 */
95 @Test
96 public void testMapper2() throws Exception {
97 WebTarget base = client.target(generateUrl("/test/null"));
98 Response response = base.request().get();
99
100 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
101
102 response.close();
103 }
104
105 }
+0
-120
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/ExceptionMapperTest.java less more
0 package org.jboss.resteasy.test.exception;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.exception.resource.ExceptionMapperAbstractExceptionMapper;
6 import org.jboss.resteasy.test.exception.resource.ExceptionMapperMyCustomException;
7 import org.jboss.resteasy.test.exception.resource.ExceptionMapperMyCustomExceptionMapper;
8 import org.jboss.resteasy.test.exception.resource.ExceptionMapperMyCustomSubException;
9 import org.jboss.resteasy.test.exception.resource.ExceptionMapperResource;
10 import org.jboss.resteasy.test.exception.resource.ExceptionMapperWebAppExceptionMapper;
11 import org.jboss.resteasy.test.exception.resource.NotFoundExceptionMapper;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.util.Types;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Test;
19 import org.junit.Assert;
20 import org.junit.AfterClass;
21 import org.junit.BeforeClass;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Client;
25 import javax.ws.rs.client.ClientBuilder;
26 import javax.ws.rs.core.Response;
27 import javax.ws.rs.ext.ExceptionMapper;
28 import java.lang.reflect.Type;
29
30 /**
31 * @tpSubChapter Resteasy-client
32 * @tpChapter Integration tests
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class ExceptionMapperTest {
38
39 static Client client;
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(ExceptionMapperTest.class.getSimpleName());
44 war.addClasses(ExceptionMapperAbstractExceptionMapper.class);
45 return TestUtil.finishContainerPrepare(war, null, ExceptionMapperResource.class, ExceptionMapperWebAppExceptionMapper.class,
46 ExceptionMapperMyCustomExceptionMapper.class, ExceptionMapperMyCustomException.class,
47 ExceptionMapperMyCustomSubException.class, NotFoundExceptionMapper.class);
48 }
49
50 private String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, ExceptionMapperTest.class.getSimpleName());
52 }
53
54 @BeforeClass
55 public static void setup() {
56 client = ClientBuilder.newClient();
57 }
58
59 @AfterClass
60 public static void close() {
61 client.close();
62 }
63
64 /**
65 * @tpTestDetails Client sends GET request to the server, which causes application custom exception being thrown, this
66 * exception is caught by application provided ExceptionMapper. The application provides two providers for mapping
67 * exceptions. General RuntimeException mapping and MyCustomException mapping which extends the RuntimeException.
68 * @tpPassCrit The more specific MyCustomException mapping will be used.
69 * @tpSince RESTEasy 3.0.16
70 */
71 @Test
72 public void testCustomExceptionsUsed() {
73 Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ExceptionMapperMyCustomExceptionMapper.class, ExceptionMapper.class)[0];
74 Assert.assertEquals(ExceptionMapperMyCustomException.class, exceptionType);
75 Response response = client.target(generateURL("/resource/custom")).request().get();
76 Assert.assertNotEquals("General RuntimeException mapper was used instead of more specific one"
77 , HttpResponseCodes.SC_NOT_ACCEPTABLE, response.getStatus());
78 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
79 Assert.assertEquals("custom", response.readEntity(String.class));
80 }
81
82 /**
83 * @tpTestDetails Client sends GET request to the server, which causes WebapplicationException being thrown, this
84 * exception is caught by application provided ExceptionMapper
85 * @tpPassCrit Application provided ExceptionMapper serves the exception and creates response with ACCEPTED status
86 * @tpSince RESTEasy 3.0.16
87 */
88 @Test
89 public void testWAEResponseUsed() {
90 Response response = client.target(generateURL("/resource/responseok")).request().get();
91 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
92 Assert.assertEquals("hello", response.readEntity(String.class));
93 }
94
95 /**
96 * @tpTestDetails Client sends GET request to the server, which causes the subclass of an exception
97 * which has an ExceptionMapper to be thrown. This subclass exception is caught by application provided ExceptionMapper
98 * @tpPassCrit Application provided ExceptionMapper serves the exception and creates response with ACCEPTED status
99 * @tpSince RESTEasy 3.0.20
100 */
101 @Test
102 public void testCustomSubExceptionsUsed() {
103 Response response = client.target(generateURL("/resource/sub")).request().get();
104 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
105 Assert.assertEquals("custom", response.readEntity(String.class));
106 }
107
108 /**
109 * @tpTestDetails Client sends GET request to a nonexistent resource, which causes a NotFoundException to be thrown.
110 * The NotFoundException is caught by the application provided NotFoundExceptionMapper, which sends a 410 status.
111 * @tpSince RESTEasy 3.0.20
112 */
113 @Test
114 public void testNotFoundExceptionMapping() {
115 Response response = client.target(generateURL("/bogus")).request().get();
116 Assert.assertEquals(410, response.getStatus());
117 response.close();
118 }
119 }
+0
-55
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/ExceptionMapperWebRuntimeExceptionTest.java less more
0 package org.jboss.resteasy.test.exception;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.exception.resource.ExceptionMapperWebRuntimeExceptionMapper;
8 import org.jboss.resteasy.test.exception.resource.ExceptionMapperWebRuntimeExceptionResource;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.WebTarget;
18 import javax.ws.rs.core.Response;
19
20 /**
21 * @tpSubChapter Resteasy-client
22 * @tpChapter Integration tests
23 * @tpSince RESTEasy 3.0.16
24 * @tpTestCaseDetails Regression test for RESTEASY-595
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class ExceptionMapperWebRuntimeExceptionTest {
29
30 @Deployment
31 public static Archive<?> createTestArchive() {
32 WebArchive war = TestUtil.prepareArchive(ExceptionMapperWebRuntimeExceptionTest.class.getSimpleName());
33 return TestUtil.finishContainerPrepare(war, null, ExceptionMapperWebRuntimeExceptionMapper.class,
34 ExceptionMapperWebRuntimeExceptionResource.class);
35 }
36
37 /**
38 * @tpTestDetails Check ExceptionMapper for WebApplicationException
39 * @tpSince RESTEasy 3.0.16
40 */
41 @Test
42 public void testWebAPplicationException() throws Exception {
43 ResteasyClient client = new ResteasyClientBuilder().build();
44 WebTarget base = client.target(PortProviderUtil.generateURL("/test", ExceptionMapperWebRuntimeExceptionTest.class.getSimpleName()));
45 Response response = base.request().get();
46
47 Assert.assertEquals(Response.Status.PRECONDITION_FAILED.getStatusCode(), response.getStatus());
48 Assert.assertEquals("Wrong headers", response.getHeaders().getFirst("custom"), "header");
49
50 response.close();
51 client.close();
52 }
53
54 }
+0
-69
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/WebApplicationExceptionTest.java less more
0 package org.jboss.resteasy.test.exception;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.exception.resource.WebApplicationExceptionResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.WebTarget;
18 import javax.ws.rs.core.Response;
19
20 /**
21 * @tpSubChapter Exceptions
22 * @tpChapter Integration tests
23 * @tpTestCaseDetails Test for javax.ws.rs.WebApplicationException class
24 * @tpSince RESTEasy 3.0.16
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class WebApplicationExceptionTest {
29
30 @Deployment
31 public static Archive<?> createTestArchive() {
32 WebArchive war = TestUtil.prepareArchive(WebApplicationExceptionTest.class.getSimpleName());
33 return TestUtil.finishContainerPrepare(war, null, WebApplicationExceptionResource.class);
34 }
35
36 private String generateURL(String path) {
37 return PortProviderUtil.generateURL(path, WebApplicationExceptionTest.class.getSimpleName());
38 }
39
40 private void basicTest(String path, int code) {
41 ResteasyClient client = new ResteasyClientBuilder().build();
42 WebTarget base = client.target(generateURL(path));
43 Response response = base.request().get();
44 Assert.assertEquals(code, response.getStatus());
45 response.close();
46 client.close();
47 }
48
49 /**
50 * @tpTestDetails Test for exception without error entity
51 * @tpSince RESTEasy 3.0.16
52 */
53 @Test
54 public void testException() {
55 basicTest("/exception", HttpResponseCodes.SC_UNAUTHORIZED);
56 }
57
58 /**
59 * @tpTestDetails Test for exception with error entity.
60 * Regression test for RESTEASY-24
61 * @tpSince RESTEasy 3.0.16
62 */
63 @Test
64 public void testExceptionWithEntity() {
65 basicTest("/exception/entity", HttpResponseCodes.SC_UNAUTHORIZED);
66 }
67
68 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/AbstractMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4
5 public abstract class AbstractMapper<E extends Throwable> implements ExceptionMapper<E> {
6
7 @Override
8 public Response toResponse(final E exception) {
9 final Response.ResponseBuilder builder = Response.ok();
10
11 handleError(builder, exception);
12
13 return builder.build();
14 }
15
16 protected abstract void handleError(final Response.ResponseBuilder builder, E e);
17 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/AbstractMapperDefault.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.MediaType;
3 import javax.ws.rs.core.Response;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class AbstractMapperDefault extends AbstractMapper<RuntimeException> {
8 @Override
9 protected void handleError(final Response.ResponseBuilder builder, final RuntimeException e) {
10 builder.entity("default").type(MediaType.TEXT_HTML_TYPE);
11 }
12 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/AbstractMapperException.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 public class AbstractMapperException extends RuntimeException {
3 public AbstractMapperException(final String message) {
4 super(message);
5 }
6 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/AbstractMapperMyCustom.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.MediaType;
3 import javax.ws.rs.core.Response;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class AbstractMapperMyCustom extends AbstractMapper<AbstractMapperException> {
8 @Override
9 protected void handleError(final Response.ResponseBuilder builder, final AbstractMapperException e) {
10 builder.entity("custom").type(MediaType.TEXT_HTML_TYPE);
11 }
12 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/AbstractMapperResource.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 @Path("resource")
6 public class AbstractMapperResource {
7 @GET
8 @Path("custom")
9 public String custom() throws Throwable {
10 throw new AbstractMapperException("hello");
11 }
12 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionHandlingProvider.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class ExceptionHandlingProvider implements ExceptionMapper<Exception> {
8 public Response toResponse(Exception exception) {
9 return Response.serverError().entity("Expected exception raised").build();
10 }
11 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionHandlingResource.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;
4
5 @Path("/")
6 public class ExceptionHandlingResource {
7 @Path("test")
8 @POST
9 public void post() throws Exception {
10 throw new Exception("test");
11 }
12 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperAbstractExceptionMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4
5 public abstract class ExceptionMapperAbstractExceptionMapper<E extends Throwable> implements ExceptionMapper<E> {
6
7 @Override
8 public Response toResponse(final E exception) {
9 final Response.ResponseBuilder builder = Response.ok();
10 handleError(builder, exception);
11 return builder.build();
12 }
13
14 protected abstract void handleError(final Response.ResponseBuilder builder, E e);
15 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperApplicationRuntimeCustomMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import org.jboss.resteasy.spi.ApplicationException;
3
4 import javax.ws.rs.core.Response;
5 import javax.ws.rs.ext.ExceptionMapper;
6
7 public class ExceptionMapperApplicationRuntimeCustomMapper implements ExceptionMapper<ApplicationException> {
8 public Response toResponse(ApplicationException exception) {
9 return Response.status(Response.Status.PRECONDITION_FAILED).build();
10 }
11 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperApplicationRuntimeMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4
5 public class ExceptionMapperApplicationRuntimeMapper implements ExceptionMapper<RuntimeException> {
6 public Response toResponse(RuntimeException exception) {
7 return Response.serverError().build();
8 }
9 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperApplicationRuntimeResource.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/test")
7 public class ExceptionMapperApplicationRuntimeResource {
8 @GET
9 @Produces("text/plain")
10 public String get() {
11 throw new ExceptionMapperCustomRuntimeException();
12 }
13 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperCustomRuntimeCustomMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4
5 public class ExceptionMapperCustomRuntimeCustomMapper implements ExceptionMapper<ExceptionMapperCustomRuntimeException> {
6 public Response toResponse(ExceptionMapperCustomRuntimeException exception) {
7 return Response.status(Response.Status.PRECONDITION_FAILED).header("custom", "header").entity("My custom message").build();
8 }
9 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperCustomRuntimeException.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 public class ExceptionMapperCustomRuntimeException extends RuntimeException {
3 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperCustomRuntimeMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4
5 public class ExceptionMapperCustomRuntimeMapper implements ExceptionMapper<RuntimeException> {
6 public Response toResponse(RuntimeException exception) {
7 return Response.serverError().build();
8 }
9 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperCustomRuntimeResource.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/test")
7 public class ExceptionMapperCustomRuntimeResource {
8 @GET
9 @Produces("text/plain")
10 public String get() {
11 throw new ExceptionMapperCustomRuntimeException();
12 }
13 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperInjectionCustomMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.core.Context;
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.Request;
7 import javax.ws.rs.core.Response;
8 import javax.ws.rs.core.Variant;
9 import javax.ws.rs.ext.ExceptionMapper;
10 import java.util.ArrayList;
11
12 public class ExceptionMapperInjectionCustomMapper implements ExceptionMapper<ExceptionMapperCustomRuntimeException> {
13
14 private static Logger logger = Logger.getLogger(ExceptionMapperInjectionCustomMapper.class);
15
16 @Context
17 Request request;
18
19 public Response toResponse(ExceptionMapperCustomRuntimeException exception) {
20 logger.info("Method: " + request.getMethod());
21
22 ArrayList<Variant> list = new ArrayList<Variant>();
23 list.add(new Variant(MediaType.APPLICATION_JSON_TYPE, (String) null, null));
24 request.selectVariant(list);
25 return Response.status(Response.Status.PRECONDITION_FAILED).build();
26 }
27 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperInjectionCustomSimpleMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4
5 public class ExceptionMapperInjectionCustomSimpleMapper implements ExceptionMapper<ExceptionMapperInjectionException> {
6 public Response toResponse(ExceptionMapperInjectionException exception) {
7 return null;
8 }
9 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperInjectionException.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 public class ExceptionMapperInjectionException extends RuntimeException {
3 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperInjectionNotFoundMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.util.HttpResponseCodes;
4
5 import javax.ws.rs.NotFoundException;
6 import javax.ws.rs.core.Context;
7 import javax.ws.rs.core.HttpHeaders;
8 import javax.ws.rs.core.Response;
9 import javax.ws.rs.ext.ExceptionMapper;
10
11 public class ExceptionMapperInjectionNotFoundMapper implements
12 ExceptionMapper<NotFoundException> {
13 private static Logger logger = Logger.getLogger(ExceptionMapperInjectionNotFoundMapper.class);
14
15 @Context
16 HttpHeaders httpHeaders;
17
18 public Response toResponse(NotFoundException exception) {
19 logger.info(String.format("Request headers: %s", httpHeaders.getRequestHeaders()));
20 logger.info("Exception is mapped!");
21 return Response.status(HttpResponseCodes.SC_HTTP_VERSION_NOT_SUPPORTED).build();
22 }
23 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperInjectionResource.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/test")
7 public class ExceptionMapperInjectionResource {
8 @GET
9 @Produces("text/plain")
10 public String get() {
11 throw new ExceptionMapperCustomRuntimeException();
12 }
13
14 @Path("/null")
15 @GET
16 @Produces("text/plain")
17 public String getNull() {
18 throw new ExceptionMapperInjectionException();
19 }
20 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperMyCustomException.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 public class ExceptionMapperMyCustomException extends RuntimeException {
3 public ExceptionMapperMyCustomException(final String message) {
4 super(message);
5 }
6 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperMyCustomExceptionMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.MediaType;
3 import javax.ws.rs.core.Response;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class ExceptionMapperMyCustomExceptionMapper extends ExceptionMapperAbstractExceptionMapper<ExceptionMapperMyCustomException> {
8 @Override
9 protected void handleError(final Response.ResponseBuilder builder, final ExceptionMapperMyCustomException e) {
10 builder.entity("custom").type(MediaType.TEXT_HTML_TYPE);
11 }
12 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperMyCustomSubException.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 public class ExceptionMapperMyCustomSubException extends ExceptionMapperMyCustomException {
3
4 private static final long serialVersionUID = 1L;
5
6 public ExceptionMapperMyCustomSubException(final String message) {
7 super(message);
8 }
9 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperResource.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.WebApplicationException;
5 import javax.ws.rs.core.Response;
6
7 @Path("resource")
8 public class ExceptionMapperResource {
9 @GET
10 @Path("responseok")
11 public String responseOk() {
12 Response r = Response.ok("hello").build();
13 throw new WebApplicationException(r);
14 }
15
16 @GET
17 @Path("custom")
18 public String custom() throws Throwable {
19 throw new ExceptionMapperMyCustomException("hello");
20 }
21
22 @GET
23 @Path("sub")
24 public String sub() throws Throwable {
25 throw new ExceptionMapperMyCustomSubException("sub");
26 }
27 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperRuntimeExceptionMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class ExceptionMapperRuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {
8
9 @Override
10 public Response toResponse(RuntimeException exception) {
11 return Response.status(Response.Status.NOT_ACCEPTABLE).build();
12 }
13 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperWebAppExceptionMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.Response;
4 import javax.ws.rs.ext.ExceptionMapper;
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 public class ExceptionMapperWebAppExceptionMapper implements ExceptionMapper<WebApplicationException> {
9
10 @Override
11 public Response toResponse(WebApplicationException exception) {
12 // When not found, i.e. url is wrong, one get also
13 // WebApplicationException
14 if (exception.getClass() != WebApplicationException.class) {
15 return exception.getResponse();
16 }
17 return Response.status(Response.Status.ACCEPTED).build();
18 }
19
20 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperWebRuntimeExceptionMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.Response;
4 import javax.ws.rs.ext.ExceptionMapper;
5
6 public class ExceptionMapperWebRuntimeExceptionMapper implements ExceptionMapper<WebApplicationException> {
7 public Response toResponse(WebApplicationException exception) {
8 return Response.status(Response.Status.PRECONDITION_FAILED).header("custom", "header").build();
9 }
10 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/ExceptionMapperWebRuntimeExceptionResource.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.WebApplicationException;
6
7 @Path("/test")
8 public class ExceptionMapperWebRuntimeExceptionResource {
9 @GET
10 @Produces("text/plain")
11 public String get() {
12 throw new WebApplicationException(401);
13 }
14
15 @GET
16 @Path("failure")
17 @Produces("text/plain")
18 public String getFailure() {
19 return "hello";
20 }
21 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/NotFoundExceptionMapper.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import javax.ws.rs.NotFoundException;
3 import javax.ws.rs.core.Response;
4 import javax.ws.rs.ext.ExceptionMapper;
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 public class NotFoundExceptionMapper implements ExceptionMapper<NotFoundException>
9 {
10 public Response toResponse(NotFoundException exception)
11 {
12 return Response.status(410).build();
13 }
14 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/exception/resource/WebApplicationExceptionResource.java less more
0 package org.jboss.resteasy.test.exception.resource;
1
2 import org.jboss.resteasy.util.HttpResponseCodes;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.Response;
8
9 @Path("/")
10 public class WebApplicationExceptionResource {
11 @Path("/exception")
12 @GET
13 public Response get() throws WebApplicationException {
14 throw new WebApplicationException(Response.status(HttpResponseCodes.SC_UNAUTHORIZED).build());
15 }
16
17 @Path("/exception/entity")
18 @GET
19 public Response getEntity() throws WebApplicationException {
20 throw new WebApplicationException(Response.status(HttpResponseCodes.SC_UNAUTHORIZED).entity("error").build());
21 }
22 }
+0
-301
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/AtomComplexModelTest.java less more
0 package org.jboss.resteasy.test.providers.atom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.plugins.providers.atom.Content;
10 import org.jboss.resteasy.plugins.providers.atom.Entry;
11 import org.jboss.resteasy.plugins.providers.atom.Person;
12 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelArchived;
13 import org.jboss.resteasy.test.providers.atom.resource.AtomAssetMetadata;
14 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelAtomAssetMetadataDecorators;
15 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelAtomAssetMetadtaProcessor;
16 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelCategories;
17 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelCheckinComment;
18 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelCreated;
19 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelDisabled;
20 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelEntryResource;
21 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelFormat;
22 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelNote;
23 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelState;
24 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelUuid;
25 import org.jboss.resteasy.test.providers.atom.resource.AtomComplexModelVersionNumber;
26 import org.jboss.resteasy.util.HttpResponseCodes;
27 import org.jboss.resteasy.utils.PortProviderUtil;
28 import org.jboss.resteasy.utils.TestUtil;
29 import org.jboss.shrinkwrap.api.Archive;
30 import org.jboss.shrinkwrap.api.asset.StringAsset;
31 import org.jboss.shrinkwrap.api.spec.WebArchive;
32 import org.junit.After;
33 import org.junit.Assert;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.UriBuilder;
41 import javax.xml.bind.JAXBContext;
42 import javax.xml.bind.Marshaller;
43 import javax.xml.bind.Unmarshaller;
44 import java.io.DataOutputStream;
45 import java.io.StringReader;
46 import java.io.StringWriter;
47 import java.io.Writer;
48 import java.net.HttpURLConnection;
49 import java.net.URI;
50 import java.net.URL;
51 import java.util.Date;
52
53 import static junit.framework.TestCase.assertEquals;
54 import static org.junit.Assert.assertNotNull;
55
56 /**
57 * @tpSubChapter Atom provider
58 * @tpChapter Integration tests
59 * @tpTestCaseDetails Check complex model with Atom Provider
60 * @tpSince RESTEasy 3.0.16
61 */
62 @RunWith(Arquillian.class)
63 @RunAsClient
64 public class AtomComplexModelTest {
65
66 static ResteasyClient client;
67
68 @Deployment
69 public static Archive<?> deploy() {
70 WebArchive war = TestUtil.prepareArchive(AtomComplexModelTest.class.getSimpleName());
71 war.addClasses(AtomComplexModelArchived.class,
72 AtomAssetMetadata.class,
73 AtomComplexModelAtomAssetMetadataDecorators.class,
74 AtomComplexModelAtomAssetMetadtaProcessor.class,
75 AtomComplexModelCategories.class,
76 AtomComplexModelCheckinComment.class,
77 AtomComplexModelCreated.class,
78 AtomComplexModelDisabled.class,
79 AtomComplexModelEntryResource.class,
80 AtomComplexModelFormat.class,
81 AtomComplexModelNote.class,
82 AtomComplexModelState.class,
83 AtomComplexModelUuid.class,
84 AtomComplexModelVersionNumber.class);
85 return TestUtil.finishContainerPrepare(war, null, AtomComplexModelEntryResource.class);
86 }
87
88 @Before
89 public void init() {
90 client = new ResteasyClientBuilder().build();
91 }
92
93 @After
94 public void after() throws Exception {
95 client.close();
96 }
97
98 private String generateURL(String path) {
99 return PortProviderUtil.generateURL(path, AtomComplexModelTest.class.getSimpleName());
100 }
101
102 /**
103 * @tpTestDetails Check complex type
104 * @tpSince RESTEasy 3.0.16
105 */
106 @Test
107 public void testComplexType() throws Exception {
108 URI baseUri = new URI("resteasy-test");
109
110 Entry entry = new Entry();
111 entry.setTitle("testtitle");
112 entry.setSummary("testdesc");
113 entry.setPublished(new Date());
114 entry.getAuthors().add(new Person("testperson"));
115 entry.setId(baseUri);
116
117 AtomAssetMetadata atomAssetMetadata = entry.getAnyOtherJAXBObject(AtomAssetMetadata.class);
118 if (atomAssetMetadata == null) {
119 atomAssetMetadata = new AtomAssetMetadata();
120 }
121 atomAssetMetadata.setArchived(false);
122 atomAssetMetadata.setUuid("testuuid");
123 atomAssetMetadata.setCategories(new String[]{"a", "b", "c"});
124
125 entry.setAnyOtherJAXBObject(atomAssetMetadata);
126
127 Content content = new Content();
128 content.setSrc(UriBuilder.fromUri(baseUri).path("binary").build());
129 content.setType(MediaType.APPLICATION_OCTET_STREAM_TYPE);
130 entry.setContent(content);
131
132 Class[] classes = new Class[]{AtomAssetMetadata.class, Entry.class};
133 JAXBContext jaxbContext = JAXBContext.newInstance(classes);
134
135 Marshaller marshaller = jaxbContext.createMarshaller();
136
137 Writer xmlWriter = new StringWriter();
138 marshaller.marshal(entry, xmlWriter);
139 String xmlOut = xmlWriter.toString();
140
141 Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
142 StringReader xmlReader = new StringReader(xmlOut);
143
144 Entry newEntry = (Entry) unmarshaller.unmarshal(xmlReader);
145 atomAssetMetadata = newEntry.getAnyOtherJAXBObject(AtomAssetMetadata.class);
146 assertNotNull("Metadata of complex type is null", atomAssetMetadata);
147 assertNotNull("Categories from metadata is missing", atomAssetMetadata.getCategories());
148 }
149
150 /**
151 * @tpTestDetails Check old client
152 * @tpSince RESTEasy 3.0.16
153 */
154 @Test
155 public void testOldClient() throws Exception {
156 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
157 "<entry xmlns=\"http://www.w3.org/2005/Atom\">" +
158 "<title>testCreatePackageFromAtom7</title>" +
159 "<summary>desc for testCreatePackageFromAtom</summary>" +
160 "<metadata xmlns=\"\"><categories><value>c1</value></categories> <note><value>meta</value> </note></metadata>" +
161 "</entry>";
162
163 {
164 URL url = new URL(generateURL("/entry"));
165 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
166 connection.setRequestMethod("POST");
167 connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
168 connection.setRequestProperty("Content-Type", MediaType.APPLICATION_ATOM_XML);
169 connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length));
170 connection.setUseCaches(false);
171 connection.setDoInput(true);
172 connection.setDoOutput(true);
173
174 //Send request
175 DataOutputStream wr = new DataOutputStream(
176 connection.getOutputStream());
177 wr.writeBytes(xml);
178 wr.flush();
179 wr.close();
180
181 assertEquals(HttpResponseCodes.SC_OK, connection.getResponseCode());
182 }
183
184 {
185 ClientRequest request = new ClientRequest(generateURL("/entry2"));
186 request.header("Accept", MediaType.APPLICATION_ATOM_XML);
187 request.header("Content-Type", MediaType.APPLICATION_ATOM_XML);
188 ClientResponse<Entry> response = request.get(Entry.class);
189 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
190
191 assertNotNull("Wrong content of response", response.getEntity().getAnyOtherJAXBObject(AtomAssetMetadata.class));
192 }
193
194 {
195 URL url = new URL(generateURL("/entry3"));
196 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
197 connection.setRequestMethod("POST");
198 connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
199 connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML);
200 connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length));
201 connection.setUseCaches(false);
202 connection.setDoInput(true);
203 connection.setDoOutput(true);
204
205 //Send request
206 DataOutputStream wr = new DataOutputStream(
207 connection.getOutputStream());
208 wr.writeBytes(xml);
209 wr.flush();
210 wr.close();
211
212 assertEquals(HttpResponseCodes.SC_OK, connection.getResponseCode());
213 }
214
215 {
216 ClientRequest request = new ClientRequest(generateURL("/entry4"));
217 request.header("Accept", MediaType.APPLICATION_XML);
218 request.header("Content-Type", MediaType.APPLICATION_XML);
219 ClientResponse<Entry> response = request.get(Entry.class);
220 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
221 assertNotNull("Wrong content of response", response.getEntity().getAnyOtherJAXBObject(AtomAssetMetadata.class));
222 }
223 }
224
225 /**
226 * @tpTestDetails Check new client
227 * @tpSince RESTEasy 3.0.16
228 */
229 @Test
230 public void testNewClient() throws Exception {
231 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
232 "<entry xmlns=\"http://www.w3.org/2005/Atom\">" +
233 "<title>testCreatePackageFromAtom7</title>" +
234 "<summary>desc for testCreatePackageFromAtom</summary>" +
235 "<metadata xmlns=\"\"><categories><value>c1</value></categories> <note><value>meta</value> </note></metadata>" +
236 "</entry>";
237
238 {
239 URL url = new URL(generateURL("/entry"));
240 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
241 connection.setRequestMethod("POST");
242 connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
243 connection.setRequestProperty("Content-Type", MediaType.APPLICATION_ATOM_XML);
244 connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length));
245 connection.setUseCaches(false);
246 connection.setDoInput(true);
247 connection.setDoOutput(true);
248
249 //Send request
250 DataOutputStream wr = new DataOutputStream(
251 connection.getOutputStream());
252 wr.writeBytes(xml);
253 wr.flush();
254 wr.close();
255
256 assertEquals(HttpResponseCodes.SC_OK, connection.getResponseCode());
257 }
258
259 {
260 Response response = client.target(generateURL("/entry2")).request()
261 .header("Accept", MediaType.APPLICATION_ATOM_XML)
262 .header("Content-Type", MediaType.APPLICATION_ATOM_XML)
263 .get();
264 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
265 assertNotNull("Wrong content of response", response.readEntity(Entry.class).getAnyOtherJAXBObject(AtomAssetMetadata.class));
266 response.close();
267 }
268
269 {
270 URL url = new URL(generateURL("/entry3"));
271 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
272 connection.setRequestMethod("POST");
273 connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
274 connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML);
275 connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length));
276 connection.setUseCaches(false);
277 connection.setDoInput(true);
278 connection.setDoOutput(true);
279
280 //Send request
281 DataOutputStream wr = new DataOutputStream(
282 connection.getOutputStream());
283 wr.writeBytes(xml);
284 wr.flush();
285 wr.close();
286
287 assertEquals(HttpResponseCodes.SC_OK, connection.getResponseCode());
288 }
289
290 {
291 Response response = client.target(generateURL("/entry4")).request()
292 .header("Accept", MediaType.APPLICATION_XML)
293 .header("Content-Type", MediaType.APPLICATION_XML)
294 .get();
295 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
296 assertNotNull("Wrong content of response", response.readEntity(Entry.class).getAnyOtherJAXBObject(AtomAssetMetadata.class));
297 response.close();
298 }
299 }
300 }
+0
-245
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/AtomProviderTest.java less more
0 package org.jboss.resteasy.test.providers.atom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.plugins.providers.atom.Entry;
9 import org.jboss.resteasy.plugins.providers.atom.Feed;
10 import org.jboss.resteasy.plugins.providers.atom.Link;
11 import org.jboss.resteasy.plugins.providers.atom.Person;
12 import org.jboss.resteasy.test.providers.atom.resource.AtomProviderResource;
13 import org.jboss.resteasy.test.providers.atom.resource.AtomProviderCustomer;
14 import org.jboss.resteasy.test.providers.atom.resource.AtomProviderDataCollectionRecord;
15 import org.jboss.resteasy.test.providers.atom.resource.ObjectFactory;
16 import org.jboss.resteasy.util.HttpResponseCodes;
17 import org.jboss.resteasy.utils.PortProviderUtil;
18 import org.jboss.resteasy.utils.TestUtil;
19 import org.jboss.shrinkwrap.api.Archive;
20 import org.jboss.shrinkwrap.api.spec.WebArchive;
21 import org.junit.Test;
22 import org.junit.Assert;
23 import org.junit.Before;
24 import org.junit.After;
25 import org.junit.runner.RunWith;
26
27 import javax.ws.rs.Consumes;
28 import javax.ws.rs.GET;
29 import javax.ws.rs.POST;
30 import javax.ws.rs.Path;
31 import javax.ws.rs.Produces;
32 import javax.ws.rs.client.WebTarget;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.Response;
35 import java.net.URI;
36
37
38 /**
39 * @tpSubChapter Atom provider
40 * @tpChapter Integration tests
41 * @tpSince RESTEasy 3.0.16
42 */
43 @RunWith(Arquillian.class)
44 @RunAsClient
45 public class AtomProviderTest {
46
47 @Path("atom")
48 public interface AtomProviderResourceInterface {
49 @POST
50 @Path("feed")
51 @Consumes("application/atom+xml")
52 @Produces("application/atom+xml")
53 Feed postFeed(String feed);
54
55 @GET
56 @Path("xmltype")
57 @Produces("application/atom+xml")
58 Entry getXmlType();
59
60 }
61
62 protected static final Logger logger = Logger.getLogger(AtomProviderTest.class.getName());
63
64 static ResteasyClient client;
65
66 @Deployment
67 public static Archive<?> deploy() {
68 WebArchive war = TestUtil.prepareArchive(AtomProviderTest.class.getSimpleName());
69 war.addClass(AtomProviderTest.class);
70 return TestUtil.finishContainerPrepare(war, null, AtomProviderResource.class, AtomProviderCustomer.class,
71 AtomProviderDataCollectionRecord.class, ObjectFactory.class);
72 }
73
74 @Before
75 public void init() {
76 client = new ResteasyClientBuilder().build();
77 }
78
79 @After
80 public void after() throws Exception {
81 client.close();
82 }
83
84 private String generateURL(String path) {
85 return PortProviderUtil.generateURL(path, AtomProviderTest.class.getSimpleName());
86 }
87
88 private static final String RFC_COMPLEX_XML = " <atom:feed xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:ns3=\"http://jboss.org/Customer\">\n"
89 + " <atom:title type=\"text\">dive into mark</atom:title>\n"
90 + " <atom:subtitle type=\"html\">\n"
91 + " A &lt;em&gt;lot&lt;/em&gt; of effort\n"
92 + " went into making this effortless\n"
93 + " </atom:subtitle>\n"
94 + " <atom:updated>2005-07-31T12:29:29Z</atom:updated>\n"
95 + " <atom:id>tag:example.org,2003:3</atom:id>\n"
96 + " <atom:link rel=\"alternate\" type=\"text/html\"\n"
97 + " hreflang=\"en\" href=\"http://example.org/\"/>\n"
98 + " <atom:link rel=\"self\" type=\"application/atom+xml\"\n"
99 + " href=\"http://example.org/feed.atom\"/>\n"
100 + " <atom:rights>Copyright (c) 2003, Mark Pilgrim</atom:rights>\n"
101 + " <atom:generator uri=\"http://www.example.com/\" version=\"1.0\">\n"
102 + " Example Toolkit\n"
103 + " </atom:generator>\n"
104 + " <atom:entry>\n"
105 + " <atom:title>Atom draft-07 snapshot</atom:title>\n"
106 + " <atom:link rel=\"alternate\" type=\"text/html\"\n"
107 + " href=\"http://example.org/2005/04/02/atom\"/>\n"
108 + " <atom:link rel=\"enclosure\" type=\"audio/mpeg\" length=\"1337\"\n"
109 + " href=\"http://example.org/audio/ph34r_my_podcast.mp3\"/>\n"
110 + " <atom:id>tag:example.org,2003:3.2397</atom:id>\n"
111 + " <atom:updated>2005-07-31T12:29:29Z</atom:updated>\n"
112 + " <atom:published>2003-12-13T08:29:29-04:00</atom:published>\n"
113 + " <atom:author>\n"
114 + " <atom:name>Mark Pilgrim</atom:name>\n"
115 + " <atom:uri>http://example.org/</atom:uri>\n"
116 + " <atom:email>f8dy@example.com</atom:email>\n"
117 + " </atom:author>\n"
118 + " <atom:contributor>\n"
119 + " <atom:name>Sam Ruby</atom:name>\n"
120 + " </atom:contributor>\n"
121 + " <atom:contributor>\n"
122 + " <atom:name>Joe Gregorio</atom:name>\n"
123 + " </atom:contributor>\n"
124 + " <atom:content type=\"application/xml\" xml:lang=\"en\"\n"
125 + " xml:base=\"http://diveintomark.org/\" >\n"
126 + " <ns3:customer>\n"
127 + " <name>bill</name>\n"
128 + " </ns3:customer>\n"
129 + " </atom:content>\n" + " </atom:entry>\n" + " </atom:feed>";
130
131 public static void assertFeed(Feed feed) throws Exception {
132 Assert.assertEquals("dive into mark", feed.getTitle());
133 Assert.assertTrue(feed.getSubtitle().indexOf("effortless") > -1);
134 Assert.assertEquals(feed.getRights(), "Copyright (c) 2003, Mark Pilgrim");
135 Assert.assertEquals(feed.getGenerator().getUri(), new URI("http://www.example.com/"));
136 Assert.assertEquals(feed.getGenerator().getVersion(), "1.0");
137 Assert.assertEquals(feed.getGenerator().getText().trim(), "Example Toolkit");
138 Assert.assertNotNull(feed.getUpdated());
139 Assert.assertEquals(feed.getId().toString(), "tag:example.org,2003:3");
140 Link alternate = feed.getLinkByRel("alternate");
141 Assert.assertNotNull(alternate);
142 Assert.assertEquals(alternate.getType(), MediaType.valueOf("text/html"));
143 Assert.assertEquals(alternate.getHreflang(), "en");
144 Assert.assertEquals(alternate.getHref(), new URI("http://example.org/"));
145 Link self = feed.getLinkByRel("self");
146 Assert.assertNotNull(self);
147 Assert.assertEquals(self.getType(), MediaType.APPLICATION_ATOM_XML_TYPE);
148 Assert.assertEquals(self.getHreflang(), null);
149 Assert.assertEquals(self.getHref(), new URI("http://example.org/feed.atom"));
150
151 Assert.assertEquals(1, feed.getEntries().size());
152 Entry entry = feed.getEntries().get(0);
153 Assert.assertEquals("Atom draft-07 snapshot", entry.getTitle());
154 alternate = entry.getLinkByRel("alternate");
155 Assert.assertNotNull(alternate);
156 Assert.assertEquals(alternate.getType(), MediaType.valueOf("text/html"));
157 Assert.assertEquals(alternate.getHref(), new URI("http://example.org/2005/04/02/atom"));
158 Link enclosure = entry.getLinkByRel("enclosure");
159 Assert.assertNotNull(enclosure);
160 Assert.assertEquals(enclosure.getType(), MediaType.valueOf("audio/mpeg"));
161 Assert.assertEquals(enclosure.getLength(), "1337");
162 Assert.assertEquals(enclosure.getHref(), new URI(
163 "http://example.org/audio/ph34r_my_podcast.mp3"));
164 Assert.assertEquals(entry.getId(), new URI("tag:example.org,2003:3.2397"));
165 Assert.assertNotNull(entry.getUpdated());
166 Assert.assertNotNull(entry.getPublished());
167 Person author = entry.getAuthors().get(0);
168 Assert.assertEquals(author.getName(), "Mark Pilgrim");
169 Assert.assertEquals(author.getUri(), new URI("http://example.org/"));
170 Assert.assertEquals(author.getEmail(), "f8dy@example.com");
171 Assert.assertEquals(entry.getContributors().get(0).getName(), "Sam Ruby");
172 Assert.assertEquals(entry.getContributors().get(1).getName(), "Joe Gregorio");
173 Assert.assertEquals(entry.getContent().getType(), MediaType.APPLICATION_XML_TYPE);
174 Assert.assertEquals(entry.getContent().getLanguage(), "en");
175 Assert.assertEquals(entry.getContent().getBase(), new URI("http://diveintomark.org/"));
176 logger.info(entry.getContent().getElement().getNodeName());
177 logger.info(entry.getContent().getElement().getNamespaceURI());
178 AtomProviderCustomer cust = entry.getContent().getJAXBObject(AtomProviderCustomer.class);
179 Assert.assertEquals(cust.getName(), "bill");
180
181 }
182
183 /**
184 * @tpTestDetails Client sends GET request for atom Feed xml annotated resource. It is asserted that response contains fields
185 * from original request.
186 * in the second case multiple json entities as String.
187 * @tpPassCrit The resource returns json entities in correct format
188 * @tpSince RESTEasy 3.0.16
189 */
190 @Test
191 public void testAtomFeed() throws Exception {
192 WebTarget target = client.target(generateURL("/atom/feed"));
193 Response response = target.request().get();
194 String stringResponse = response.readEntity(String.class);
195 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
196 logger.info(stringResponse);
197
198 AtomProviderResourceInterface proxy = client.target(generateURL("")).proxy(AtomProviderResourceInterface.class);
199 Feed feed = proxy.postFeed(RFC_COMPLEX_XML);
200 assertFeed(feed);
201 }
202
203 /**
204 * @tpTestDetails Client sends GET request for atom Entry xml annotated resource.
205 * @tpPassCrit The response is successful
206 * @tpSince RESTEasy 3.0.16
207 */
208 @Test
209 public void testAtomEntry() throws Exception {
210 WebTarget target = client.target(generateURL("/atom/entry"));
211 Response response = target.request().get();
212 String stringResponse = response.readEntity(String.class);
213 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
214 logger.info(stringResponse);
215 }
216
217 /**
218 * @tpTestDetails Client sends GET request for atom Entry with xml object.
219 * @tpPassCrit The response header contains "application/atom+xml" content-type
220 * @tpInfo JBEAP-1048
221 * @tpSince RESTEasy 3.0.16
222 */
223 @Test
224 public void testHeaderContentType() throws Exception {
225 WebTarget target = client.target(generateURL("/atom/xmltype"));
226 Response response = target.request().get();
227 logger.info(response.getHeaders().getFirst("Content-Type"));
228 Assert.assertEquals("application/atom+xml", response.getHeaders().getFirst("Content-Type"));
229 }
230
231 /**
232 * @tpTestDetails Client sends GET request for atom Entry with xml object.
233 * @tpPassCrit The response entity Entry contains AtomProviderDataCollectionRecord which contains correct value.
234 * @tpInfo JBEAP-1048
235 * @tpSince RESTEasy 3.0.16
236 */
237 @Test
238 public void testXmlType() throws Exception {
239 AtomProviderResourceInterface proxy = client.target(generateURL("")).proxy(AtomProviderResourceInterface.class);
240 Entry entry = proxy.getXmlType();
241 AtomProviderDataCollectionRecord record = entry.getContent().getJAXBObject(AtomProviderDataCollectionRecord.class);
242 Assert.assertEquals(record.getCollectedData(), "hello world");
243 }
244 }
+0
-99
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/JAXBContextFinderTest.java less more
0 package org.jboss.resteasy.test.providers.atom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.plugins.providers.atom.Entry;
10 import org.jboss.resteasy.plugins.providers.atom.Feed;
11 import org.jboss.resteasy.test.providers.atom.resource.JAXBContextFinderAtomServer;
12 import org.jboss.resteasy.test.providers.atom.resource.JAXBContextFinderCustomerAtom;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.core.Response;
25 import java.lang.reflect.Field;
26 import java.util.Iterator;
27
28 /**
29 * @tpSubChapter Atom provider
30 * @tpChapter Integration tests
31 * @tpTestCaseDetails Test integration of atom provider and JAXB Context finder
32 * @tpSince RESTEasy 3.0.16
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class JAXBContextFinderTest {
37
38 static ResteasyClient client;
39
40 @Deployment
41 public static Archive<?> deploy() {
42 WebArchive war = TestUtil.prepareArchive(JAXBContextFinderTest.class.getSimpleName());
43 war.addClass(JAXBContextFinderCustomerAtom.class);
44 return TestUtil.finishContainerPrepare(war, null, JAXBContextFinderAtomServer.class);
45 }
46
47 @Before
48 public void init() {
49 client = new ResteasyClientBuilder().build();
50 }
51
52 @After
53 public void after() throws Exception {
54 client.close();
55 }
56
57 private String generateURL(String path) {
58 return PortProviderUtil.generateURL(path, JAXBContextFinderTest.class.getSimpleName());
59 }
60
61 /**
62 * @tpTestDetails Test old client
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void testAtomFeedOldClient() throws Exception {
67 ClientRequest request = new ClientRequest(generateURL("/atom/feed"));
68 ClientResponse<Feed> response = request.get(Feed.class);
69 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
70 Feed feed = response.getEntity();
71 Iterator<Entry> it = feed.getEntries().iterator();
72 Entry entry1 = it.next();
73 Entry entry2 = it.next();
74 Field field = Entry.class.getDeclaredField("finder");
75 field.setAccessible(true);
76 Assert.assertNotNull("First feet is not correct", field.get(entry1));
77 Assert.assertEquals("Second feet is not correct", field.get(entry1), field.get(entry2));
78 }
79
80 /**
81 * @tpTestDetails Test new client
82 * @tpSince RESTEasy 3.0.16
83 */
84 @Test
85 public void testAtomFeedNewClient() throws Exception {
86 Response response = client.target(generateURL("/atom/feed")).request().get();
87 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
88 Feed feed = response.readEntity(Feed.class);
89 Iterator<Entry> it = feed.getEntries().iterator();
90 Entry entry1 = it.next();
91 Entry entry2 = it.next();
92 Field field = Entry.class.getDeclaredField("finder");
93 field.setAccessible(true);
94 Assert.assertNotNull("First feet is not correct", field.get(entry1));
95 Assert.assertEquals("Second feet is not correct", field.get(entry1), field.get(entry2));
96 response.close();
97 }
98 }
+0
-83
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/LinkTest.java less more
0 package org.jboss.resteasy.test.providers.atom;
1
2 import static org.hamcrest.CoreMatchers.containsString;
3
4 import javax.ws.rs.core.Response;
5
6 import org.jboss.arquillian.container.test.api.Deployment;
7 import org.jboss.arquillian.container.test.api.RunAsClient;
8 import org.jboss.arquillian.junit.Arquillian;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
10 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
11 import org.jboss.resteasy.test.providers.atom.resource.LinkProduct;
12 import org.jboss.resteasy.test.providers.atom.resource.LinkProductService;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.After;
18 import org.junit.Assert;
19 import org.junit.Before;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23
24 /**
25 * @tpSubChapter Atom provider
26 * @tpChapter Integration tests
27 * @tpTestCaseDetails Test for org.jboss.resteasy.plugins.providers.atom.Link class
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class LinkTest {
33
34 static ResteasyClient client;
35
36 @Deployment
37 public static Archive<?> deploy() {
38 WebArchive war = TestUtil.prepareArchive(LinkTest.class.getSimpleName());
39 war.addClass(LinkProduct.class);
40 return TestUtil.finishContainerPrepare(war, null, LinkProductService.class);
41 }
42
43 @Before
44 public void init() {
45 client = new ResteasyClientBuilder().build();
46 }
47
48 @After
49 public void after() throws Exception {
50 client.close();
51 }
52
53 private String generateURL(String path) {
54 return PortProviderUtil.generateURL(path, LinkTest.class.getSimpleName());
55 }
56
57 /**
58 * @tpTestDetails Test response as java custom object
59 * @tpSince RESTEasy 3.0.16
60 */
61 @Test
62 public void testRelativeLinkProductOutput() throws Exception {
63 Response response = client.target(generateURL("/products/333")).request().get();
64 LinkProduct product = response.readEntity(LinkProduct.class);
65 Assert.assertEquals("/LinkTest/products/333/self", product.getLinks().get(0).getHref().getPath());
66 Assert.assertEquals("/LinkTest/products", product.getLinks().get(1).getHref().getPath());
67 response.close();
68 }
69
70 /**
71 * @tpTestDetails Test response as XML String
72 * @tpSince RESTEasy 3.0.16
73 */
74 @Test
75 public void testRelativeLinkStringOutput() throws Exception {
76 Response response = client.target(generateURL("/products/333")).request().get();
77 String stringResponse = response.readEntity(String.class);
78 Assert.assertThat("Wrong link in response", stringResponse, containsString("/LinkTest/products/333/self\""));
79 Assert.assertThat("Wrong link in response", stringResponse, containsString("/LinkTest/products\""));
80 response.close();
81 }
82 }
+0
-162
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomAssetMetadata.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6 import javax.xml.bind.annotation.XmlSeeAlso;
7 import java.util.Date;
8
9 @XmlRootElement(name = "metadata")
10 @XmlAccessorType(XmlAccessType.FIELD)
11 @XmlSeeAlso({AtomComplexModelCategories.class})
12 public class AtomAssetMetadata {
13
14 @XmlElement
15 private AtomComplexModelUuid uuid;
16 @XmlElement
17 private AtomComplexModelCategories categories;
18 @XmlElement
19 private AtomComplexModelNote note;
20 @XmlElement
21 private AtomComplexModelCreated created;
22 @XmlElement
23 private AtomComplexModelFormat format;
24 @XmlElement
25 private AtomComplexModelDisabled disabled;
26 @XmlElement
27 private AtomComplexModelState state;
28 @XmlElement
29 private AtomComplexModelVersionNumber versionNumber;
30 @XmlElement
31 private AtomComplexModelCheckinComment checkinComment;
32 @XmlElement
33 private AtomComplexModelArchived archived;
34
35 public String getUuid() {
36 return uuid != null ? uuid.getValue() : null;
37 }
38
39 public void setUuid(String uuid) {
40 if (this.uuid == null) {
41 this.uuid = new AtomComplexModelUuid();
42 }
43 this.uuid.setValue(uuid);
44 }
45
46 public String[] getCategories() {
47 return categories != null ? categories.getValues() : null;
48 }
49
50 public void setCategories(String[] categories) {
51 if (this.categories == null ) {
52 this.categories = new AtomComplexModelCategories();
53 }
54 this.categories.setValue(categories);
55 }
56
57 public String getNote() {
58 return note != null ? note.getValue() : null;
59 }
60
61 public void setNote(String note) {
62 if (this.note == null) {
63 this.note = new AtomComplexModelNote();
64 }
65 this.note.setValue(note);
66 }
67
68 public Date getCreated() {
69 return created != null ? created.getValue() : null;
70 }
71
72 public void setCreated(Date created) {
73 if (this.created == null) {
74 this.created = new AtomComplexModelCreated();
75 }
76 this.created.setValue(created);
77 }
78
79 public String getFormat() {
80 return format != null ? format.getValue() : null;
81 }
82
83 public void setFormat(String format) {
84 if (this.format == null) {
85 this.format = new AtomComplexModelFormat();
86 }
87 this.format.setValue(format);
88 }
89
90 public boolean getDisabled() {
91 return disabled != null ? disabled.getValue() : false;
92 }
93
94 public void setDisabled(boolean disabled) {
95 if (this.disabled == null) {
96 this.disabled = new AtomComplexModelDisabled();
97 }
98 this.disabled.setValue(disabled);
99 }
100
101 public String getState() {
102 return state != null ? state.getValue() : null;
103 }
104
105 public void setState(String state) {
106 if (this.state == null) {
107 this.state = new AtomComplexModelState();
108 }
109 this.state.setValue(state);
110 }
111
112 public long getVersionNumber() {
113 return versionNumber != null ? versionNumber.getValue() : -1L;
114 }
115
116 public void setVersionNumber(long versionNumber) {
117 if (this.versionNumber == null) {
118 this.versionNumber = new AtomComplexModelVersionNumber();
119 }
120 this.versionNumber.setValue(versionNumber);
121 }
122
123 public String getCheckinComment() {
124 return checkinComment != null ? checkinComment.getValue() : null;
125 }
126
127 public void setCheckinComment(String checkinComment) {
128 if (this.checkinComment == null ) {
129 this.checkinComment = new AtomComplexModelCheckinComment();
130 }
131 this.checkinComment.setValue(checkinComment);
132 }
133
134 public boolean isArchived() {
135 return archived != null ? archived.getValue() : false;
136 }
137
138 public void setArchived(boolean archived) {
139 if (this.archived == null) {
140 this.archived = new AtomComplexModelArchived();
141 }
142 this.archived.setValue(archived);
143 }
144
145 @Override
146 public String toString() {
147 return "AtomAssetMetadata{" +
148 "uuid=" + uuid +
149 ", categories=" + categories +
150 ", note=" + note +
151 ", created=" + created +
152 ", format=" + format +
153 ", disabled=" + disabled +
154 ", state=" + state +
155 ", versionNumber=" + versionNumber +
156 ", checkinComment=" + checkinComment +
157 ", archived=" + archived +
158 '}';
159 }
160
161 }
+0
-40
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelArchived.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18
19 import javax.xml.bind.annotation.XmlAccessType;
20 import javax.xml.bind.annotation.XmlAccessorType;
21 import javax.xml.bind.annotation.XmlElement;
22 import javax.xml.bind.annotation.XmlRootElement;
23
24 @XmlRootElement(name = "archived")
25 @XmlAccessorType(XmlAccessType.FIELD)
26 public class AtomComplexModelArchived {
27
28 @XmlElement
29 private boolean value;
30
31 public boolean getValue() {
32 return value;
33 }
34
35 public void setValue(boolean archived) {
36 value = archived;
37 }
38
39 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelAtomAssetMetadataDecorators.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import org.jboss.resteasy.annotations.Decorator;
3
4 import javax.xml.bind.Marshaller;
5 import java.lang.annotation.ElementType;
6 import java.lang.annotation.Retention;
7 import java.lang.annotation.RetentionPolicy;
8 import java.lang.annotation.Target;
9
10 @Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
11 @Retention(RetentionPolicy.RUNTIME)
12 @Decorator(processor = AtomComplexModelAtomAssetMetadtaProcessor.class, target = Marshaller.class)
13 public @interface AtomComplexModelAtomAssetMetadataDecorators {
14 }
+0
-32
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelAtomAssetMetadtaProcessor.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import org.jboss.resteasy.logging.Logger;
3 import org.jboss.resteasy.plugins.providers.atom.Entry;
4 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
5
6 import javax.ws.rs.core.MediaType;
7 import javax.xml.bind.JAXBContext;
8 import javax.xml.bind.Marshaller;
9 import java.io.PrintWriter;
10 import java.io.StringWriter;
11 import java.lang.annotation.Annotation;
12
13 public class AtomComplexModelAtomAssetMetadtaProcessor implements DecoratorProcessor<Marshaller, AtomComplexModelAtomAssetMetadataDecorators> {
14
15 private static Logger logger = Logger.getLogger(AtomComplexModelAtomAssetMetadtaProcessor.class);
16
17 @Override
18 public Marshaller decorate(Marshaller target, AtomComplexModelAtomAssetMetadataDecorators annotation, Class type, Annotation[] annotations, MediaType mediaType) {
19 Class[] classes = new Class[]{AtomAssetMetadata.class, Entry.class};
20 try {
21 JAXBContext jaxbContext = JAXBContext.newInstance(classes);
22 return jaxbContext.createMarshaller();
23 } catch (Exception e) {
24
25 StringWriter errors = new StringWriter();
26 e.printStackTrace(new PrintWriter(errors));
27 logger.error(errors.toString());
28 }
29 return null;
30 }
31 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelCategories.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18 import javax.xml.bind.annotation.XmlAccessType;
19 import javax.xml.bind.annotation.XmlAccessorType;
20 import javax.xml.bind.annotation.XmlElement;
21 import javax.xml.bind.annotation.XmlRootElement;
22
23 @XmlRootElement(name = "categories")
24 @XmlAccessorType(XmlAccessType.FIELD)
25 public class AtomComplexModelCategories {
26
27 @XmlElement(name = "value")
28 private String[] values;
29
30 public String[] getValues() {
31 return values;
32 }
33
34 public void setValue(String[] categories) {
35 values = categories;
36 }
37
38 }
+0
-40
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelCheckinComment.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18
19 import javax.xml.bind.annotation.XmlAccessType;
20 import javax.xml.bind.annotation.XmlAccessorType;
21 import javax.xml.bind.annotation.XmlElement;
22 import javax.xml.bind.annotation.XmlRootElement;
23
24 @XmlRootElement(name = "checkinComment")
25 @XmlAccessorType(XmlAccessType.FIELD)
26 public class AtomComplexModelCheckinComment {
27
28 @XmlElement
29 private String value;
30
31 public String getValue() {
32 return value; //To change body of created methods use File | Settings | File Templates.
33 }
34
35 public void setValue(String checkin) {
36 value = checkin;
37 }
38
39 }
+0
-41
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelCreated.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18
19 import javax.xml.bind.annotation.XmlAccessType;
20 import javax.xml.bind.annotation.XmlAccessorType;
21 import javax.xml.bind.annotation.XmlElement;
22 import javax.xml.bind.annotation.XmlRootElement;
23 import java.util.Date;
24
25 @XmlRootElement(name = "created")
26 @XmlAccessorType(XmlAccessType.FIELD)
27 public class AtomComplexModelCreated {
28
29 @XmlElement
30 private Date value;
31
32 public Date getValue() {
33 return value;
34 }
35
36 public void setValue(Date created) {
37 value = created;
38 }
39
40 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelDisabled.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18 import javax.xml.bind.annotation.XmlAccessType;
19 import javax.xml.bind.annotation.XmlAccessorType;
20 import javax.xml.bind.annotation.XmlElement;
21 import javax.xml.bind.annotation.XmlRootElement;
22
23 @XmlRootElement(name = "disabled")
24 @XmlAccessorType(XmlAccessType.FIELD)
25 public class AtomComplexModelDisabled {
26
27 @XmlElement
28 private boolean value;
29
30 public boolean getValue() {
31 return value;
32 }
33
34 public void setValue(boolean disabled) {
35 value = disabled;
36 }
37
38 }
+0
-114
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelEntryResource.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import org.jboss.resteasy.plugins.providers.atom.Content;
3 import org.jboss.resteasy.plugins.providers.atom.Entry;
4 import org.jboss.resteasy.plugins.providers.atom.Person;
5
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.GET;
8 import javax.ws.rs.POST;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.Produces;
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.core.Context;
13 import javax.ws.rs.core.MediaType;
14 import javax.ws.rs.core.UriBuilder;
15 import javax.ws.rs.core.UriInfo;
16 import java.net.URI;
17 import java.util.Date;
18
19
20 @Path("/")
21 public class AtomComplexModelEntryResource {
22
23 @POST
24 @Path("entry")
25 @Consumes(MediaType.APPLICATION_ATOM_XML)
26 @Produces(MediaType.APPLICATION_ATOM_XML)
27 public AtomAssetMetadata entry(Entry entry, @Context UriInfo uriInfo) {
28 try {
29 AtomAssetMetadata assetMetadata = entry.getAnyOtherJAXBObject(AtomAssetMetadata.class);
30 return assetMetadata;
31 } catch (Exception e) {
32 throw new WebApplicationException(e);
33 }
34 }
35
36
37 @GET
38 @Path("entry2")
39 @Consumes(MediaType.APPLICATION_ATOM_XML)
40 @Produces(MediaType.APPLICATION_ATOM_XML)
41 public Entry entry2(@Context UriInfo uriInfo) {
42 try {
43 return toAssetEntry(uriInfo);
44 } catch (Exception e) {
45 throw new WebApplicationException(e);
46 }
47 }
48
49 @POST
50 @Path("entry3")
51 @Consumes(MediaType.APPLICATION_XML)
52 @Produces(MediaType.APPLICATION_XML)
53 public AtomAssetMetadata entry3(Entry entry, @Context UriInfo uriInfo) {
54 try {
55 AtomAssetMetadata assetMetadata = entry.getAnyOtherJAXBObject(AtomAssetMetadata.class);
56 return assetMetadata;
57 } catch (Exception e) {
58 throw new WebApplicationException(e);
59 }
60 }
61
62
63 @GET
64 @Path("entry4")
65 @AtomComplexModelAtomAssetMetadataDecorators
66 @Consumes(MediaType.APPLICATION_XML)
67 @Produces(MediaType.APPLICATION_XML)
68 public Entry entry4(@Context UriInfo uriInfo) {
69 try {
70 return toAssetEntry(uriInfo);
71 } catch (Exception e) {
72 throw new WebApplicationException(e);
73 }
74 }
75
76
77
78 public Entry toAssetEntry(UriInfo uriInfo) throws Exception {
79 URI baseUri;
80 baseUri = uriInfo.getBaseUriBuilder()
81 .path("packages/{packageName}/assets/{assetName}")
82 .build("testpackageName", "testassetName");
83
84 Entry entry = new Entry();
85 entry.setTitle("testtitle");
86 entry.setSummary("testdesc");
87 entry.setPublished(new Date());
88 entry.setBase(baseUri);
89 entry.getAuthors().add(new Person("testperson"));
90
91 entry.setId(baseUri);
92
93 AtomAssetMetadata atomAssetMetadata = entry.getAnyOtherJAXBObject(AtomAssetMetadata.class);
94 if (atomAssetMetadata == null) {
95 atomAssetMetadata = new AtomAssetMetadata();
96 }
97 atomAssetMetadata.setArchived(false);
98 atomAssetMetadata.setUuid("testuuid");
99
100 entry.setAnyOtherJAXBObject(atomAssetMetadata);
101
102 Content content = new Content();
103 content.setSrc(UriBuilder.fromUri(baseUri).path("binary").build());
104 content.setType(MediaType.APPLICATION_OCTET_STREAM_TYPE);
105
106 entry.setContent(content);
107
108 return entry;
109 }
110
111
112 }
113
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelFormat.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18 import javax.xml.bind.annotation.XmlAccessType;
19 import javax.xml.bind.annotation.XmlAccessorType;
20 import javax.xml.bind.annotation.XmlElement;
21 import javax.xml.bind.annotation.XmlRootElement;
22
23 @XmlRootElement(name = "format")
24 @XmlAccessorType(XmlAccessType.FIELD)
25 public class AtomComplexModelFormat {
26
27 @XmlElement
28 private String value;
29
30 public String getValue() {
31 return value;
32 }
33
34 public void setValue(String format) {
35 value = format;
36 }
37
38 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelNote.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18 import javax.xml.bind.annotation.XmlAccessType;
19 import javax.xml.bind.annotation.XmlAccessorType;
20 import javax.xml.bind.annotation.XmlElement;
21 import javax.xml.bind.annotation.XmlRootElement;
22
23 @XmlRootElement(name = "note")
24 @XmlAccessorType(XmlAccessType.FIELD)
25 public class AtomComplexModelNote {
26
27 @XmlElement
28 private String value;
29
30 public String getValue() {
31 return value;
32 }
33
34 public void setValue(String note) {
35 value = note;
36 }
37
38 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelState.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18 import javax.xml.bind.annotation.XmlAccessType;
19 import javax.xml.bind.annotation.XmlAccessorType;
20 import javax.xml.bind.annotation.XmlElement;
21 import javax.xml.bind.annotation.XmlRootElement;
22
23 @XmlRootElement(name = "state")
24 @XmlAccessorType(XmlAccessType.FIELD)
25 public class AtomComplexModelState {
26
27 @XmlElement
28 private String value;
29
30 public String getValue() {
31 return value;
32 }
33
34 public void setValue(String state) {
35 value = state;
36 }
37
38 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelUuid.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18 import javax.xml.bind.annotation.XmlAccessType;
19 import javax.xml.bind.annotation.XmlAccessorType;
20 import javax.xml.bind.annotation.XmlElement;
21 import javax.xml.bind.annotation.XmlRootElement;
22
23 @XmlRootElement(name = "uuid")
24 @XmlAccessorType(XmlAccessType.FIELD)
25 public class AtomComplexModelUuid {
26
27 @XmlElement
28 private String value;
29
30 public String getValue() {
31 return value;
32 }
33
34 public void setValue(String uuid) {
35 value = uuid;
36 }
37
38 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomComplexModelVersionNumber.java less more
0 /*
1 * Copyright 2012 JBoss Inc
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.jboss.resteasy.test.providers.atom.resource;
17
18 import javax.xml.bind.annotation.XmlAccessType;
19 import javax.xml.bind.annotation.XmlAccessorType;
20 import javax.xml.bind.annotation.XmlElement;
21 import javax.xml.bind.annotation.XmlRootElement;
22
23 @XmlRootElement(name = "versionNumber")
24 @XmlAccessorType(XmlAccessType.FIELD)
25 public class AtomComplexModelVersionNumber {
26
27 @XmlElement
28 private long value;
29
30 public long getValue() {
31 return value;
32 }
33
34 public void setValue(long uuid) {
35 value = uuid;
36 }
37
38 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomProviderCustomer.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "customer", namespace = "http://jboss.org/Customer")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class AtomProviderCustomer {
10 @XmlElement
11 private String name;
12
13 public AtomProviderCustomer() {
14 }
15
16 public AtomProviderCustomer(final String name) {
17 this.name = name;
18 }
19
20 public String getName() {
21 return name;
22 }
23 }
+0
-76
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomProviderDataCollectionRecord.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlType;
6 import javax.xml.datatype.XMLGregorianCalendar;
7
8 /**
9 * <p>
10 * Java class for AtomProviderDataCollectionRecord complex type.
11 * <p>
12 * <p>
13 * The following schema fragment specifies the expected content contained within
14 * this class.
15 * <p>
16 * <p>
17 * <pre>
18 * &lt;complexType name=&quot;AtomProviderDataCollectionRecord&quot;&gt;
19 * &lt;complexContent&gt;
20 * &lt;restriction base=&quot;{http://www.w3.org/2001/XMLSchema}anyType&quot;&gt;
21 * &lt;sequence&gt;
22 * &lt;element name=&quot;timestamp&quot; type=&quot;{http://www.w3.org/2001/XMLSchema}dateTime&quot;/&gt;
23 * &lt;element name=&quot;collectedData&quot; type=&quot;{http://www.w3.org/2001/XMLSchema}string&quot;/&gt;
24 * &lt;/sequence&gt;
25 * &lt;/restriction&gt;
26 * &lt;/complexContent&gt;
27 * &lt;/complexType&gt;
28 * </pre>
29 */
30 @XmlAccessorType(XmlAccessType.FIELD)
31 @XmlType(name = "AtomProviderDataCollectionRecord", propOrder = {"timestamp", "collectedData"})
32 public class AtomProviderDataCollectionRecord {
33
34 @XmlElement(required = true)
35 protected XMLGregorianCalendar timestamp;
36 @XmlElement(required = true)
37 protected String collectedData;
38
39 /**
40 * Gets the value of the timestamp property.
41 *
42 * @return possible object is {@link XMLGregorianCalendar }
43 */
44 public XMLGregorianCalendar getTimestamp() {
45 return timestamp;
46 }
47
48 /**
49 * Sets the value of the timestamp property.
50 *
51 * @param value allowed object is {@link XMLGregorianCalendar }
52 */
53 public void setTimestamp(XMLGregorianCalendar value) {
54 this.timestamp = value;
55 }
56
57 /**
58 * Gets the value of the collectedData property.
59 *
60 * @return possible object is {@link String }
61 */
62 public String getCollectedData() {
63 return collectedData;
64 }
65
66 /**
67 * Sets the value of the collectedData property.
68 *
69 * @param value allowed object is {@link String }
70 */
71 public void setCollectedData(String value) {
72 this.collectedData = value;
73 }
74
75 }
+0
-82
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/AtomProviderResource.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import org.jboss.resteasy.test.providers.atom.AtomProviderTest;
3 import org.jboss.resteasy.plugins.providers.atom.Content;
4 import org.jboss.resteasy.plugins.providers.atom.Entry;
5 import org.jboss.resteasy.plugins.providers.atom.Feed;
6
7 import javax.ws.rs.Path;
8 import javax.ws.rs.GET;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.POST;
11 import javax.ws.rs.Consumes;
12 import javax.ws.rs.core.MediaType;
13
14 @Path("atom")
15 public class AtomProviderResource {
16 @GET
17 @Path("entry")
18 @Produces("application/atom+xml")
19 public Entry getEntry() {
20 Entry entry = new Entry();
21 entry.setTitle("Hello World");
22 Content content = new Content();
23 content.setJAXBObject(new AtomProviderCustomer("bill"));
24 entry.setContent(content);
25 return entry;
26 }
27
28 @GET
29 @Path("feed")
30 @Produces("application/atom+xml")
31 public Feed getFeed() {
32 Feed feed = new Feed();
33 feed.getEntries().add(getEntry());
34 return feed;
35 }
36
37 @GET
38 @Path("text/entry")
39 @Produces("application/atom+xml")
40 public Entry getTextEntry() {
41 Entry entry = new Entry();
42 entry.setTitle("Hello World");
43 Content content = new Content();
44 content.setText("<pre>How are you today?\nNotBad!</pre>");
45 content.setType(MediaType.TEXT_HTML_TYPE);
46 entry.setContent(content);
47 return entry;
48 }
49
50 @GET
51 @Path("text/feed")
52 @Produces("application/atom+xml")
53 public Feed getTextFeed() {
54 Feed feed = new Feed();
55 feed.getEntries().add(getTextEntry());
56 return feed;
57 }
58
59 @POST
60 @Path("feed")
61 @Consumes("application/atom+xml")
62 @Produces("application/atom+xml")
63 public Feed postFeed(Feed feed) throws Exception {
64 AtomProviderTest.assertFeed(feed);
65 return feed;
66 }
67
68 @GET
69 @Path("xmltype")
70 @Produces("application/atom+xml")
71 public Entry getXmlType() {
72 Entry entry = new Entry();
73 entry.setTitle("Hello World");
74 Content content = new Content();
75 AtomProviderDataCollectionRecord record = new AtomProviderDataCollectionRecord();
76 record.setCollectedData("hello world");
77 content.setJAXBObject(record);
78 entry.setContent(content);
79 return entry;
80 }
81 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/JAXBContextFinderAtomServer.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import org.jboss.resteasy.plugins.providers.atom.Entry;
3 import org.jboss.resteasy.plugins.providers.atom.Feed;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import java.net.URISyntaxException;
9
10 @Path("atom")
11 public class JAXBContextFinderAtomServer {
12 @GET
13 @Path("feed")
14 @Produces("application/atom+xml")
15 public Feed getFeed() throws URISyntaxException {
16 Feed feed = new Feed();
17 feed.setTitle("My Feed");
18 Entry entry = new Entry();
19 entry.setTitle("Hello World");
20 entry.setAnyOtherJAXBObject(new JAXBContextFinderCustomerAtom("bill"));
21 feed.getEntries().add(entry);
22 entry = new Entry();
23 entry.setTitle("Hello Uranus");
24 entry.setAnyOtherJAXBObject(new JAXBContextFinderCustomerAtom("bob"));
25 feed.getEntries().add(entry);
26 return feed;
27 }
28 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/JAXBContextFinderCustomerAtom.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 /**
8 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
9 * @version $Revision: 1 $
10 */
11 @XmlRootElement(name = "customer", namespace = "http://jboss.org/Customer")
12 @XmlAccessorType(XmlAccessType.FIELD)
13 public class JAXBContextFinderCustomerAtom {
14 @XmlElement
15 private String name;
16
17 public JAXBContextFinderCustomerAtom() {
18 }
19
20 public JAXBContextFinderCustomerAtom(final String name) {
21 this.name = name;
22 }
23
24 public String getName() {
25 return name;
26 }
27 }
+0
-50
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/LinkProduct.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import org.jboss.resteasy.plugins.providers.atom.Link;
3
4 import javax.xml.bind.annotation.XmlAccessType;
5 import javax.xml.bind.annotation.XmlAccessorType;
6 import javax.xml.bind.annotation.XmlAttribute;
7 import javax.xml.bind.annotation.XmlElement;
8 import javax.xml.bind.annotation.XmlElementRef;
9 import javax.xml.bind.annotation.XmlRootElement;
10 import java.util.ArrayList;
11 import java.util.List;
12
13 /**
14 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
15 * @version $Revision: 1 $
16 */
17 @XmlRootElement(name = "product")
18 @XmlAccessorType(XmlAccessType.PROPERTY)
19 public class LinkProduct {
20 protected int id;
21
22 protected String name;
23
24
25 private ArrayList<Link> linkList = new ArrayList<Link>();
26
27 @XmlAttribute
28 public int getId() {
29 return id;
30 }
31
32 public void setId(int id) {
33 this.id = id;
34 }
35
36 @XmlElement
37 public String getName() {
38 return name;
39 }
40
41 public void setName(String name) {
42 this.name = name;
43 }
44
45 @XmlElementRef
46 public List<Link> getLinks() {
47 return linkList;
48 }
49 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/LinkProductService.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1
2 import org.jboss.resteasy.plugins.providers.atom.BaseLink;
3 import org.jboss.resteasy.plugins.providers.atom.RelativeLink;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import javax.ws.rs.Produces;
9
10 @Path("/products")
11 public class LinkProductService {
12 @GET
13 @Produces("application/xml")
14 @Path("{id}")
15 public LinkProduct getProduct(@PathParam("id") int id) {
16 LinkProduct p = new LinkProduct();
17 p.setId(id);
18 p.setName("iphone");
19 p.getLinks().add(new RelativeLink("self", "/self"));
20 p.getLinks().add(new BaseLink("create", "/products"));
21 return p;
22 }
23 }
+0
-91
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/atom/resource/ObjectFactory.java less more
0 package org.jboss.resteasy.test.providers.atom.resource;
1 import javax.xml.bind.JAXBElement;
2 import javax.xml.bind.annotation.XmlElementDecl;
3 import javax.xml.bind.annotation.XmlRegistry;
4 import javax.xml.datatype.XMLGregorianCalendar;
5 import javax.xml.namespace.QName;
6
7 /**
8 * This object contains factory methods for each Java content interface and Java
9 * element interface generated in the mil.navy.tsts.datacollection.parseRS
10 * package.
11 * <p>
12 * An ObjectFactory allows you to programatically construct new instances of the
13 * Java representation for XML content. The Java representation of XML content
14 * can consist of schema derived interfaces and classes representing the binding
15 * of schema type definitions, element declarations and model groups. Factory
16 * methods for each of these are provided in this class.
17 */
18 @XmlRegistry
19 public class ObjectFactory {
20
21 private static final QName _DataCollectionRecord_QNAME = new QName(
22 "http://www.example.org/DataCollectionPackage", "DataCollectionRecord");
23 private static final QName _SourceID_QNAME = new QName(
24 "http://www.example.org/DataCollectionPackage", "sourceID");
25 private static final QName _Timestamp_QNAME = new QName(
26 "http://www.example.org/DataCollectionPackage", "timestamp");
27 private static final QName _EventID_QNAME = new QName(
28 "http://www.example.org/DataCollectionPackage", "eventID");
29 private static final QName _CollectedData_QNAME = new QName(
30 "http://www.example.org/DataCollectionPackage", "collectedData");
31
32 /**
33 * Create a new ObjectFactory that can be used to create new instances of
34 * schema derived classes for package: mil.navy.tsts.datacollection.parseRS
35 */
36 public ObjectFactory() {
37 }
38
39 /**
40 * Create an instance of {@link AtomProviderDataCollectionRecord }
41 */
42 public AtomProviderDataCollectionRecord createDataCollectionRecord() {
43 return new AtomProviderDataCollectionRecord();
44 }
45
46 /**
47 * Create an instance of {@link JAXBElement }{@code <}
48 * {@link AtomProviderDataCollectionRecord }{@code >}
49 */
50 @XmlElementDecl(namespace = "http://www.example.org/DataCollectionPackage", name = "DataCollectionRecord")
51 public JAXBElement<AtomProviderDataCollectionRecord> createDataCollectionRecord(AtomProviderDataCollectionRecord value) {
52 return new JAXBElement<AtomProviderDataCollectionRecord>(_DataCollectionRecord_QNAME,
53 AtomProviderDataCollectionRecord.class, null, value);
54 }
55
56 /**
57 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}
58 */
59 @XmlElementDecl(namespace = "http://www.example.org/DataCollectionPackage", name = "sourceID")
60 public JAXBElement<String> createSourceID(String value) {
61 return new JAXBElement<String>(_SourceID_QNAME, String.class, null, value);
62 }
63
64 /**
65 * Create an instance of {@link JAXBElement }{@code <}
66 * {@link XMLGregorianCalendar }{@code >}
67 */
68 @XmlElementDecl(namespace = "http://www.example.org/DataCollectionPackage", name = "timestamp")
69 public JAXBElement<XMLGregorianCalendar> createTimestamp(XMLGregorianCalendar value) {
70 return new JAXBElement<XMLGregorianCalendar>(_Timestamp_QNAME, XMLGregorianCalendar.class,
71 null, value);
72 }
73
74 /**
75 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}
76 */
77 @XmlElementDecl(namespace = "http://www.example.org/DataCollectionPackage", name = "eventID")
78 public JAXBElement<String> createEventID(String value) {
79 return new JAXBElement<String>(_EventID_QNAME, String.class, null, value);
80 }
81
82 /**
83 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}
84 */
85 @XmlElementDecl(namespace = "http://www.example.org/DataCollectionPackage", name = "collectedData")
86 public JAXBElement<String> createCollectedData(String value) {
87 return new JAXBElement<String>(_CollectedData_QNAME, String.class, null, value);
88 }
89
90 }
+0
-148
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/CollectionProviderTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.providers.custom.resource.CollectionProviderCollectionWriter;
6 import org.jboss.resteasy.test.providers.custom.resource.CollectionProviderIncorrectCollectionWriter;
7 import org.jboss.resteasy.test.providers.custom.resource.CollectionProviderResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.BeforeClass;
14 import org.junit.Test;
15 import org.junit.AfterClass;
16 import org.junit.Assert;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.Path;
20 import javax.ws.rs.client.Client;
21 import javax.ws.rs.client.ClientBuilder;
22 import javax.ws.rs.core.Response;
23 import java.lang.annotation.Annotation;
24 import java.lang.reflect.Method;
25 import java.lang.reflect.ParameterizedType;
26 import java.lang.reflect.Type;
27 import java.util.LinkedList;
28 import java.util.List;
29
30 /**
31 * @tpSubChapter Resteasy-client
32 * @tpChapter Integration tests
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class CollectionProviderTest {
38
39 public static String getPathValue(Annotation[] annotations) {
40 return getSpecifiedAnnotationValue(annotations, Path.class);
41 }
42
43 @SuppressWarnings("unchecked")
44 public static <T extends Annotation> T getSpecifiedAnnotation(
45 Annotation[] annotations, Class<T> clazz) {
46 T t = null;
47 for (Annotation a : annotations) {
48 if (a.annotationType() == clazz) {
49 t = (T) a;
50 }
51 }
52 return t != null ? t : null;
53 }
54
55 public static <T extends Annotation> String getSpecifiedAnnotationValue(
56 Annotation[] annotations, Class<T> clazz) {
57 T t = getSpecifiedAnnotation(annotations, clazz);
58 try {
59 Method m = clazz.getMethod("value");
60 return (String) m.invoke(t);
61 } catch (Exception e) {
62 return null;
63 }
64 }
65
66 public static boolean checkOther(Class<?> type, Type genericType) {
67 if (!(genericType instanceof ParameterizedType)) {
68 return false;
69 }
70 ParameterizedType pType = (ParameterizedType) genericType;
71 boolean ok = pType.getRawType().equals(LinkedList.class);
72 ok &= pType.getActualTypeArguments()[0].equals(String.class);
73 return ok;
74 }
75
76 public static boolean checkResponseNongeneric(Class<?> type,
77 Type genericType) {
78 boolean ok = genericType.equals(LinkedList.class);
79 ok &= type.equals(LinkedList.class);
80 return ok;
81 }
82
83 public static boolean checkGeneric(Class<?> type, Type genericType) {
84 if (ParameterizedType.class.isInstance(genericType)) {
85 genericType = ((ParameterizedType) genericType).getRawType();
86 }
87 boolean ok = genericType.getClass().equals(List.class)
88 || genericType.equals(LinkedList.class);
89 ok &= type.equals(LinkedList.class);
90 return ok;
91 }
92
93
94 static Client client;
95
96 @BeforeClass
97 public static void before() throws Exception {
98 client = ClientBuilder.newClient();
99 }
100
101 @Deployment
102 public static Archive<?> deploy() {
103 WebArchive war = TestUtil.prepareArchive(CollectionProviderTest.class.getSimpleName());
104 war.addClasses(CollectionProviderTest.class);
105 return TestUtil.finishContainerPrepare(war, null, CollectionProviderResource.class,
106 CollectionProviderIncorrectCollectionWriter.class, CollectionProviderCollectionWriter.class);
107 }
108
109 private String generateURL(String path) {
110 return PortProviderUtil.generateURL(path, CollectionProviderTest.class.getSimpleName());
111 }
112
113 @AfterClass
114 public static void close() {
115 client.close();
116 }
117
118 /**
119 * @tpTestDetails Client sends GET request to the server, server sends LinkedList with String items. Two message
120 * body readers are registered. One always returns isWritable false, so the other one has to be used.
121 * @tpPassCrit Correct MessageBodyReader is used for writing response of the type LinkedList<String>
122 * @tpSince RESTEasy 3.0.16
123 */
124 @Test
125 public void testGenericTypeDefault() {
126 Response response = client.target(generateURL("/resource/response/linkedlist")).request().get();
127 String val = response.readEntity(String.class);
128 Assert.assertEquals("OK", val);
129 }
130
131 /**
132 * @tpTestDetails Client sends GET request to the server, server sends response with GenericEntity of the type
133 * LinkedList with String items. Two message body readers are registered. One always returns isWritable false,
134 * so the other one has to be used.
135 * @tpPassCrit Correct MessageBodyReader is used for writing response with GenericEntity of the type LinkedList<String>
136 * @tpSince RESTEasy 3.0.16
137 */
138 @Test
139 public void testGenericTypeResponse() {
140 Response response = client.target(generateURL("/resource/genericentity/linkedlist")).request().get();
141 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
142 String val = response.readEntity(String.class);
143 Assert.assertEquals("OK", val);
144 }
145
146
147 }
+0
-69
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/CustomProviderPreferenceTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.providers.custom.resource.CustomProviderPreferenceUser;
8 import org.jboss.resteasy.test.providers.custom.resource.CustomProviderPreferenceUserBodyWriter;
9 import org.jboss.resteasy.test.providers.custom.resource.CustomProviderPreferenceUserResource;
10 import org.jboss.resteasy.util.HttpResponseCodes;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.core.Response;
22
23 /**
24 * @tpSubChapter Providers
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Test for custom provider preference.
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class CustomProviderPreferenceTest {
32
33 static ResteasyClient client;
34
35 @Deployment
36 public static Archive<?> createTestArchive() {
37 WebArchive war = TestUtil.prepareArchive(CustomProviderPreferenceTest.class.getSimpleName());
38 war.addClass(CustomProviderPreferenceUser.class);
39 return TestUtil.finishContainerPrepare(war, null, CustomProviderPreferenceUserResource.class,
40 CustomProviderPreferenceUserBodyWriter.class);
41 }
42
43 @Before
44 public void init() {
45 client = new ResteasyClientBuilder().build();
46 }
47
48 @After
49 public void after() throws Exception {
50 client.close();
51 }
52
53 private String generateURL(String path) {
54 return PortProviderUtil.generateURL(path, CustomProviderPreferenceTest.class.getSimpleName());
55 }
56
57 /**
58 * @tpTestDetails Client test.
59 * @tpSince RESTEasy 3.0.16
60 */
61 @Test
62 public void testCustomProviderPreference() throws Exception {
63 Response response = client.target(generateURL("/user")).request().get();
64 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
65 Assert.assertEquals("Wrong content of response", "jharting;email@example.com", response.readEntity(String.class));
66 response.close();
67 }
68 }
+0
-65
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/CustomValueInjectorTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.providers.custom.resource.CustomValueInjectorHello;
8 import org.jboss.resteasy.test.providers.custom.resource.CustomValueInjectorHelloResource;
9 import org.jboss.resteasy.test.providers.custom.resource.CustomValueInjectorInjectorFactoryImpl;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 /**
21 * @tpSubChapter Providers
22 * @tpChapter Integration tests
23 * @tpTestCaseDetails Test for custom value injector.
24 * @tpSince RESTEasy 3.0.16
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class CustomValueInjectorTest {
29
30 static ResteasyClient client;
31
32 @Deployment
33 public static Archive<?> createTestArchive() {
34 WebArchive war = TestUtil.prepareArchive(CustomValueInjectorTest.class.getSimpleName());
35 war.addClass(CustomValueInjectorHello.class);
36 return TestUtil.finishContainerPrepare(war, null, CustomValueInjectorHelloResource.class,
37 CustomValueInjectorInjectorFactoryImpl.class);
38 }
39
40 @Before
41 public void init() {
42 client = new ResteasyClientBuilder().build();
43 }
44
45 @After
46 public void after() throws Exception {
47 client.close();
48 }
49
50 private String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, CustomValueInjectorTest.class.getSimpleName());
52 }
53
54 /**
55 * @tpTestDetails Client test.
56 * @tpSince RESTEasy 3.0.16
57 */
58 @Test
59 public void testCustomInjectorFactory() throws Exception {
60 String result = client.target(generateURL("/")).request().get(String.class);
61 Assert.assertEquals("Response has wrong content", "world", result);
62 }
63
64 }
+0
-91
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/DuplicateProviderRegistrationTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.category.NotForForwardCompatibility;
5 import org.jboss.resteasy.test.providers.custom.resource.DuplicateProviderRegistrationFeature;
6 import org.jboss.resteasy.test.providers.custom.resource.DuplicateProviderRegistrationFilter;
7 import org.jboss.resteasy.test.providers.custom.resource.DuplicateProviderRegistrationInterceptor;
8 import org.jboss.resteasy.utils.TestUtil;
9 import org.jboss.shrinkwrap.api.Archive;
10 import org.jboss.shrinkwrap.api.spec.WebArchive;
11 import org.junit.Assert;
12 import org.junit.Test;
13 import org.junit.experimental.categories.Category;
14 import org.junit.runner.RunWith;
15
16 import javax.ws.rs.client.Client;
17 import javax.ws.rs.client.ClientBuilder;
18 import javax.ws.rs.client.WebTarget;
19 import javax.ws.rs.core.Feature;
20 import javax.ws.rs.ext.ReaderInterceptor;
21
22 /**
23 * @tpSubChapter Providers
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Regression test for JBEAP-4703
26 * @tpSince RESTEasy 3.0.17
27 */
28 @RunWith(Arquillian.class)
29 public class DuplicateProviderRegistrationTest {
30
31 private static final String ERR_MSG = "Wrong cound of RESTEASY002155 warning message";
32 @SuppressWarnings(value = "unchecked")
33 @Deployment
34 public static Archive<?> createTestArchive() {
35 WebArchive war = TestUtil.prepareArchive(DuplicateProviderRegistrationTest.class.getSimpleName());
36 war.addClasses(DuplicateProviderRegistrationFeature.class, DuplicateProviderRegistrationFilter.class,
37 TestUtil.class, DuplicateProviderRegistrationInterceptor.class);
38 war.addClass(NotForForwardCompatibility.class);
39 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
40 }
41
42 private static int getWarningCount() {
43 return TestUtil.getWarningCount("RESTEASY002155", true);
44 }
45
46 /**
47 * @tpTestDetails Basic test
48 * @tpSince RESTEasy 3.0.17
49 */
50 @Test
51 @Category({NotForForwardCompatibility.class})
52 public void testDuplicateProvider() {
53 int initWarningCount = getWarningCount();
54 Client client = ClientBuilder.newClient();
55 try {
56 WebTarget webTarget = client.target("http://www.changeit.com");
57 // DuplicateProviderRegistrationFeature will be registered third on the same webTarget even if
58 // webTarget.getConfiguration().isRegistered(DuplicateProviderRegistrationFeature.class)==true
59 webTarget.register(DuplicateProviderRegistrationFeature.class).register(new DuplicateProviderRegistrationFeature()).register(new DuplicateProviderRegistrationFeature());
60 } finally {
61 client.close();
62 }
63 Assert.assertEquals(ERR_MSG, 2, getWarningCount() - initWarningCount);
64 }
65
66 /**
67 * @tpTestDetails This test is taken from javax.ws.rs.core.Configurable javadoc
68 * @tpSince RESTEasy 3.0.17
69 */
70 @Test
71 @Category({NotForForwardCompatibility.class})
72 public void testFromJavadoc() {
73 int initWarningCount = getWarningCount();
74 Client client = ClientBuilder.newClient();
75 try {
76 WebTarget webTarget = client.target("http://www.changeit.com");
77 webTarget.register(DuplicateProviderRegistrationInterceptor.class, ReaderInterceptor.class);
78 webTarget.register(DuplicateProviderRegistrationInterceptor.class); // Rejected by runtime.
79 webTarget.register(new DuplicateProviderRegistrationInterceptor()); // Rejected by runtime.
80 webTarget.register(DuplicateProviderRegistrationInterceptor.class, 6500); // Rejected by runtime.
81
82 webTarget.register(new DuplicateProviderRegistrationFeature());
83 webTarget.register(DuplicateProviderRegistrationFeature.class); // rejected by runtime.
84 webTarget.register(DuplicateProviderRegistrationFeature.class, Feature.class); // Rejected by runtime.
85 } finally {
86 client.close();
87 }
88 Assert.assertEquals(ERR_MSG, 5, getWarningCount() - initWarningCount);
89 }
90 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/FilterDispatcherUndertowTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import java.net.HttpURLConnection;
3 import java.net.URL;
4
5 import org.jboss.arquillian.container.test.api.Deployment;
6 import org.jboss.arquillian.container.test.api.RunAsClient;
7 import org.jboss.arquillian.junit.Arquillian;
8 import org.jboss.resteasy.test.providers.custom.resource.FilterDispatcherForwardServlet;
9 import org.jboss.resteasy.test.providers.custom.resource.FilterDispatcherServlet;
10 import org.jboss.resteasy.util.HttpResponseCodes;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18 import org.apache.logging.log4j.LogManager;
19 import org.apache.logging.log4j.Logger;
20
21 /**
22 * @tpSubChapter Resteasy-client
23 * @tpChapter Integration tests
24 * @tpTestCaseDetails Regression test for RESTEASY-903
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class FilterDispatcherUndertowTest {
30 private static final Logger logger = LogManager.getLogger(FilterDispatcherUndertowTest.class.getName());
31
32 @Deployment
33 public static Archive<?> createTestArchive() {
34 WebArchive war = TestUtil.prepareArchive(FilterDispatcherUndertowTest.class.getSimpleName());
35 war.addClass(FilterDispatcherForwardServlet.class);
36 war.addClass(FilterDispatcherServlet.class);
37 war.addAsWebInfResource(FilterDispatcherUndertowTest.class.getPackage(), "FilterDispatcherManifestWeb.xml", "web.xml");
38 war.addAsWebInfResource(FilterDispatcherUndertowTest.class.getPackage(), "FilterDispatcherManifest.MF", "MANIFEST.MF");
39 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
40 }
41
42 /**
43 * @tpTestDetails Server should be able to forward a HttpServletRequest/HttpServletResponse captured
44 * using the @Context annotation on a member variables inside a resource class.
45 * @tpPassCrit Response should have code 200.
46 * @tpSince RESTEasy 3.0.16
47 */
48 @Test
49 public void testUndertow() throws Exception {
50 logger.info("starting testUndertow()");
51 URL url = new URL(PortProviderUtil.generateURL("/test", FilterDispatcherUndertowTest.class.getSimpleName()));
52 HttpURLConnection conn = HttpURLConnection.class.cast(url.openConnection());
53 conn.connect();
54 logger.info("Connection status: " + conn.getResponseCode());
55 byte[] b = new byte[16];
56 conn.getInputStream().read(b);
57 logger.info("Response result: " + new String(b));
58 Assert.assertEquals(HttpResponseCodes.SC_OK, conn.getResponseCode());
59 conn.disconnect();
60 }
61 }
62
+0
-58
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/MissingProducerTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.category.NotForForwardCompatibility;
6 import org.jboss.resteasy.utils.TestUtil;
7 import org.jboss.shrinkwrap.api.Archive;
8 import org.jboss.shrinkwrap.api.spec.WebArchive;
9 import org.junit.Assert;
10 import org.junit.Test;
11 import org.junit.experimental.categories.Category;
12 import org.junit.runner.RunWith;
13
14 /**
15 * @tpSubChapter Core
16 * @tpChapter Integration tests
17 * @tpSince RESTEasy 3.0.17
18 * @tpTestCaseDetails Regression test for JBEAP-4719
19 */
20 @RunWith(Arquillian.class)
21 @RunAsClient
22 public class MissingProducerTest {
23 private static final String ERR_MSG = "Warning was not logged";
24 private static int initLogMsg1Count = parseLog1();
25 private static int initLogMsg2Count = parseLog2();
26 private static int initLogMsg3Count = parseLog3();
27
28 private static int parseLog1() {
29 return TestUtil.getWarningCount("RESTEASY002120: ClassNotFoundException: ", false);
30 }
31 private static int parseLog2() {
32 return TestUtil.getWarningCount("Unable to load builtin provider org.jboss.resteasy.Missing from ", false);
33 }
34 private static int parseLog3() {
35 return TestUtil.getWarningCount("classes/META-INF/services/javax.ws.rs.ext.Providers", false);
36 }
37
38 @SuppressWarnings(value = "unchecked")
39 @Deployment
40 public static Archive<?> createTestArchive() {
41 WebArchive war = TestUtil.prepareArchive(MissingProducerTest.class.getSimpleName());
42 war.addAsResource(MissingProducerTest.class.getPackage(), "MissingProducer.Providers", "META-INF/services/javax.ws.rs.ext.Providers");
43 return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
44 }
45
46 /**
47 * @tpTestDetails Check logs for RESTEASY002120 warning message.
48 * @tpSince RESTEasy 3.0.17
49 */
50 @Test
51 @Category({NotForForwardCompatibility.class})
52 public void testMissingProducer() {
53 Assert.assertEquals(ERR_MSG, 1, parseLog1() - initLogMsg1Count);
54 Assert.assertEquals(ERR_MSG, 1, parseLog2() - initLogMsg2Count);
55 Assert.assertEquals(ERR_MSG, 1, parseLog3() - initLogMsg3Count);
56 }
57 }
+0
-88
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/ProviderContextInjectionTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.providers.custom.resource.ProviderContextInjectionAnyExceptionExceptionMapper;
6 import org.jboss.resteasy.test.providers.custom.resource.ProviderContextInjectionEnumContextResolver;
7 import org.jboss.resteasy.test.providers.custom.resource.ProviderContextInjectionEnumProvider;
8 import org.jboss.resteasy.test.providers.custom.resource.ProviderContextInjectionIOExceptionExceptionMapper;
9 import org.jboss.resteasy.test.providers.custom.resource.ProviderContextInjectionResource;
10 import org.jboss.resteasy.test.providers.custom.resource.ProviderContextInjectionTextPlainEnumContextResolver;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.AfterClass;
16 import org.junit.Assert;
17 import org.junit.BeforeClass;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.Client;
22 import javax.ws.rs.client.ClientBuilder;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Resteasy-client
27 * @tpChapter Integration tests
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class ProviderContextInjectionTest {
33
34 static Client client;
35
36 @BeforeClass
37 public static void setup() {
38 client = ClientBuilder.newClient();
39 }
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(ProviderContextInjectionTest.class.getSimpleName());
44 war.addClasses(ProviderContextInjectionEnumProvider.class);
45 return TestUtil.finishContainerPrepare(war, null, ProviderContextInjectionResource.class,
46 ProviderContextInjectionAnyExceptionExceptionMapper.class, ProviderContextInjectionIOExceptionExceptionMapper.class,
47 ProviderContextInjectionEnumContextResolver.class, ProviderContextInjectionTextPlainEnumContextResolver.class);
48 }
49
50 private String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, ProviderContextInjectionTest.class.getSimpleName());
52 }
53
54 @AfterClass
55 public static void close() {
56 client.close();
57 }
58
59 /**
60 * @tpTestDetails Providers are injected into Resource with @Context injection. The resource gets ContextResolver
61 * provider for user defined enum type EnumProvider and verifies that correct application provider was chosen.
62 * @tpPassCrit Correct application provider was chosen
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void isRegisteredWildCardContextResolverTest() {
67 Response response = client.target(generateURL("/resource/isRegisteredContextResolver")).request().get();
68 Assert.assertEquals(200, response.getStatus());
69 response.close();
70 }
71
72
73 /**
74 * @tpTestDetails Providers are injected into Resource with @Context injection. The resource gets ExceptionMapper
75 * provider for RuntimeException and verifies that the correct application provider was chosen.
76 * @tpPassCrit Correct application provider was chosen
77 * @tpSince RESTEasy 3.0.16
78 */
79 @Test
80 public void testExceptionMapped() {
81 Response response = client.target(generateURL("/resource/isRegisteredRuntimeExceptionMapper")).request().get();
82 Assert.assertEquals(200, response.getStatus());
83 response.close();
84 }
85
86
87 }
+0
-203
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/ReaderWriterTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.OperateOnDeployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.resteasy.client.ProxyFactory;
7 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterClient;
11 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterCurlyBraces;
12 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterCustomer;
13 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterCustomerWriter;
14 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterNowhereClient;
15 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterResource;
16 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterSpaces;
17 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterSub;
18 import org.jboss.resteasy.util.HttpResponseCodes;
19 import org.jboss.resteasy.utils.PortProviderUtil;
20 import org.jboss.resteasy.utils.TestUtil;
21 import org.jboss.shrinkwrap.api.Archive;
22 import org.jboss.shrinkwrap.api.spec.WebArchive;
23 import org.junit.AfterClass;
24 import org.junit.Assert;
25 import org.junit.BeforeClass;
26 import org.junit.Test;
27 import org.junit.runner.RunWith;
28
29 import javax.ws.rs.client.WebTarget;
30 import javax.ws.rs.core.Response;
31 import java.net.HttpURLConnection;
32 import java.net.URL;
33
34 /**
35 * @tpSubChapter Providers
36 * @tpChapter Integration tests
37 * @tpTestCaseDetails Regression test for RESTEasy issues
38 * @tpSince RESTEasy 3.0.16
39 */
40 @RunWith(Arquillian.class)
41 @RunAsClient
42 public class ReaderWriterTest {
43 static ResteasyClient client;
44
45 @Deployment(name = "ReaderWriterCustomerWriter")
46 public static Archive<?> deployCustomWriter() {
47 WebArchive war = TestUtil.prepareArchive(ReaderWriterCustomerWriter.class.getSimpleName());
48 war.addClass(ReaderWriterCustomer.class);
49 war.addClass(PortProviderUtil.class);
50 return TestUtil.finishContainerPrepare(war, null, ReaderWriterCustomerWriter.class, ReaderWriterResource.class);
51 }
52
53 @Deployment(name = "ReaderWriterResource")
54 public static Archive<?> deployReaderWriterClass() {
55 WebArchive war = TestUtil.prepareArchive(ReaderWriterResource.class.getSimpleName());
56 war.addClass(PortProviderUtil.class);
57 return TestUtil.finishContainerPrepare(war, null, ReaderWriterResource.class);
58 }
59
60 @Deployment(name = "ReaderWriterSpaces")
61 public static Archive<?> deployReaderWriterSpaces() {
62 WebArchive war = TestUtil.prepareArchive(ReaderWriterSpaces.class.getSimpleName());
63 war.addClass(ReaderWriterSub.class);
64 war.addClass(PortProviderUtil.class);
65 return TestUtil.finishContainerPrepare(war, null, ReaderWriterSpaces.class);
66 }
67
68 @Deployment(name = "ReaderWriterCurlyBraces")
69 public static Archive<?> deployReaderWriterCurlyBraces() {
70 WebArchive war = TestUtil.prepareArchive(ReaderWriterCurlyBraces.class.getSimpleName());
71 war.addClass(PortProviderUtil.class);
72 return TestUtil.finishContainerPrepare(war, null, ReaderWriterCurlyBraces.class);
73 }
74
75
76 @BeforeClass
77 public static void init() {
78 client = new ResteasyClientBuilder().build();
79 }
80
81 @AfterClass
82 public static void close() {
83 client.close();
84 }
85 /**
86 * @tpTestDetails Regression test for RESTEASY-144
87 * @tpSince RESTEasy 3.0.16
88 */
89 @Test
90 public void test144() throws Exception {
91 WebTarget base = client.target(PortProviderUtil.generateURL("/implicit", ReaderWriterCustomerWriter.class.getSimpleName()));
92 Response response = base.request().get();
93 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
94 Assert.assertEquals("application/xml;charset=UTF-8", response.getStringHeaders().getFirst("content-type"));
95 String s = new String(response.readEntity(byte[].class), "US-ASCII");
96 Assert.assertEquals("Response contains wrong content", "<customer><name>bill</name></customer>", s);
97 response.close();
98
99 response = base.request().delete();
100 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
101 response.close();
102
103 ReaderWriterClient proxy = client.target(PortProviderUtil.generateBaseUrl(ReaderWriterCustomerWriter.class.getSimpleName()))
104 .proxy(ReaderWriterClient.class);
105 response = proxy.deleteCustomer();
106 response.close();
107
108 response = proxy.deleteComplex();
109 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
110 response.close();
111 }
112
113 /**
114 * @tpTestDetails Regression test for RESTEASY-61
115 * @tpSince RESTEasy 3.0.16
116 */
117 @Test
118 public void testJdkURLConnection() throws Exception {
119 URL url = new URL(PortProviderUtil.generateURL("/simple", ReaderWriterResource.class.getSimpleName()));
120 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
121 @SuppressWarnings("unused")
122 Object obj = conn.getContent();
123 }
124
125 /**
126 * @tpTestDetails Regression test for RESTEASY-24 and RESTEASY-139
127 * @tpSince RESTEasy 3.0.16
128 */
129 @Test
130 public void test24() throws Exception {
131 WebTarget base = client.target(PortProviderUtil.generateURL("/complex", ReaderWriterResource.class.getSimpleName()));
132 Response response = base.request().get();
133 Assert.assertEquals(HttpResponseCodes.SC_FOUND, response.getStatus());
134 Assert.assertEquals(response.getStringHeaders().getFirst("content-type"), "text/plain;charset=UTF-8");
135 byte[] responseBody = response.readEntity(byte[].class);
136 String responseString = new String(responseBody, "US-ASCII");
137 Assert.assertEquals("Response contains wrong content", "hello world", responseString);
138
139 }
140
141 /**
142 * @tpTestDetails Regression test for RESTEASY-1 and RESTEASY-2
143 * @tpSince RESTEasy 3.0.16
144 */
145 @Test
146 public void test1and2() throws Exception {
147 WebTarget base = client.target(PortProviderUtil.generateURL("/simple", ReaderWriterResource.class.getSimpleName()));
148 Response response = base.request().get();
149 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
150 Assert.assertEquals("text/plain;charset=UTF-8", response.getStringHeaders().getFirst("content-type"));
151 String s = new String(response.readEntity(byte[].class), "US-ASCII");
152 Assert.assertEquals("Response contains wrong content", "hello world", s);
153 }
154
155 /**
156 * @tpTestDetails Test for resource mapped to nowhere using deprecated proxy.
157 * @tpSince RESTEasy 3.0.16
158 */
159 @Test
160 public void testItDeprecatedProxy() throws Exception {
161 ReaderWriterNowhereClient client = ProxyFactory.create(ReaderWriterNowhereClient.class, PortProviderUtil.generateBaseUrl("app"));
162 client.read();
163 }
164
165 /**
166 * @tpTestDetails Test for resource mapped to nowhere using proxy.
167 * @tpSince RESTEasy 3.0.16
168 */
169 @Test
170 public void testItNewProxy() throws Exception {
171 ReaderWriterNowhereClient proxy = ProxyBuilder.builder(ReaderWriterNowhereClient.class,
172 client.target(PortProviderUtil.generateBaseUrl("app"))).build();
173 Response response = proxy.read();
174 response.close();
175 }
176
177 /**
178 * @tpTestDetails Regression test for RESTEASY-212
179 * @tpSince RESTEasy 3.0.16
180 */
181 @Test
182 public void test212() throws Exception {
183 WebTarget base = client.target(PortProviderUtil.generateURL("/spaces/with%20spaces/without", ReaderWriterSpaces.class.getSimpleName()));
184 Response response = base.request().get();
185 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
186 response.close();
187 }
188
189 /**
190 * @tpTestDetails Regression test for RESTEASY-227
191 * @tpSince RESTEasy 3.0.16
192 */
193 @Test
194 @OperateOnDeployment("ReaderWriterCurlyBraces")
195 public void test227() throws Exception {
196 WebTarget base = client.target(PortProviderUtil.generateURL("/curly/abcd", ReaderWriterCurlyBraces.class.getSimpleName()));
197 Response response = base.request().get();
198 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
199 response.close();
200 }
201
202 }
+0
-83
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/ResponseContainerFilterTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.test.providers.custom.resource.ResponseContainerResource;
8 import org.jboss.resteasy.test.providers.custom.resource.ResponseContainerResponseFilter;
9 import org.jboss.resteasy.test.providers.custom.resource.ResponseContainerSecondResponseFilter;
10 import org.jboss.resteasy.test.providers.custom.resource.ResponseContainerTemplateFilter;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.Test;
17 import org.junit.BeforeClass;
18 import org.junit.AfterClass;
19 import org.junit.Assert;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Client;
23 import javax.ws.rs.client.ClientBuilder;
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @tpSubChapter Resteasy-client
30 * @tpChapter Integration tests
31 * @tpSince RESTEasy 3.0.16
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class ResponseContainerFilterTest {
36
37 protected static final Logger logger = LogManager.getLogger(ResponseContainerFilterTest.class.getName());
38
39 static Client client;
40
41 @BeforeClass
42 public static void setup() throws Exception {
43 client = ClientBuilder.newClient();
44 }
45
46 @Deployment
47 public static Archive<?> deploy() {
48 WebArchive war = TestUtil.prepareArchive(ResponseContainerFilterTest.class.getSimpleName());
49 war.addClasses(ResponseContainerTemplateFilter.class);
50 return TestUtil.finishContainerPrepare(war, null, ResponseContainerResource.class,
51 ResponseContainerResponseFilter.class, ResponseContainerSecondResponseFilter.class);
52 }
53
54 private String generateURL(String path) {
55 return PortProviderUtil.generateURL(path, ResponseContainerFilterTest.class.getSimpleName());
56 }
57
58 @AfterClass
59 public static void close() throws Exception {
60 client.close();
61 }
62
63 /**
64 * @tpTestDetails Client sends POST request with it's custom header "OPERATION" specified in it. Server has registered
65 * two ContainerResponseFilters, which have common ancestor and different priority. The filter ResponseFilter
66 * with higher priority should be used here first, because the order of execution for Response filters is descending.
67 * @tpPassCrit The ResponseFilter is used first for processing the response
68 * @tpSince RESTEasy 3.0.16
69 */
70 @Test
71 public void testHasEntity() {
72 Response response = client.target(generateURL("/resource/hasentity")).request("*/*")
73 .header("OPERATION", "hasentity").post(Entity.entity("entity", MediaType.WILDCARD_TYPE));
74 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
75 Assert.assertEquals("The ResponseFilters were used in different order than expected" , MediaType.TEXT_PLAIN_TYPE
76 , response.getMediaType());
77 logger.info(response.readEntity(String.class));
78 response.close();
79
80 }
81
82 }
+0
-96
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/ResponseFilterChangeStatusTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.test.providers.custom.resource.ResponseFilterChangeStatusResource;
8 import org.jboss.resteasy.test.providers.custom.resource.ResponseFilterChangeStatusResponseFilter;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.AfterClass;
15 import org.junit.BeforeClass;
16 import org.junit.Rule;
17 import org.junit.Test;
18 import org.junit.Assert;
19 import org.junit.rules.ExpectedException;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.ProcessingException;
23 import javax.ws.rs.client.Client;
24 import javax.ws.rs.client.ClientBuilder;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @tpSubChapter Resteasy-client
30 * @tpChapter Integration tests
31 * @tpSince RESTEasy 3.0.16
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class ResponseFilterChangeStatusTest {
36
37 protected static final Logger logger = LogManager.getLogger(ResponseFilterChangeStatusTest.class.getName());
38
39 @Rule
40 public ExpectedException thrown = ExpectedException.none();
41
42 static Client client;
43
44 @BeforeClass
45 public static void setup() throws Exception {
46 client = ClientBuilder.newClient();
47 }
48
49 @Deployment
50 public static Archive<?> deploy() {
51 WebArchive war = TestUtil.prepareArchive(ResponseFilterChangeStatusTest.class.getSimpleName());
52 return TestUtil.finishContainerPrepare(war, null, ResponseFilterChangeStatusResource.class, ResponseFilterChangeStatusResponseFilter.class);
53 }
54
55 private String generateURL(String path) {
56 return PortProviderUtil.generateURL(path, ResponseFilterChangeStatusTest.class.getSimpleName());
57 }
58
59 @AfterClass
60 public static void close() throws Exception {
61 client.close();
62 }
63
64 /**
65 * @tpTestDetails Client sends HEAD request. The response gets processed by custom ResponseFilter.
66 * @tpPassCrit The response code status is changed to 201 (CREATED), the response doesn't contain any entity,
67 * because this was HEAD request and response has set up its MediaType
68 * @tpSince RESTEasy 3.0.16
69 */
70 @Test
71 public void testDefaultHead() {
72 Response response = client.target(generateURL("/default_head")).request().head();
73 Assert.assertEquals(HttpResponseCodes.SC_CREATED, response.getStatus());
74
75 thrown.expect(ProcessingException.class);
76 response.readEntity(String.class);
77
78 logger.info(response.getMediaType());
79 Assert.assertTrue("Response must heave set up all headers, as if GET request was called."
80 , response.getMediaType().equals(MediaType.TEXT_PLAIN_TYPE));
81 response.close();
82 }
83
84 /**
85 * @tpTestDetails Client sends POST request. The response gets processed by custom ResponseFilter.
86 * @tpPassCrit The response code status is changed to 201 (CREATED)
87 * @tpSince RESTEasy 3.0.16
88 */
89 @Test
90 public void testChangeStatus() {
91 Response response = client.target(generateURL("/empty")).request().post(null);
92 Assert.assertEquals(HttpResponseCodes.SC_CREATED, response.getStatus());
93 response.close();
94 }
95 }
+0
-120
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/ResponseFilterTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.providers.custom.resource.ResponseFilter;
6 import org.jboss.resteasy.test.providers.custom.resource.ResponseFilterResource;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.AfterClass;
13 import org.junit.BeforeClass;
14 import org.junit.Test;
15 import org.junit.Assert;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.client.Entity;
21 import javax.ws.rs.core.Response;
22
23 /**
24 * @tpSubChapter Resteasy-client
25 * @tpChapter Integration tests
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class ResponseFilterTest {
31
32 static Client client;
33
34 @BeforeClass
35 public static void setup() {
36 client = ClientBuilder.newClient();
37 }
38
39 @Deployment
40 public static Archive<?> deploy() {
41 WebArchive war = TestUtil.prepareArchive(ResponseFilterTest.class.getSimpleName());
42 war.addClasses(CollectionProviderTest.class);
43 return TestUtil.finishContainerPrepare(war, null, ResponseFilterResource.class, ResponseFilter.class);
44 }
45
46 private String generateURL(String path) {
47 return PortProviderUtil.generateURL(path, ResponseFilterTest.class.getSimpleName());
48 }
49
50 @AfterClass
51 public static void close() {
52 client.close();
53 }
54
55
56 /**
57 * @tpTestDetails Client sends POST requests for each possible Response status code as the entity. The Response is
58 * set up for the response code of the request. Response is then processed by ResponseFilter which sets response code
59 * to 200 (OK) and puts the original response code into the body of the response.
60 * @tpPassCrit The response code status is changed to 200 (SUCCESS) and response contains the original code from the
61 * request
62 * @tpSince RESTEasy 3.0.16
63 */
64 @Test
65 public void testStatus() {
66 for (Response.Status status : Response.Status.values()) {
67 String content = String.valueOf(status.getStatusCode());
68 Response response = client.target(generateURL("/resource/getstatus")).request().post(Entity.text(content));
69 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
70 Assert.assertEquals("The entity doesn't contain the original http code of the request"
71 , content, response.readEntity(String.class));
72 response.close();
73 }
74
75 }
76
77 /**
78 * @tpTestDetails Client sends POST requests for each possible Response status code as the entity. The Response is
79 * set up for the response code of the request. Response is then processed by ResponseFilter which sets response code
80 * to 200 (OK) if the statusInfo() method of the responseContext returns non-null result.
81 * Then it puts the original response code into the body of the response. If the statusInfo() method returns null result
82 * the entity of the response is set up to null.
83 * @tpPassCrit The response code status is changed to 200 (SUCCESS) and response contains the original code from the
84 * request
85 * @tpSince RESTEasy 3.0.16
86 */
87 @Test
88 public void testStatusInfo() {
89 for (Response.Status status : Response.Status.values()) {
90 String content = String.valueOf(status.getStatusCode());
91 Response response = client.target(generateURL("/resource/getstatusinfo")).request().post(Entity.text(content));
92 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
93 Assert.assertEquals("The entity doesn't contain the original http code of the request", content,
94 response.readEntity(String.class));
95 response.close();
96 }
97
98 }
99
100 /**
101 * @tpTestDetails Client sends POST requests with the text entity containing information abou type. Response filter
102 * uses getEntityType() method of the responseContext to get information about type of the entity in the Response.
103 * @tpPassCrit The response code status is changed to 200 (SUCCESS) and response contains the original code from the
104 * request
105 * @tpSince RESTEasy 3.0.16
106 */
107 @Test
108 public void testEntityType() {
109 String content = "string";
110 Response response = client.target(generateURL("/resource/getentitytype")).request().post(Entity.text(content));
111 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
112 Assert.assertEquals("The entity doesn't contain the original entity type", String.class.getName()
113 , response.readEntity(String.class));
114 response.close();
115
116 }
117
118
119 }
+0
-88
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/ResponseGetAnnotationsTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.providers.custom.resource.ResponseGetAnnotationsAnnotatedClass;
6 import org.jboss.resteasy.test.providers.custom.resource.ResponseGetAnnotationsDateClientReaderWriter;
7 import org.jboss.resteasy.test.providers.custom.resource.ResponseGetAnnotationsDateContainerReaderWriter;
8 import org.jboss.resteasy.test.providers.custom.resource.ResponseGetAnnotationsResource;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Test;
14 import org.junit.BeforeClass;
15 import org.junit.AfterClass;
16 import org.junit.Assert;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Client;
20 import javax.ws.rs.client.ClientBuilder;
21 import javax.ws.rs.client.Entity;
22 import javax.ws.rs.core.Response;
23 import java.lang.annotation.Annotation;
24 import java.util.Calendar;
25 import java.util.Date;
26
27 /**
28 * @tpSubChapter Resteasy-client
29 * @tpChapter Integration tests
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class ResponseGetAnnotationsTest {
35
36 static Client client;
37
38 @BeforeClass
39 public static void setup() throws Exception {
40 client = ClientBuilder.newClient();
41 }
42
43 @Deployment
44 public static Archive<?> deploy() {
45 WebArchive war = TestUtil.prepareArchive(ResponseGetAnnotationsTest.class.getSimpleName());
46 war.addClasses(ResponseGetAnnotationsAnnotatedClass.class);
47 return TestUtil.finishContainerPrepare(war, null, ResponseGetAnnotationsResource.class,
48 ResponseGetAnnotationsDateContainerReaderWriter.class);
49 }
50
51 private String generateURL(String path) {
52 return PortProviderUtil.generateURL(path, ResponseGetAnnotationsTest.class.getSimpleName());
53 }
54
55 @AfterClass
56 public static void close() throws Exception {
57 client.close();
58 }
59
60 /**
61 * @tpTestDetails Client registers it's own instance of Date MessageBodyReader and MessageBodyWriter. Server gets
62 * registered provider to Read and Write responses with Date and Annotations objects. Client sends POST request with
63 * Date entity and expects response with Date and Annotations from a test class.
64 * @tpPassCrit The date and annotations are present in the response
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testGetAnnotations() {
69 Date date = Calendar.getInstance().getTime();
70 String entity = ResponseGetAnnotationsDateContainerReaderWriter.dateToString(date);
71 StringBuilder sb = new StringBuilder();
72 ResponseGetAnnotationsDateClientReaderWriter rw = new ResponseGetAnnotationsDateClientReaderWriter(sb);
73
74 Response response = client.target(generateURL("/entity")).register(rw).request().post(Entity.text(entity));
75
76 Date responseDate = response.readEntity(Date.class);
77 Assert.assertTrue("The date in the response doesn't match the expected one", date.equals(responseDate));
78
79 Annotation[] annotations = ResponseGetAnnotationsAnnotatedClass.class.getAnnotations();
80 for (Annotation annotation : annotations) {
81 String name = annotation.annotationType().getName();
82 Assert.assertTrue("The response doesn't contain the expected annotation", sb.toString().contains(name));
83 }
84 }
85
86
87 }
+0
-117
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/RetrieveRegisteredClassesTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import java.io.IOException;
3 import java.util.Set;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.client.Client;
9 import javax.ws.rs.client.ClientBuilder;
10 import javax.ws.rs.client.ClientRequestContext;
11 import javax.ws.rs.client.ClientRequestFilter;
12 import javax.ws.rs.client.WebTarget;
13 import javax.ws.rs.core.Configuration;
14 import javax.ws.rs.core.MediaType;
15
16 import org.jboss.arquillian.container.test.api.Deployment;
17 import org.jboss.arquillian.container.test.api.RunAsClient;
18 import org.jboss.arquillian.junit.Arquillian;
19 import org.jboss.resteasy.utils.PortProviderUtil;
20 import org.jboss.resteasy.utils.TestUtil;
21 import org.jboss.shrinkwrap.api.Archive;
22 import org.jboss.shrinkwrap.api.spec.WebArchive;
23 import org.junit.Assert;
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class RetrieveRegisteredClassesTest
30 {
31
32 @Path("/testResource")
33 @Produces(MediaType.APPLICATION_XML)
34 public static final class TestResource
35 {
36
37 @GET
38 public String get()
39 {
40 return TestResource.class.getName();
41 }
42
43 }
44
45 private static class MyFilter implements ClientRequestFilter
46 {
47
48 // To discard empty constructor
49 private MyFilter(Object value)
50 {
51 }
52
53 @Override
54 public void filter(ClientRequestContext clientRequestContext) throws IOException
55 {
56 }
57
58 }
59
60 @Deployment
61 public static Archive<?> deploy()
62 {
63 WebArchive war = TestUtil.prepareArchive(RetrieveRegisteredClassesTest.class.getSimpleName());
64 return TestUtil.finishContainerPrepare(war, null, TestResource.class);
65 }
66
67 @Test
68 public void test()
69 {
70
71 Client client = ClientBuilder.newClient();
72 try
73 {
74 String uri = PortProviderUtil
75 .generateURL("/testResource", RetrieveRegisteredClassesTest.class.getSimpleName());
76 MyFilter myFilter = new MyFilter(new Object());
77
78 WebTarget firstWebTarget = client.target(uri).register(myFilter);
79 String firstResult = firstWebTarget.request(MediaType.APPLICATION_XML).get(String.class);
80 Configuration firstWebTargetConfiguration = firstWebTarget.getConfiguration();
81 Set<Class<?>> classes = firstWebTargetConfiguration.getClasses();
82 Set<Object> instances = firstWebTargetConfiguration.getInstances();
83 Assert.assertFalse(classes.contains(MyFilter.class));
84 Assert.assertTrue(instances.contains(myFilter));
85
86 WebTarget secondWebTarget = client.target(uri);
87 Configuration secondWebTargetConfiguration = secondWebTarget.getConfiguration();
88 for (Class<?> classz : classes)
89 {
90 if (!secondWebTargetConfiguration.isRegistered(classz))
91 {
92 secondWebTarget.register(classz);
93 }
94 }
95 for (Object instance : instances)
96 {
97 if (!secondWebTargetConfiguration.isRegistered(instance.getClass()))
98 {
99 secondWebTarget.register(instance);
100 }
101 }
102 String secondeResult = secondWebTarget.request(MediaType.APPLICATION_XML).get(String.class);
103 classes = secondWebTargetConfiguration.getClasses();
104 instances = secondWebTargetConfiguration.getInstances();
105 Assert.assertFalse(classes.contains(MyFilter.class));
106 Assert.assertTrue(instances.contains(myFilter));
107 Assert.assertEquals(firstResult, secondeResult);
108 }
109 finally
110 {
111 client.close();
112 }
113
114 }
115
116 }
+0
-99
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/SetRequestUriTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.providers.custom.resource.SetRequestUriRequestFilter;
6 import org.jboss.resteasy.test.providers.custom.resource.SetRequestUriResource;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.AfterClass;
13 import org.junit.BeforeClass;
14 import org.junit.Test;
15 import org.junit.Assert;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Resteasy-client
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class SetRequestUriTest {
30
31 static Client client;
32
33 @BeforeClass
34 public static void setup() throws Exception {
35 client = ClientBuilder.newClient();
36 }
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(SetRequestUriTest.class.getSimpleName());
41 return TestUtil.finishContainerPrepare(war, null, SetRequestUriResource.class, SetRequestUriRequestFilter.class);
42 }
43
44 private String generateURL(String path) {
45 return PortProviderUtil.generateURL(path, SetRequestUriTest.class.getSimpleName());
46 }
47
48 @AfterClass
49 public static void close() throws Exception {
50 client.close();
51 }
52
53
54 /**
55 * @tpTestDetails Client sends GET request with https protocol uri. The resource has injected UriInfo and returns
56 * response containing absolute path of the uri from the request.
57 * @tpPassCrit The response code status is changed to 200 (SUCCESS) and the absolute uri matches the original request
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testSchemaChange() {
62 String uri = generateURL("/base/resource/change");
63 String httpsUri = uri.replace("http://", "https://");
64 Response response = client.target(uri).request().header("X-Forwarded-Proto", "https").get();
65 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
66 Assert.assertEquals("The original https uri doesn't match the entity in the response", httpsUri,
67 response.readEntity(String.class));
68 }
69
70 /**
71 * @tpTestDetails Client sends GET request with https protocol uri. The resource has injected UriInfo and returns
72 * response containing absolute path of the uri from the request.
73 * @tpPassCrit The response code status is changed to 200 (SUCCESS) and the absolute uri matches the original request
74 * @tpSince RESTEasy 3.0.16
75 */
76 @Test
77 public void testUriOverride() {
78 Response response = client.target(generateURL("/base/resource/setrequesturi1")).request().get();
79 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
80 Assert.assertEquals("OK", response.readEntity(String.class));
81 }
82
83 /**
84 * @tpTestDetails Client sends GET request with non existing uri path. The request is catched by PreMatching
85 * RequestFilter which applies to all requests not matter if the resource exists on the server. The RequestFilter
86 * processes the request aborts processing of the request and sends response back to the client.
87 * @tpPassCrit The response code status is 200 (SUCCESS) and the absolute uri is changed by RequestFilter
88 * @tpSince RESTEasy 3.0.16
89 */
90 @Test
91 public void testUriOverride2() {
92 Response response = client.target(generateURL("/base/resource/setrequesturi2")).request().get();
93 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
94 Assert.assertEquals("The original uri doesn't match the entity changed by RequestFilter",
95 "http://xx.yy:888/base/resource/sub", response.readEntity(String.class));
96 }
97
98 }
+0
-78
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/SingletonCustomProviderTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.providers.custom.resource.SingletonCustomProviderObject;
8 import org.jboss.resteasy.test.providers.custom.resource.SingletonCustomProviderResource;
9 import org.jboss.resteasy.test.providers.custom.resource.SingletonCustomProviderApplication;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.ShrinkWrap;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.client.Entity;
21 import javax.ws.rs.core.Response;
22
23 /**
24 * @tpSubChapter Configuration
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Test for anonymous classes as resource added to REST singletons
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class SingletonCustomProviderTest {
32 static ResteasyClient client;
33
34 @Deployment
35 public static Archive<?> deploy() {
36 WebArchive war = ShrinkWrap.create(WebArchive.class, SingletonCustomProviderTest.class.getSimpleName() + ".war");
37 war.addClasses(SingletonCustomProviderApplication.class, SingletonCustomProviderObject.class,
38 SingletonCustomProviderResource.class);
39 return war;
40 }
41
42 private String generateURL(String path) {
43 return PortProviderUtil.generateURL(path, SingletonCustomProviderTest.class.getSimpleName());
44 }
45
46 @Before
47 public void init() {
48 client = new ResteasyClientBuilder().build();
49 }
50
51 @After
52 public void after() throws Exception {
53 client.close();
54 }
55
56 /**
57 * @tpTestDetails Check post request
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testMessageReaderThrowingWebApplicationException() throws Exception {
62 Response response = client.target(generateURL("/test")).request().post(Entity.entity("foo", "application/octet-stream"));
63 Assert.assertEquals("Wrong response status", 999, response.getStatus());
64 response.close();
65 }
66
67 /**
68 * @tpTestDetails Check get request
69 * @tpSince RESTEasy 3.0.16
70 */
71 @Test
72 public void testMessageWriterThrowingWebApplicationException() throws Exception {
73 Response response = client.target(generateURL("/test")).request().get();
74 Assert.assertEquals("Wrong response status", 999, response.getStatus());
75 response.close();
76 }
77 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/WriterNotBuiltinTest.java less more
0 package org.jboss.resteasy.test.providers.custom;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
6 import org.jboss.resteasy.test.providers.custom.resource.WriterNotBuiltinTestWriter;
7 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterCustomer;
8 import org.jboss.resteasy.test.providers.custom.resource.ReaderWriterResource;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Assert;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.core.Response;
19 import java.util.HashMap;
20 import java.util.Map;
21
22 /**
23 * @tpSubChapter Providers
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Regression test for RESTEASY-1
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 public class WriterNotBuiltinTest {
30
31 static ResteasyClient client;
32
33 @Deployment
34 public static Archive<?> deployDefaultTestPlain() {
35 WebArchive war = TestUtil.prepareArchive(WriterNotBuiltinTest.class.getSimpleName());
36 war.addClass(ReaderWriterCustomer.class);
37 war.addClass(PortProviderUtil.class);
38 Map<String, String> contextParams = new HashMap<>();
39 contextParams.put("resteasy.use.builtin.providers", "false");
40 return TestUtil.finishContainerPrepare(war, contextParams, WriterNotBuiltinTestWriter.class, ReaderWriterResource.class);
41 }
42
43 /**
44 * @tpTestDetails A more complete test for RESTEASY-1.
45 * TestReaderWriter has no type parameter,
46 * so it comes after DefaultPlainText in the built-in ordering.
47 * The fact that TestReaderWriter gets called verifies that
48 * DefaultPlainText gets passed over.
49 * @tpSince RESTEasy 3.0.16
50 */
51 @Test
52 public void test1New() throws Exception {
53 client = new ResteasyClientBuilder().build();
54 Response response = client.target(PortProviderUtil.generateURL("/string", WriterNotBuiltinTest.class.getSimpleName()))
55 .request().get();
56 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
57 Assert.assertEquals("text/plain;charset=UTF-8", response.getStringHeaders().getFirst("content-type"));
58 Assert.assertEquals("Response contains wrong content", "hello world", response.readEntity(String.class));
59 Assert.assertTrue("Wrong MessageBodyWriter was used", WriterNotBuiltinTestWriter.used);
60 client.close();
61 }
62 }
+0
-52
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/CollectionProviderCollectionWriter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import org.jboss.resteasy.test.providers.custom.CollectionProviderTest;
3
4 import javax.ws.rs.WebApplicationException;
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.MultivaluedMap;
7 import javax.ws.rs.core.Response;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.Provider;
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14 import java.util.Collection;
15
16 @Provider
17 public class CollectionProviderCollectionWriter implements
18 MessageBodyWriter<Collection<?>> {
19 @Override
20 public boolean isWriteable(Class<?> type, Type genericType,
21 Annotation[] annotations, MediaType mediaType) {
22 String path = CollectionProviderTest.getPathValue(annotations);
23 // Return type : Other
24 if (path.equalsIgnoreCase(type.getSimpleName())) {
25 return CollectionProviderTest.checkOther(type, genericType);
26 } else if (path.equalsIgnoreCase("response/linkedlist")) {
27 return CollectionProviderTest.checkResponseNongeneric(type, genericType);
28 } else if (path.equalsIgnoreCase("response/genericentity/linkedlist")) {
29 return CollectionProviderTest.checkGeneric(type, genericType);
30 } else if (path.equalsIgnoreCase("genericentity/linkedlist")) {
31 return CollectionProviderTest.checkGeneric(type, genericType);
32 }
33 return false;
34 }
35
36 @Override
37 public long getSize(Collection<?> t, Class<?> type, Type genericType,
38 Annotation[] annotations, MediaType mediaType) {
39 return Response.Status.OK.name().length();
40 }
41
42 @Override
43 public void writeTo(Collection<?> t, Class<?> type, Type genericType,
44 Annotation[] annotations, MediaType mediaType,
45 MultivaluedMap<String, Object> httpHeaders,
46 OutputStream entityStream) throws IOException,
47 WebApplicationException {
48 entityStream.write(Response.Status.OK.name().getBytes());
49 }
50
51 }
+0
-46
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/CollectionProviderIncorrectCollectionWriter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import org.jboss.resteasy.test.providers.custom.CollectionProviderTest;
3
4 import javax.ws.rs.WebApplicationException;
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.MultivaluedMap;
7 import javax.ws.rs.ext.MessageBodyWriter;
8 import javax.ws.rs.ext.Provider;
9 import java.io.IOException;
10 import java.io.OutputStream;
11 import java.lang.annotation.Annotation;
12 import java.lang.reflect.Type;
13 import java.util.Collection;
14
15 @Provider
16 public class CollectionProviderIncorrectCollectionWriter
17 implements MessageBodyWriter<Collection<?>> {
18
19 public static final String ERROR = "ERROR ";
20
21 @Override
22 public boolean isWriteable(Class<?> type, Type genericType,
23 Annotation[] annotations, MediaType mediaType) {
24 return !new CollectionProviderCollectionWriter().isWriteable(type, genericType,
25 annotations, mediaType);
26 }
27
28 @Override
29 public long getSize(Collection<?> t, Class<?> type, Type genericType,
30 Annotation[] annotations, MediaType mediaType) {
31 String path = CollectionProviderTest.getPathValue(annotations);
32 return ERROR.length() + path.length();
33 }
34
35 @Override
36 public void writeTo(Collection<?> t, Class<?> type, Type genericType,
37 Annotation[] annotations, MediaType mediaType,
38 MultivaluedMap<String, Object> httpHeaders,
39 OutputStream entityStream) throws IOException,
40 WebApplicationException {
41 String path = CollectionProviderTest.getPathValue(annotations);
42 entityStream.write(ERROR.getBytes());
43 entityStream.write(path.getBytes());
44 }
45 }
+0
-66
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/CollectionProviderResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.GenericEntity;
8 import javax.ws.rs.core.Response;
9 import java.lang.reflect.Method;
10 import java.util.LinkedList;
11
12 @Path("resource")
13 public class CollectionProviderResource {
14
15 private static Logger logger = Logger.getLogger(CollectionProviderResource.class);
16
17 @Path("linkedlist")
18 @GET
19 public LinkedList<String> checkDirect() {
20 LinkedList<String> list = new LinkedList<String>();
21 list.add("linked");
22 list.add("list");
23 return list;
24 }
25
26 @Path("response/linkedlist")
27 @GET
28 public Response checkResponseDirect() {
29 LinkedList<String> list = new LinkedList<String>();
30 list.add("linked");
31 list.add("list");
32 return Response.ok(list).build();
33 }
34
35 @Path("response/genericentity/linkedlist")
36 @GET
37 public Response checkResponseGeneric() {
38 GenericEntity<LinkedList<String>> gells = checkGeneric();
39 return Response.ok(gells).build();
40 }
41
42 @Path("genericentity/linkedlist")
43 @GET
44 public GenericEntity<LinkedList<String>> checkGeneric() {
45 LinkedList<String> list = new LinkedList<String>();
46 list.add("linked");
47 list.add("list");
48 GenericEntity<LinkedList<String>> gells = null;
49 Method method = getMethodByName("checkDirect");
50 if (method == null) {
51 throw new WebApplicationException("No method in the Resource to bind the request", 500);
52 }
53 gells = new GenericEntity<LinkedList<String>>(list, method.getGenericReturnType());
54 return gells;
55 }
56
57 private Method getMethodByName(String name) {
58 try {
59 return getClass().getMethod(name);
60 } catch (NoSuchMethodException e) {
61 logger.error("No method in the Resource to bind the request", e);
62 return null;
63 }
64 }
65 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/CustomProviderPreferenceUser.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 public class CustomProviderPreferenceUser {
3
4 private String username;
5 private String email;
6
7 public CustomProviderPreferenceUser() {
8 }
9
10 public CustomProviderPreferenceUser(final String username, final String email) {
11 this.username = username;
12 this.email = email;
13 }
14
15 public String getUsername() {
16 return username;
17 }
18
19 public void setUsername(String username) {
20 this.username = username;
21 }
22
23 public String getEmail() {
24 return email;
25 }
26
27 public void setEmail(String email) {
28 this.email = email;
29 }
30 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/CustomProviderPreferenceUserBodyWriter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.Produces;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import javax.ws.rs.ext.Provider;
8 import java.io.BufferedWriter;
9 import java.io.IOException;
10 import java.io.OutputStream;
11 import java.io.OutputStreamWriter;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14
15 @Provider
16 @Produces("text/plain")
17 public class CustomProviderPreferenceUserBodyWriter implements MessageBodyWriter<CustomProviderPreferenceUser> {
18
19 public long getSize(CustomProviderPreferenceUser arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
20 return getStringRepresentation(arg0).length();
21 }
22
23 public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
24 return true;
25 }
26
27 public void writeTo(CustomProviderPreferenceUser arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4,
28 MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException {
29 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(arg6));
30 bw.write(getStringRepresentation(arg0));
31 bw.flush();
32 }
33
34 private String getStringRepresentation(CustomProviderPreferenceUser user) {
35 return user.getUsername() + ";" + user.getEmail();
36 }
37 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/CustomProviderPreferenceUserResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/user")
7 @Produces("text/plain")
8 public class CustomProviderPreferenceUserResource {
9
10 private static final CustomProviderPreferenceUser user = new CustomProviderPreferenceUser("jharting", "email@example.com");
11
12 @GET
13 public CustomProviderPreferenceUser getUser() {
14 return user;
15 }
16 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/CustomValueInjectorHello.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 @Target(ElementType.PARAMETER)
8 @Retention(RetentionPolicy.RUNTIME)
9 public @interface CustomValueInjectorHello {
10 String value();
11 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/CustomValueInjectorHelloResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("")
7 public class CustomValueInjectorHelloResource {
8 @GET
9 @Produces("text/plain")
10 public String get(@CustomValueInjectorHello("world") String hello) {
11 return hello;
12 }
13 }
+0
-52
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/CustomValueInjectorInjectorFactoryImpl.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import org.jboss.resteasy.core.InjectorFactoryImpl;
3 import org.jboss.resteasy.core.ValueInjector;
4 import org.jboss.resteasy.spi.HttpRequest;
5 import org.jboss.resteasy.spi.HttpResponse;
6 import org.jboss.resteasy.spi.ResteasyProviderFactory;
7 import org.jboss.resteasy.spi.metadata.Parameter;
8 import org.jboss.resteasy.util.FindAnnotation;
9
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.AccessibleObject;
12 import java.lang.reflect.Type;
13
14 public class CustomValueInjectorInjectorFactoryImpl extends InjectorFactoryImpl {
15 @Override
16 public ValueInjector createParameterExtractor(Class injectTargetClass, AccessibleObject injectTarget, Class type,
17 Type genericType, Annotation[] annotations, ResteasyProviderFactory factory) {
18 final CustomValueInjectorHello hello = FindAnnotation.findAnnotation(annotations, CustomValueInjectorHello.class);
19 if (hello == null) {
20 return super.createParameterExtractor(injectTargetClass, injectTarget, type, genericType, annotations, factory);
21 } else {
22 return new ValueInjector() {
23 public Object inject(HttpRequest request, HttpResponse response) {
24 return hello.value();
25 }
26
27 public Object inject() {
28 return hello.value();
29 }
30 };
31 }
32 }
33
34 @Override
35 public ValueInjector createParameterExtractor(Parameter parameter, ResteasyProviderFactory providerFactory) {
36 final CustomValueInjectorHello hello = FindAnnotation.findAnnotation(parameter.getAnnotations(), CustomValueInjectorHello.class);
37 if (hello == null) {
38 return super.createParameterExtractor(parameter, providerFactory);
39 } else {
40 return new ValueInjector() {
41 public Object inject(HttpRequest request, HttpResponse response) {
42 return hello.value();
43 }
44
45 public Object inject() {
46 return hello.value();
47 }
48 };
49 }
50 }
51 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/FilterDispatcherForwardServlet.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import org.jboss.logging.Logger;
3
4 import java.io.IOException;
5
6 import javax.servlet.ServletException;
7 import javax.servlet.ServletRequest;
8 import javax.servlet.ServletResponse;
9 import javax.servlet.http.HttpServlet;
10
11 public class FilterDispatcherForwardServlet extends HttpServlet {
12 private static Logger logger = Logger.getLogger(FilterDispatcherForwardServlet.class);
13
14 private static final long serialVersionUID = 1L;
15
16 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
17 logger.info("enterng ForwardServlet.service()");
18 res.getOutputStream().write("forward".getBytes());
19 }
20 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/FilterDispatcherServlet.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import org.jboss.logging.Logger;
3
4 import java.io.IOException;
5
6 import javax.servlet.RequestDispatcher;
7 import javax.servlet.ServletException;
8 import javax.servlet.ServletRequest;
9 import javax.servlet.ServletResponse;
10 import javax.servlet.http.HttpServlet;
11
12 public class FilterDispatcherServlet extends HttpServlet {
13 private static Logger logger = Logger.getLogger(FilterDispatcherServlet.class);
14
15 private static final long serialVersionUID = 1L;
16
17 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
18 logger.info("entering TestServlet.service()");
19 logger.info("context path: " + req.getServletContext().getContextPath());
20 RequestDispatcher dispatcher = req.getRequestDispatcher("/forward");
21 try {
22 dispatcher.forward(req, res);
23 } catch (Exception e) {
24 throw new RuntimeException(e);
25 }
26 }
27 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ProviderContextInjectionAnyExceptionExceptionMapper.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.Response;
4 import javax.ws.rs.ext.ExceptionMapper;
5 import javax.ws.rs.ext.Provider;
6 import java.io.IOException;
7
8 @Provider
9 public class ProviderContextInjectionAnyExceptionExceptionMapper implements ExceptionMapper<Exception> {
10
11 @Override
12 public Response toResponse(Exception arg0) {
13 Response.Status status = Response.Status.NO_CONTENT;
14 if (arg0 instanceof WebApplicationException) {
15 return ((WebApplicationException) arg0).getResponse();
16 } else if (arg0 instanceof RuntimeException) {
17 throw new RuntimeException("CTS Test RuntimeException", arg0);
18 } else if (arg0 instanceof IOException) {
19 status = Response.Status.SERVICE_UNAVAILABLE;
20 } else if (arg0 != null) {
21 status = Response.Status.NOT_ACCEPTABLE;
22 }
23 return Response.status(status).build();
24 }
25
26 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ProviderContextInjectionEnumContextResolver.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.ext.ContextResolver;
3 import javax.ws.rs.ext.Provider;
4
5 @Provider
6 public class ProviderContextInjectionEnumContextResolver implements ContextResolver<ProviderContextInjectionEnumProvider> {
7
8 @Override
9 public ProviderContextInjectionEnumProvider getContext(Class<?> type) {
10 return type == ProviderContextInjectionEnumProvider.class ? ProviderContextInjectionEnumProvider.JAXRS : null;
11 }
12
13 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ProviderContextInjectionEnumProvider.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 public enum ProviderContextInjectionEnumProvider {
3 TCK, CTS, JAXRS;
4 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ProviderContextInjectionIOExceptionExceptionMapper.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4 import javax.ws.rs.ext.Provider;
5 import java.io.IOException;
6
7 @Provider
8 public class ProviderContextInjectionIOExceptionExceptionMapper implements ExceptionMapper<IOException> {
9
10 @Override
11 public Response toResponse(IOException exception) {
12 return Response.status(Response.Status.ACCEPTED).build();
13 }
14
15 }
+0
-51
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ProviderContextInjectionResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Context;
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.Response;
7 import javax.ws.rs.ext.ContextResolver;
8 import javax.ws.rs.ext.ExceptionMapper;
9 import javax.ws.rs.ext.Providers;
10
11 @Path("resource")
12 public class ProviderContextInjectionResource {
13
14 @Context
15 Providers providers;
16
17 @GET
18 @Path("isRegisteredContextResolver")
19 public Response isRegisteredContextResolver() {
20 ProviderContextInjectionEnumProvider ep = getEnumProvider(MediaType.WILDCARD_TYPE);
21 return getResponseByEnumProvider(ProviderContextInjectionEnumProvider.JAXRS, ep);
22 }
23
24 private ProviderContextInjectionEnumProvider getEnumProvider(MediaType type) {
25 ContextResolver<ProviderContextInjectionEnumProvider> scr = providers.getContextResolver(
26 ProviderContextInjectionEnumProvider.class, type);
27 ProviderContextInjectionEnumProvider ep = scr.getContext(ProviderContextInjectionEnumProvider.class);
28 return ep;
29 }
30
31 @GET
32 @Path("isRegisteredRuntimeExceptionMapper")
33 public Response isRegisteredRuntimeExceptionMapper() {
34 ExceptionMapper<RuntimeException> em = providers
35 .getExceptionMapper(RuntimeException.class);
36 Response.Status status = Response.Status.NOT_ACCEPTABLE;
37 if (em != null && em.getClass() == ProviderContextInjectionAnyExceptionExceptionMapper.class) {
38 status = Response.Status.OK;
39 }
40 return Response.status(status).build();
41 }
42
43 Response getResponseByEnumProvider(ProviderContextInjectionEnumProvider expected, ProviderContextInjectionEnumProvider given) {
44 Response.Status status = Response.Status.NO_CONTENT;
45 if (given != null) {
46 status = given != expected ? Response.Status.NOT_ACCEPTABLE : Response.Status.OK;
47 }
48 return Response.status(status).build();
49 }
50 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ProviderContextInjectionTextPlainEnumContextResolver.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.Produces;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.ext.ContextResolver;
5 import javax.ws.rs.ext.Provider;
6
7 @Provider
8 @Produces(MediaType.TEXT_PLAIN)
9 public class ProviderContextInjectionTextPlainEnumContextResolver implements ContextResolver<ProviderContextInjectionEnumProvider> {
10 @Override
11 public ProviderContextInjectionEnumProvider getContext(Class<?> type) {
12 return type == ProviderContextInjectionEnumProvider.class ? ProviderContextInjectionEnumProvider.CTS : null;
13 }
14 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ReaderWriterClient.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.core.Response;
3
4 import javax.ws.rs.DELETE;
5 import javax.ws.rs.Path;
6
7 @Path("/")
8 public interface ReaderWriterClient {
9 @Path("/implicit")
10 @DELETE
11 Response deleteCustomer();
12
13 @Path("/complex")
14 @DELETE
15 Response deleteComplex();
16 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ReaderWriterCurlyBraces.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.Produces;
6
7 @Path("/curly")
8 public class ReaderWriterCurlyBraces {
9 @Path("{tableName:[a-z][a-z0-9_]{0,49}}")
10 @GET
11 @Produces("text/plain")
12 public String get(@PathParam("tableName") String param) {
13 return "param";
14 }
15 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ReaderWriterCustomer.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 public class ReaderWriterCustomer {
3 private String name;
4
5 public String getName() {
6 return name;
7 }
8
9 public void setName(String name) {
10 this.name = name;
11 }
12 }
+0
-32
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ReaderWriterCustomerWriter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.Produces;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import javax.ws.rs.ext.Provider;
8 import java.io.IOException;
9 import java.io.OutputStream;
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.Type;
12
13 @Provider
14 @Produces("application/xml")
15 public class ReaderWriterCustomerWriter implements MessageBodyWriter<ReaderWriterCustomer> {
16 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
17 return type.equals(ReaderWriterCustomer.class);
18 }
19
20 public long getSize(ReaderWriterCustomer customer, Class<?> type, Type genericType, Annotation[] annotations,
21 MediaType mediaType) {
22 return -1;
23 }
24
25 public void writeTo(ReaderWriterCustomer customer, Class<?> type, Type genericType, Annotation[] annotations,
26 MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
27 throws IOException, WebApplicationException {
28 String out = "<customer><name>" + customer.getName() + "</name></customer>";
29 entityStream.write(out.getBytes());
30 }
31 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ReaderWriterNowhereClient.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Response;
6
7 @Path("/nowhere")
8 public interface ReaderWriterNowhereClient {
9 @GET
10 @Produces("text/plain")
11 Response read();
12 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ReaderWriterResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.util.HttpResponseCodes;
4
5 import javax.ws.rs.DELETE;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.Response;
10
11 @Path("/")
12 public class ReaderWriterResource {
13 private static Logger logger = Logger.getLogger(ReaderWriterResource.class);
14 @Path("/simple")
15 @GET
16 public Response get() {
17 Response.ResponseBuilder builder = Response.ok("hello world".getBytes());
18 builder.header("CoNtEnT-type", "text/plain");
19 return builder.build();
20 }
21
22 @Path("/string")
23 @GET
24 public Response getString() {
25 Response.ResponseBuilder builder = Response.ok("hello world");
26 builder.header("CoNtEnT-type", "text/plain");
27 logger.info("getString");
28 return builder.build();
29 }
30
31 @Path("/complex")
32 @GET
33 public Object getComplex() {
34 Response.ResponseBuilder builder = Response.status(HttpResponseCodes.SC_FOUND)
35 .entity("hello world".getBytes());
36 builder.header("CoNtEnT-type", "text/plain");
37 return builder.build();
38 }
39
40 @Path("/implicit")
41 @GET
42 @Produces("application/xml")
43 public Object getCustomer() {
44 logger.info("GET CUSTOEMR");
45 ReaderWriterCustomer cust = new ReaderWriterCustomer();
46 cust.setName("bill");
47 return Response.ok(cust).build();
48 }
49
50 @Path("/implicit")
51 @DELETE
52 public Object deleteCustomer() {
53 return Response.ok().build();
54 }
55
56 @Path("/complex")
57 @DELETE
58 public void deleteComplex() {
59
60 }
61
62 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ReaderWriterSpaces.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("/spaces")
5 public class ReaderWriterSpaces {
6
7 @Path("/with spaces")
8 public ReaderWriterSub sub() {
9 return new ReaderWriterSub();
10 }
11 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ReaderWriterSub.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 public class ReaderWriterSub {
7 @Path("/without")
8 @GET
9 @Produces("text/plain")
10 public String get() {
11 return "hello";
12 }
13 }
+0
-41
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseContainerResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Context;
5 import javax.ws.rs.core.PathSegment;
6 import javax.ws.rs.core.Response;
7 import javax.ws.rs.core.UriInfo;
8 import java.util.List;
9
10 @Path("resource")
11 public class ResponseContainerResource {
12
13 @Context
14 UriInfo info;
15
16 @POST
17 @Path("hasentity")
18 public Response hasEntity(String entity) {
19 Response.ResponseBuilder builder = createResponseWithHeader();
20 if (entity != null && entity.length() != 0) {
21 builder = builder.entity(entity);
22 }
23 Response response = builder.build();
24 return response;
25 }
26
27 private Response.ResponseBuilder createResponseWithHeader() {
28 // get value of @Path(value)
29 List<PathSegment> segments = info.getPathSegments();
30 PathSegment last = segments.get(segments.size() - 1);
31 // convert the value to ContextOperation
32 Response.ResponseBuilder builder = Response.ok();
33 // set a header with ContextOperation so that the filter knows what to do
34 builder = builder.header(ResponseContainerResponseFilter.OPERATION, last.getPath()
35 .toUpperCase());
36 return builder;
37 }
38
39
40 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseContainerResponseFilter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.ext.Provider;
4
5 @Provider
6 @Priority(500)
7 // reverse order
8 public class ResponseContainerResponseFilter extends ResponseContainerTemplateFilter {
9
10 public void hasEntity() {
11 boolean has = responseContext.hasEntity();
12 setEntity(String.valueOf(has));
13 }
14 }
+0
-35
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseContainerSecondResponseFilter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.ext.Provider;
5 import java.lang.annotation.Annotation;
6
7 // reverse order, This filter should be second
8 @Provider
9 @Priority(100)
10 public class ResponseContainerSecondResponseFilter extends ResponseContainerTemplateFilter {
11 @Override
12 protected void operationMethodNotFound(String operation) {
13 // the check is to apply on ResponseFilter only
14 // here, it is usually not found.
15 }
16
17 public void setEntity() {
18 MediaType type = responseContext.getMediaType();
19 if (assertTrue(MediaType.APPLICATION_SVG_XML_TYPE.equals(type),
20 "Unexpected mediatype", type)) {
21 return;
22 }
23
24 Annotation[] annotations = responseContext.getEntityAnnotations();
25 for (Annotation annotation : annotations) {
26 Class<?> clazz = annotation.annotationType();
27 if (assertTrue(clazz == Provider.class
28 || clazz == Priority.class, "Annotation", clazz,
29 "was unexpected")) {
30 return;
31 }
32 }
33 }
34 }
+0
-79
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseContainerTemplateFilter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2
3 import org.jboss.logging.Logger;
4
5 import javax.ws.rs.container.ContainerRequestContext;
6 import javax.ws.rs.container.ContainerResponseContext;
7 import javax.ws.rs.container.ContainerResponseFilter;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.MultivaluedMap;
10 import javax.ws.rs.core.Response;
11 import java.io.IOException;
12 import java.lang.reflect.Method;
13
14 public abstract class ResponseContainerTemplateFilter implements ContainerResponseFilter {
15
16 public static final String OPERATION = "OPERATION";
17 private static Logger logger = Logger.getLogger(ResponseContainerTemplateFilter.class);
18
19 protected ContainerRequestContext requestContext;
20 protected ContainerResponseContext responseContext;
21
22 @Override
23 public void filter(ContainerRequestContext requestContext,
24 ContainerResponseContext responseContext) throws IOException {
25 this.requestContext = requestContext;
26 this.responseContext = responseContext;
27 String operation = getHeaderString();
28 Method[] methods = getClass().getMethods();
29 for (Method method : methods) {
30 if (operation != null) {
31 if (operation.equalsIgnoreCase(method.getName())) {
32 try {
33 method.invoke(this);
34 return;
35 } catch (Exception e) {
36 logger.error("The requested resource is not available", e);
37 responseContext.setStatus(Response.Status.SERVICE_UNAVAILABLE
38 .getStatusCode());
39 setEntity(e.getMessage());
40 return;
41 }
42 }
43 }
44 }
45 operationMethodNotFound(operation);
46 }
47
48 protected void operationMethodNotFound(String operation) {
49 responseContext.setStatus(Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
50 setEntity("Operation " + operation + " not implemented");
51 }
52
53 // ///////////////////////////////////////////////////////////////////
54 protected boolean assertTrue(boolean conditionTrue, Object... msg) {
55 if (conditionTrue) {
56 return false;
57 }
58 StringBuilder sb = new StringBuilder();
59 if (msg != null) {
60 for (Object str : msg) {
61 sb.append(str).append(" ");
62 }
63 }
64 setEntity(sb.toString());
65 responseContext.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
66 return true;
67 }
68
69 protected String getHeaderString() {
70 MultivaluedMap<String, Object> headers = responseContext.getHeaders();
71 return (String) headers.getFirst(OPERATION);
72 }
73
74 protected void setEntity(String entity) {
75 responseContext.setEntity(entity, null, MediaType.TEXT_PLAIN_TYPE);
76 }
77
78 }
+0
-43
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseFilter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.container.ContainerRequestContext;
3 import javax.ws.rs.container.ContainerResponseContext;
4 import javax.ws.rs.container.ContainerResponseFilter;
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.Response;
7 import javax.ws.rs.ext.Provider;
8 import java.io.IOException;
9 import java.lang.reflect.Type;
10
11 @Provider
12 public class ResponseFilter implements ContainerResponseFilter {
13 @Override
14 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
15 if (requestContext.getUriInfo().getPath().endsWith("getstatus")) {
16 int status = responseContext.getStatus();
17 responseContext.setStatus(Response.Status.OK.getStatusCode());
18 responseContext.setEntity(String.valueOf(status), null, MediaType.TEXT_PLAIN_TYPE);
19 } else if (requestContext.getUriInfo().getPath().endsWith("getentitytype")) {
20 Type type = responseContext.getEntityType();
21 String name = "NULL";
22 if (type instanceof Class) {
23 name = ((Class<?>) type).getName();
24 } else if (type != null) {
25 name = type.getClass().getName();
26 }
27 responseContext.setEntity(name, null, MediaType.TEXT_PLAIN_TYPE);
28
29 } else if (requestContext.getUriInfo().getPath().endsWith("getstatusinfo")) {
30 Response.StatusType type = responseContext.getStatusInfo();
31 if (type == null) {
32 responseContext.setEntity("NULL", null, MediaType.TEXT_PLAIN_TYPE);
33 responseContext.setStatus(Response.Status.OK.getStatusCode());
34 return;
35 }
36 int status = type.getStatusCode();
37 responseContext.setStatus(Response.Status.OK.getStatusCode());
38 responseContext.setEntity(String.valueOf(status), null, MediaType.TEXT_PLAIN_TYPE);
39
40 }
41 }
42 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseFilterChangeStatusResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.Response;
7
8 @Path("/")
9 @Produces("text/plain")
10 public class ResponseFilterChangeStatusResource {
11
12 @POST
13 @Path("empty")
14 public void empty() {
15 }
16
17 @GET
18 @Path("default_head")
19 public Response defaultHead() {
20 return Response.ok(" ").build();
21 }
22 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseFilterChangeStatusResponseFilter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.container.ContainerRequestContext;
3 import javax.ws.rs.container.ContainerResponseContext;
4 import javax.ws.rs.container.ContainerResponseFilter;
5 import javax.ws.rs.ext.Provider;
6 import java.io.IOException;
7
8 @Provider
9 public class ResponseFilterChangeStatusResponseFilter implements ContainerResponseFilter {
10 @Override
11 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
12 responseContext.setStatus(201);
13 }
14 }
+0
-44
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseFilterResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5 import java.io.ByteArrayInputStream;
6
7 @Path("resource")
8 public class ResponseFilterResource {
9
10 @POST
11 @Path("getstatus")
12 public Response getStatus(String entity) {
13 int status = Integer.parseInt(entity);
14 Response.ResponseBuilder builder = Response.ok();
15 Response response = builder.status(status).build();
16 return response;
17 }
18
19 @POST
20 @Path("getstatusinfo")
21 public Response getStatusinfo(String entity) {
22 return getStatus(entity);
23 }
24
25 @POST
26 @Path("getentitytype")
27 public Response getEntityType(String type) {
28 Response.ResponseBuilder builder = Response.ok();
29 Object entity = null;
30 String content = "ENTity";
31 if ("string".equals(type)) {
32 entity = content;
33 } else if ("bytearray".equals(type)) {
34 entity = content.getBytes();
35 } else if ("inputstream".equals(type)) {
36 entity = new ByteArrayInputStream(content.getBytes());
37 }
38 builder = builder.entity(entity);
39 Response response = builder.build();
40 return response;
41 }
42
43 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseGetAnnotationsAnnotatedClass.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.ext.Provider;
4
5 /**
6 * This is the dummy class to get annotations from it
7 */
8 @Provider
9 @Consumes
10 public abstract class ResponseGetAnnotationsAnnotatedClass {
11
12 }
+0
-72
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseGetAnnotationsDateClientReaderWriter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import javax.ws.rs.ext.MessageBodyReader;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import javax.ws.rs.ext.Provider;
8 import java.io.BufferedReader;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.io.OutputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.Type;
15 import java.util.Date;
16
17 @Provider
18 public class ResponseGetAnnotationsDateClientReaderWriter implements MessageBodyReader<Date>,
19 MessageBodyWriter<Date> {
20 private StringBuilder atom;
21
22 public ResponseGetAnnotationsDateClientReaderWriter(final StringBuilder atom) {
23 super();
24 this.atom = atom;
25 }
26
27 @Override
28 public long getSize(Date arg0, Class<?> arg1, Type arg2, Annotation[] arg3,
29 MediaType arg4) {
30 return String.valueOf(Long.MAX_VALUE).length()
31 + ResponseGetAnnotationsDateContainerReaderWriter.SPLITTER.length();
32 }
33
34 @Override
35 public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2,
36 MediaType arg3) {
37 return arg0 == Date.class;
38 }
39
40 @Override
41 public void writeTo(Date date, Class<?> arg1, Type arg2, Annotation[] arg3,
42 MediaType arg4, MultivaluedMap<String, Object> arg5,
43 OutputStream stream) throws IOException, WebApplicationException {
44 byte[] bytes = dateToString(date).getBytes();
45 stream.write(bytes);
46 }
47
48 @Override
49 public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2,
50 MediaType arg3) {
51 return isWriteable(arg0, arg1, arg2, arg3);
52 }
53
54 @Override
55 public Date readFrom(Class<Date> arg0, Type arg1, Annotation[] arg2,
56 MediaType arg3, MultivaluedMap<String, String> arg4,
57 InputStream arg5) throws IOException, WebApplicationException {
58 InputStreamReader reader = new InputStreamReader(arg5);
59 BufferedReader br = new BufferedReader(reader);
60 String data = br.readLine();
61 String[] split = data == null ? new String[]{"0"} : data
62 .split(ResponseGetAnnotationsDateContainerReaderWriter.SPLITTER);
63 long date = Long.parseLong(split[0]);
64 atom.append(split[1]);
65 return new Date(date);
66 }
67
68 public static final String dateToString(Date date) {
69 return String.valueOf(date.getTime());
70 }
71 }
+0
-91
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseGetAnnotationsDateContainerReaderWriter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyReader;
9 import javax.ws.rs.ext.MessageBodyWriter;
10 import javax.ws.rs.ext.Provider;
11 import java.io.BufferedReader;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.InputStreamReader;
15 import java.io.OutputStream;
16 import java.lang.annotation.Annotation;
17 import java.lang.reflect.Type;
18 import java.util.Date;
19
20 @Provider
21 @Produces("*/*")
22 public class ResponseGetAnnotationsDateContainerReaderWriter implements MessageBodyReader<Date>,
23 MessageBodyWriter<Date> {
24
25 private static Logger logger = Logger.getLogger(ResponseGetAnnotationsDateContainerReaderWriter.class);
26 public static final String SPLITTER = " ANNOTATION_VALUE ";
27
28 @Override
29 public long getSize(Date arg0, Class<?> arg1, Type arg2, Annotation[] arg3,
30 MediaType arg4) {
31 Annotation[] annotations = ResponseGetAnnotationsAnnotatedClass.class.getAnnotations();
32 int size = String.valueOf(Long.MAX_VALUE).length() + SPLITTER.length()
33 + annotations[0].annotationType().getName().length()
34 + annotations[1].annotationType().getName().length();
35 logger.info("getSize() " + size);
36 return size;
37 }
38
39 @Override
40 public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2,
41 MediaType arg3) {
42 return arg0 == Date.class;
43 }
44
45 @Override
46 public void writeTo(Date date, Class<?> arg1, Type arg2, Annotation[] arg3,
47 MediaType arg4, MultivaluedMap<String, Object> arg5,
48 OutputStream stream) throws IOException, WebApplicationException {
49 String annotation = parseAnnotations(arg3);
50 byte[] bytes = dateToString(date).getBytes();
51 byte[] bytes1 = SPLITTER.getBytes();
52 byte[] bytes2 = annotation.getBytes();
53
54 logger.info("*** bytes to write " + (bytes.length + bytes1.length + bytes2.length));
55 stream.write(bytes);
56 stream.write(bytes1);
57 stream.write(bytes2);
58 }
59
60 @Override
61 public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2,
62 MediaType arg3) {
63 return isWriteable(arg0, arg1, arg2, arg3);
64 }
65
66 @Override
67 public Date readFrom(Class<Date> arg0, Type arg1, Annotation[] arg2,
68 MediaType arg3, MultivaluedMap<String, String> arg4,
69 InputStream arg5) throws IOException, WebApplicationException {
70 InputStreamReader reader = new InputStreamReader(arg5);
71 BufferedReader br = new BufferedReader(reader);
72 long date = Long.parseLong(br.readLine());
73 return new Date(date);
74 }
75
76 protected String parseAnnotations(Annotation[] annotations) {
77 StringBuilder value = new StringBuilder();
78 if (annotations != null) {
79 for (Annotation annotation : annotations) {
80 value.append(annotation.annotationType().getName())
81 .append(", ");
82 }
83 }
84 return value.toString();
85 }
86
87 public static final String dateToString(Date date) {
88 return String.valueOf(date.getTime());
89 }
90 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/ResponseGetAnnotationsResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5 import java.lang.annotation.Annotation;
6 import java.util.Date;
7
8 @Path("/")
9 public class ResponseGetAnnotationsResource {
10 @POST
11 @Path("entity")
12 public Response entity(Date date) {
13 Annotation[] annotations = ResponseGetAnnotationsAnnotatedClass.class.getAnnotations();
14 Response response = Response.ok().entity(date, annotations).build();
15 return response;
16 }
17
18 }
+0
-40
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/SetRequestUriRequestFilter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.annotation.Priority;
3 import javax.ws.rs.container.ContainerRequestContext;
4 import javax.ws.rs.container.ContainerRequestFilter;
5 import javax.ws.rs.container.PreMatching;
6 import javax.ws.rs.core.Response;
7 import javax.ws.rs.core.UriInfo;
8 import javax.ws.rs.ext.Provider;
9 import java.io.IOException;
10 import java.net.URI;
11
12 @Provider
13 @Priority(100)
14 @PreMatching
15 public class SetRequestUriRequestFilter implements ContainerRequestFilter {
16 @Override
17 public void filter(ContainerRequestContext requestContext) throws IOException {
18 if ("https".equalsIgnoreCase(requestContext.getHeaderString("X-Forwarded-Proto"))) {
19 requestContext.setRequestUri(
20 requestContext.getUriInfo().getBaseUriBuilder().scheme("https").build(),
21 requestContext.getUriInfo().getRequestUriBuilder().scheme("https").build());
22 } else if (requestContext.getUriInfo().getPath().contains("setrequesturi1")) {
23 requestContext.setRequestUri(
24 requestContext.getUriInfo().getRequestUriBuilder().path("uri").build());
25 } else if (requestContext.getUriInfo().getPath().contains("setrequesturi2")) {
26 requestContext.setRequestUri(URI.create("http://localhost:888/otherbase"),
27 URI.create("http://xx.yy:888/base/resource/sub"));
28 UriInfo info = requestContext.getUriInfo();
29 abortWithEntity(requestContext, info.getAbsolutePath().toASCIIString());
30 }
31 }
32
33 protected void abortWithEntity(ContainerRequestContext requestContext, String entity) {
34 StringBuilder sb = new StringBuilder();
35 sb.append(entity);
36 Response response = Response.ok(sb.toString()).build();
37 requestContext.abortWith(response);
38 }
39 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/SetRequestUriResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Context;
5 import javax.ws.rs.core.UriInfo;
6
7 @Path("base/resource")
8 public class SetRequestUriResource {
9
10 @Context
11 protected UriInfo uriInfo;
12
13 @GET
14 @Path("setrequesturi1/uri")
15 public String setRequestUri() {
16 return "OK";
17 }
18
19 @GET
20 @Path("setrequesturi1")
21 public String setRequestUriDidNotChangeUri() {
22 return "Filter did not change the uri to go to";
23 }
24
25 @GET
26 @Path("change")
27 public String changeProtocol() {
28 return uriInfo.getAbsolutePath().toString();
29 }
30 }
+0
-75
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/SingletonCustomProviderApplication.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2
3 import javax.ws.rs.ApplicationPath;
4 import javax.ws.rs.WebApplicationException;
5 import javax.ws.rs.core.Application;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyReader;
9 import javax.ws.rs.ext.MessageBodyWriter;
10 import javax.ws.rs.ext.Provider;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.OutputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.util.HashSet;
17 import java.util.Set;
18
19 @Provider
20 @ApplicationPath("/")
21 public class SingletonCustomProviderApplication extends Application {
22
23 public static Set<Class<?>> classes = new HashSet<Class<?>>();
24 public static Set<Object> singletons = new HashSet<Object>();
25
26 /**
27 * @see Application#getClasses()
28 */
29 @Override
30 public Set<Class<?>> getClasses() {
31 if (classes.isEmpty()) {
32 classes.add(SingletonCustomProviderResource.class);
33 }
34 return classes;
35 }
36
37 /**
38 * @see Application#getSingletons()
39 */
40 @Override
41 public Set<Object> getSingletons() {
42 if (singletons.isEmpty()) {
43 singletons.add(new MessageBodyReader<SingletonCustomProviderObject>() {
44 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediType) {
45 return true;
46 }
47
48 public SingletonCustomProviderObject readFrom(Class<SingletonCustomProviderObject> type, Type genericType, Annotation[] annotations,
49 MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
50 throws IOException, WebApplicationException {
51 throw new WebApplicationException(999); // deliberate crazy status
52 }
53
54 });
55 singletons.add(new MessageBodyWriter<SingletonCustomProviderObject>() {
56 public long getSize(SingletonCustomProviderObject dummyObject, Class<?> type, Type genericType, Annotation[] annotations,
57 MediaType mediaType) {
58 return -1;
59 }
60
61 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
62 return true;
63 }
64
65 public void writeTo(SingletonCustomProviderObject t, Class<?> type, Type genericType, Annotation[] annotations,
66 MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
67 throws IOException, WebApplicationException {
68 throw new WebApplicationException(999); // deliberate crazy status
69 }
70 });
71 }
72 return singletons;
73 }
74 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/SingletonCustomProviderObject.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 public class SingletonCustomProviderObject {
3
4 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/SingletonCustomProviderResource.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7
8 @Path("/test")
9 public class SingletonCustomProviderResource {
10
11 @POST
12 @Consumes("application/octet-stream")
13 public void testConsume(SingletonCustomProviderObject foo) {
14 }
15
16
17 @GET
18 @Produces("application/octet-stream")
19 public SingletonCustomProviderObject testProduce() {
20 return new SingletonCustomProviderObject();
21 }
22
23 }
+0
-55
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/custom/resource/WriterNotBuiltinTestWriter.java less more
0 package org.jboss.resteasy.test.providers.custom.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.plugins.providers.ProviderHelper;
4 import org.jboss.resteasy.util.TypeConverter;
5
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.WebApplicationException;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.MultivaluedMap;
11 import javax.ws.rs.ext.MessageBodyReader;
12 import javax.ws.rs.ext.MessageBodyWriter;
13 import javax.ws.rs.ext.Provider;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.OutputStream;
17 import java.lang.annotation.Annotation;
18 import java.lang.reflect.Type;
19
20 @Provider
21 @Produces("*/*")
22 @Consumes("*/*")
23 public class WriterNotBuiltinTestWriter implements MessageBodyWriter, MessageBodyReader {
24 private static Logger logger = Logger.getLogger(WriterNotBuiltinTestWriter.class);
25
26 public static boolean used;
27
28 public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
29 return true;
30 }
31
32 public long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
33 return o.toString().getBytes().length;
34 }
35
36 public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
37 entityStream.write(o.toString().getBytes());
38 logger.info("my writeTo");
39 used = true;
40 }
41
42 public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
43 return true;
44 }
45
46 @SuppressWarnings(value = "unchecked")
47 public Object readFrom(Class type, Type genericType,
48 Annotation[] annotations, MediaType mediaType,
49 MultivaluedMap httpHeaders, InputStream entityStream)
50 throws IOException, WebApplicationException {
51 String value = ProviderHelper.readString(entityStream, mediaType);
52 return TypeConverter.getType(type, value);
53 }
54 }
+0
-93
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/inputstream/InputStreamCloseTest.java less more
0 package org.jboss.resteasy.test.providers.inputstream;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.providers.inputstream.resource.InputStreamCloseInputStream;
10 import org.jboss.resteasy.test.providers.inputstream.resource.InputStreamCloseResource;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.core.Response;
23
24 /**
25 * @tpSubChapter Configuration
26 * @tpChapter Integration tests
27 * @tpTestCaseDetails Regression test for RESTEASY-741
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class InputStreamCloseTest {
33
34 static ResteasyClient client;
35
36 @Deployment
37 public static Archive<?> deploy() {
38 WebArchive war = TestUtil.prepareArchive(InputStreamCloseTest.class.getSimpleName());
39 war.addClass(InputStreamCloseInputStream.class);
40 return TestUtil.finishContainerPrepare(war, null, InputStreamCloseResource.class);
41 }
42
43 private String generateURL(String path) {
44 return PortProviderUtil.generateURL(path, InputStreamCloseTest.class.getSimpleName());
45 }
46
47 @Before
48 public void init() {
49 client = new ResteasyClientBuilder().build();
50 }
51
52 @After
53 public void after() throws Exception {
54 client.close();
55 }
56
57 /**
58 * @tpTestDetails Old client test
59 * @tpSince RESTEasy 3.0.16
60 */
61 @Test
62 public void oldClient() throws Exception {
63 // Resource creates and returns InputStream.
64 ClientRequest request = new ClientRequest(generateURL("/create/"));
65 ClientResponse<?> response = request.get(String.class);
66 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
67 Assert.assertEquals("hello", response.getEntity());
68
69 // Verify previously created InputStream has been closed.
70 request = new ClientRequest(generateURL("/test/"));
71 response = request.get();
72 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
73 }
74
75 /**
76 * @tpTestDetails New client test
77 * @tpSince RESTEasy 3.0.16
78 */
79 @Test
80 public void newClient() throws Exception {
81 // Resource creates and returns InputStream.
82 Response response = client.target(generateURL("/create/")).request().get();
83 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
84 Assert.assertEquals("hello", response.readEntity(String.class));
85 response.close();
86
87 // Verify previously created InputStream has been closed.
88 response = client.target(generateURL("/test/")).request().get();
89 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
90 response.close();
91 }
92 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/inputstream/resource/InputStreamCloseInputStream.java less more
0 package org.jboss.resteasy.test.providers.inputstream.resource;
1
2 import java.io.ByteArrayInputStream;
3 import java.io.IOException;
4
5 public class InputStreamCloseInputStream extends ByteArrayInputStream {
6 private boolean closed;
7
8 public InputStreamCloseInputStream(final byte[] b) {
9 super(b);
10 }
11
12 public void close() throws IOException {
13 super.close();
14 closed = true;
15 }
16
17 public boolean isClosed() {
18 return closed;
19 }
20 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/inputstream/resource/InputStreamCloseResource.java less more
0 package org.jboss.resteasy.test.providers.inputstream.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Response;
6 import java.io.InputStream;
7
8 @Path("/")
9 public class InputStreamCloseResource {
10 private static InputStreamCloseInputStream inputStream;
11
12 @GET
13 @Produces("text/plain")
14 @Path("create")
15 public InputStream create() {
16 inputStream = new InputStreamCloseInputStream("hello".getBytes());
17 return inputStream;
18 }
19
20 @GET
21 @Path("test")
22 public Response test() {
23 return (inputStream.isClosed() ? Response.ok().build() : Response.serverError().build());
24 }
25 }
+0
-240
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/JacksonTest.java less more
0 package org.jboss.resteasy.test.providers.jackson;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.providers.jackson.resource.JacksonJAXBResource;
9 import org.jboss.resteasy.test.providers.jackson.resource.JacksonProduct;
10 import org.jboss.resteasy.test.providers.jackson.resource.JacksonXmlProduct;
11 import org.jboss.resteasy.test.providers.jackson.resource.JacksonXmlResource;
12 import org.jboss.resteasy.test.providers.jackson.resource.JacksonXmlResourceWithJacksonAnnotation;
13 import org.jboss.resteasy.test.providers.jackson.resource.JacksonXmlResourceWithJAXB;
14 import org.jboss.resteasy.test.providers.jackson.resource.JacksonResource;
15 import org.jboss.resteasy.util.HttpResponseCodes;
16 import org.jboss.resteasy.utils.PortProviderUtil;
17 import org.jboss.resteasy.utils.TestUtil;
18 import org.jboss.shrinkwrap.api.Archive;
19 import org.jboss.shrinkwrap.api.spec.WebArchive;
20 import org.junit.Test;
21 import org.junit.Before;
22 import org.junit.After;
23 import org.junit.Assert;
24 import org.junit.AfterClass;
25 import org.junit.runner.RunWith;
26
27 import javax.ws.rs.Consumes;
28 import javax.ws.rs.GET;
29 import javax.ws.rs.POST;
30 import javax.ws.rs.Path;
31 import javax.ws.rs.PathParam;
32 import javax.ws.rs.Produces;
33 import javax.ws.rs.client.Entity;
34 import javax.ws.rs.client.WebTarget;
35 import javax.ws.rs.core.Response;
36
37 /**
38 * @tpSubChapter Jackson provider
39 * @tpChapter Integration tests
40 * @tpSince RESTEasy 3.0.16
41 */
42 @RunWith(Arquillian.class)
43 @RunAsClient
44 public class JacksonTest {
45
46 protected static final Logger logger = Logger.getLogger(JacksonTest.class.getName());
47 private static final String JETTISON_DEPLOYMENT = "jettison";
48
49 @Path("/products")
50 public interface JacksonProxy {
51 @GET
52 @Produces("application/json")
53 @Path("{id}")
54 JacksonProduct getProduct();
55
56 @GET
57 @Produces("application/json")
58 JacksonProduct[] getProducts();
59
60 @POST
61 @Produces("application/foo+json")
62 @Consumes("application/foo+json")
63 @Path("{id}")
64 JacksonProduct post(@PathParam("id") int id, JacksonProduct p);
65 }
66
67
68 static ResteasyClient client;
69
70 @Deployment(name = "default")
71 public static Archive<?> deploy() {
72 WebArchive war = TestUtil.prepareArchive(JacksonTest.class.getSimpleName());
73 war.addClass(JacksonTest.class);
74 war.addAsManifestResource("jboss-deployment-structure-jackson-v1.xml", "jboss-deployment-structure.xml");
75 return TestUtil.finishContainerPrepare(war, null, JacksonResource.class, JacksonProduct.class,
76 JacksonXmlResource.class, JacksonXmlProduct.class, JacksonJAXBResource.class,
77 JacksonXmlResourceWithJacksonAnnotation.class, JacksonXmlResourceWithJAXB.class);
78 }
79
80 /**
81 * Jettison is deprecated, so it needs to be added to EAP manually (see JBEAP-2856).
82 */
83 @Deployment(name = "jettison")
84 public static Archive<?> deployJettison() {
85 WebArchive war = TestUtil.prepareArchive(JETTISON_DEPLOYMENT);
86 war.addClass(JacksonTest.class);
87 war.addAsManifestResource("jboss-deployment-structure-jackson-v1-jettison.xml", "jboss-deployment-structure.xml");
88 return TestUtil.finishContainerPrepare(war, null, JacksonResource.class, JacksonProduct.class,
89 JacksonXmlResource.class, JacksonXmlProduct.class, JacksonJAXBResource.class,
90 JacksonXmlResourceWithJacksonAnnotation.class, JacksonXmlResourceWithJAXB.class);
91 }
92
93 @Before
94 public void init() {
95 client = new ResteasyClientBuilder().build();
96 }
97
98 @After
99 public void after() throws Exception {
100 client.close();
101 }
102
103 private String generateURL(String path) {
104 return PortProviderUtil.generateURL(path, JacksonTest.class.getSimpleName());
105 }
106
107
108 @AfterClass
109 public static void shutdown() throws Exception {
110 client.close();
111 }
112
113 /**
114 * @tpTestDetails Client sends GET request for json annotated resource. In the first case it returns single json entity,
115 * in the second case multiple json entities as String.
116 * @tpPassCrit The resource returns json entities in correct format
117 * @tpSince RESTEasy 3.0.16
118 */
119 @Test
120 public void testJacksonString() throws Exception {
121 WebTarget target = client.target(generateURL("/products/333"));
122 Response response = target.request().get();
123 String entity = response.readEntity(String.class);
124 logger.info(entity);
125 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
126 Assert.assertEquals("The response entity content doesn't match the expected",
127 "{\"name\":\"Iphone\",\"id\":333}", entity);
128 response.close();
129
130 target = client.target(generateURL("/products"));
131 response = target.request().get();
132 entity = response.readEntity(String.class);
133 logger.info(entity);
134 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
135 Assert.assertEquals("The response entity content doesn't match the expected",
136 "[{\"name\":\"Iphone\",\"id\":333},{\"name\":\"macbook\",\"id\":44}]", entity);
137 response.close();
138 }
139
140 /**
141 * @tpTestDetails Client sends GET request for json annotated resource. The resource is annotated with @BadgerFish
142 * and @NoJackson annotations. The jettison provider should be triggered instead of jackson one.
143 * Jettison is deprecated, so it needs to be added to EAP manually (see JBEAP-2856).
144 * @tpPassCrit The resource returns json entities in correct format
145 * @tpInfo JBEAP-2856
146 * @tpSince RESTEasy 3.0.16
147 */
148 @Test
149 public void testXmlString() throws Exception {
150 WebTarget target = client.target(PortProviderUtil.generateURL("/xml/products/333", JETTISON_DEPLOYMENT));
151 Response response = target.request().get();
152 String entity = response.readEntity(String.class);
153 logger.info(entity);
154 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-2856"), HttpResponseCodes.SC_OK, response.getStatus());
155 Assert.assertTrue("Entity doesn't have json format", entity.startsWith("{\"product"));
156 response.close();
157
158 target = client.target(PortProviderUtil.generateURL("/xml/products", JETTISON_DEPLOYMENT));
159 Response response2 = target.request().get();
160 String entity2 = response2.readEntity(String.class);
161 logger.info(entity2);
162 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-2856"), HttpResponseCodes.SC_OK, response2.getStatus());
163 Assert.assertTrue("Entity doesn't have json format", entity2.startsWith("[{\"product"));
164 response2.close();
165 }
166
167 /**
168 * @tpTestDetails Client sends GET and POST request for json annotated resource. For the response processing is used jackson
169 * provider. There are three types of response in this test:
170 * + The response entity is returned as instance of JacksonProduct class.
171 * + The response entity is returned as instance of String class
172 * + The response entity is returned as instance of JacksonProduct class and response is mediatype of 'application/foo+json'
173 * @tpPassCrit The returned object contains expected values
174 * @tpSince RESTEasy 3.0.16
175 */
176 @Test
177 public void testJackson() throws Exception {
178 WebTarget target = client.target(generateURL("/products/333"));
179 Response response = target.request().get();
180 JacksonProduct p = response.readEntity(JacksonProduct.class);
181 Assert.assertEquals("JacksonProduct id value doesn't match", 333, p.getId());
182 Assert.assertEquals("JacksonProduct name value doesn't match", "Iphone", p.getName());
183 response.close();
184
185 target = client.target(generateURL("/products"));
186 response = target.request().get();
187 String entity = response.readEntity(String.class);
188 logger.info(entity);
189 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
190 response.close();
191
192 target = client.target(generateURL("/products/333"));
193 response = target.request().post(Entity.entity(p, "application/foo+json"));
194 p = response.readEntity(JacksonProduct.class);
195 Assert.assertEquals("JacksonProduct id value doesn't match", 333, p.getId());
196 Assert.assertEquals("JacksonProduct name value doesn't match", "Iphone", p.getName());
197 response.close();
198
199
200 }
201
202 /**
203 * @tpTestDetails Client sends POST request with JacksonProduct entity using client proxy.
204 * @tpPassCrit The returned object contains expected values
205 * @tpSince RESTEasy 3.0.16
206 */
207 @Test
208 public void testJacksonProxy() throws Exception {
209 JacksonProxy proxy = client.target(generateURL("")).proxy(JacksonProxy.class);
210 JacksonProduct p = new JacksonProduct(1, "Stuff");
211 p = proxy.post(1, p);
212 Assert.assertEquals("JacksonProduct id value doesn't match", 1, p.getId());
213 Assert.assertEquals("JacksonProduct name value doesn't match", "Stuff", p.getName());
214 }
215
216 /**
217 * @tpTestDetails Client has both, JAXB and Jackson v.1 providers on the classpath. First it sends GET request for
218 * JAXB annotated resource and verifies renaming of the Xml element attribute. Second it sends GET request for resource
219 * with Jackson annotation and verifies that json response contains the renamed attribute.
220 * @tpPassCrit The response contains the renamed attributes
221 * @tpSince RESTEasy 3.0.16
222 */
223 @Test
224 public void testJacksonJAXB() throws Exception {
225 {
226 WebTarget target = client.target(generateURL("/jaxb"));
227 String response = target.request().get(String.class);
228 logger.info(response);
229 Assert.assertTrue("The response doesn't contain the renamed attribute", response.contains("attr_1"));
230 }
231
232 {
233 WebTarget target = client.target(generateURL("/jaxb/json"));
234 String response = target.request().get(String.class);
235 logger.info(response);
236 Assert.assertTrue("The response doesn't contain the renamed attribute", response.contains("attr_1"));
237 }
238 }
239 }
+0
-103
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/ProxyWithGenericReturnTypeJacksonTest.java less more
0 package org.jboss.resteasy.test.providers.jackson;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
7 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
8 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.test.providers.jackson.resource.ProxyWithGenericReturnTypeJacksonAbstractParent;
11 import org.jboss.resteasy.test.providers.jackson.resource.ProxyWithGenericReturnTypeJacksonInvocationHandler;
12 import org.jboss.resteasy.test.providers.jackson.resource.ProxyWithGenericReturnTypeJacksonResource;
13 import org.jboss.resteasy.test.providers.jackson.resource.ProxyWithGenericReturnTypeJacksonSubResourceIntf;
14 import org.jboss.resteasy.test.providers.jackson.resource.ProxyWithGenericReturnTypeJacksonSubResourceSubIntf;
15 import org.jboss.resteasy.test.providers.jackson.resource.ProxyWithGenericReturnTypeJacksonType1;
16 import org.jboss.resteasy.test.providers.jackson.resource.ProxyWithGenericReturnTypeJacksonType2;
17 import org.jboss.resteasy.util.HttpResponseCodes;
18 import org.jboss.resteasy.utils.PortProviderUtil;
19 import org.jboss.resteasy.utils.TestUtil;
20 import org.jboss.shrinkwrap.api.Archive;
21 import org.jboss.shrinkwrap.api.spec.WebArchive;
22 import org.junit.After;
23 import org.junit.Assert;
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.junit.runner.RunWith;
27 import javax.ws.rs.core.Response;
28
29 /**
30 * @tpSubChapter Jackson provider
31 * @tpChapter Integration tests
32 * @tpTestCaseDetails Test jackson1 provider with proxy with generic return type
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class ProxyWithGenericReturnTypeJacksonTest {
38
39 protected static final Logger logger = Logger.getLogger(ProxyWithGenericReturnTypeJacksonTest.class.getName());
40
41 static ResteasyClient client;
42
43 @Deployment
44 public static Archive<?> deploy() {
45 WebArchive war = TestUtil.prepareArchive(ProxyWithGenericReturnTypeJacksonTest.class.getSimpleName());
46 war.addClasses(ProxyWithGenericReturnTypeJacksonAbstractParent.class, ProxyWithGenericReturnTypeJacksonInvocationHandler.class,
47 ProxyWithGenericReturnTypeJacksonSubResourceIntf.class, ProxyWithGenericReturnTypeJacksonSubResourceSubIntf.class,
48 ProxyWithGenericReturnTypeJacksonType1.class, ProxyWithGenericReturnTypeJacksonType2.class);
49 war.addAsManifestResource("jboss-deployment-structure-jackson-v1.xml", "jboss-deployment-structure.xml");
50 return TestUtil.finishContainerPrepare(war, null, ProxyWithGenericReturnTypeJacksonResource.class);
51 }
52
53 @Before
54 public void init() {
55 client = new ResteasyClientBuilder().build();
56 }
57
58 @After
59 public void after() throws Exception {
60 client.close();
61 }
62
63 private String generateURL(String path) {
64 return PortProviderUtil.generateURL(path, ProxyWithGenericReturnTypeJacksonTest.class.getSimpleName());
65 }
66
67 /**
68 * @tpTestDetails Test new client
69 * @tpSince RESTEasy 3.0.16
70 */
71 @Test
72 public void testNewClient() throws Exception {
73 Response response = client.target(generateURL("/test/one/")).request().get();
74 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
75 Assert.assertTrue("Type property is missing.", response.readEntity(String.class).contains("type"));
76 response.close();
77
78 response = client.target(generateURL("/test/list/")).request().get();
79 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
80 Assert.assertTrue("Type property is missing.", response.readEntity(String.class).contains("type"));
81 response.close();
82 }
83
84 /**
85 * @tpTestDetails Test old client
86 * @tpSince RESTEasy 3.0.16
87 */
88 @Test
89 public void testOldClient() throws Exception {
90 ClientRequest request = new ClientRequest(generateURL("/test/one/"));
91 ClientResponse<String> response = request.get(String.class);
92 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
93 Assert.assertTrue("Type property is missing.", response.getEntity(String.class).contains("type"));
94 response.releaseConnection();
95
96 request = new ClientRequest(generateURL("/test/list/"));
97 response = request.get(String.class);
98 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
99 Assert.assertTrue("Type property is missing.", response.getEntity(String.class).contains("type"));
100 response.releaseConnection();
101 }
102 }
+0
-30
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/JacksonJAXBResource.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/jaxb")
7 public class JacksonJAXBResource {
8
9 @GET
10 @Produces("application/json")
11 public JacksonXmlResourceWithJAXB getJAXBResource() {
12 JacksonXmlResourceWithJAXB resourceWithJAXB = new JacksonXmlResourceWithJAXB();
13 resourceWithJAXB.setAttr1("XXX");
14 resourceWithJAXB.setAttr2("YYY");
15 return resourceWithJAXB;
16 }
17
18
19 @GET
20 @Path(("/json"))
21 @Produces("application/json")
22 public JacksonXmlResourceWithJacksonAnnotation getJacksonAnnotatedResource() {
23 JacksonXmlResourceWithJacksonAnnotation resource = new JacksonXmlResourceWithJacksonAnnotation();
24 resource.setAttr1("XXX");
25 resource.setAttr2("YYY");
26 return resource;
27 }
28
29 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/JacksonProduct.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 public class JacksonProduct {
3 protected String name;
4
5 protected int id;
6
7 public JacksonProduct() {
8 }
9
10 public JacksonProduct(final int id, final String name) {
11 this.id = id;
12 this.name = name;
13 }
14
15 public String getName() {
16 return name;
17 }
18
19 public void setName(String name) {
20 this.name = name;
21 }
22
23 public int getId() {
24 return id;
25 }
26
27 public void setId(int id) {
28 this.id = id;
29 }
30 }
+0
-35
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/JacksonResource.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Consumes;
7
8 @Path("/products")
9 public class JacksonResource {
10
11 @GET
12 @Produces("application/json")
13 @Path("{id}")
14 public JacksonProduct getProduct() {
15 return new JacksonProduct(333, "Iphone");
16 }
17
18 @GET
19 @Produces("application/json")
20 public JacksonProduct[] getProducts() {
21
22 JacksonProduct[] products = {new JacksonProduct(333, "Iphone"), new JacksonProduct(44, "macbook")};
23 return products;
24 }
25
26 @POST
27 @Produces("application/foo+json")
28 @Consumes("application/foo+json")
29 @Path("{id}")
30 public JacksonProduct post(JacksonProduct p) {
31 return p;
32 }
33
34 }
+0
-43
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/JacksonXmlProduct.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import org.jboss.resteasy.annotations.providers.NoJackson;
3
4 import javax.xml.bind.annotation.XmlAccessType;
5 import javax.xml.bind.annotation.XmlAccessorType;
6 import javax.xml.bind.annotation.XmlAttribute;
7 import javax.xml.bind.annotation.XmlRootElement;
8
9 @XmlRootElement(name = "product")
10 @XmlAccessorType(XmlAccessType.FIELD)
11 @NoJackson
12 public class JacksonXmlProduct {
13 @XmlAttribute
14 protected String name;
15
16 @XmlAttribute
17 protected int id;
18
19 public JacksonXmlProduct() {
20 }
21
22 public JacksonXmlProduct(final int id, final String name) {
23 this.id = id;
24 this.name = name;
25 }
26
27 public String getName() {
28 return name;
29 }
30
31 public void setName(String name) {
32 this.name = name;
33 }
34
35 public int getId() {
36 return id;
37 }
38
39 public void setId(int id) {
40 this.id = id;
41 }
42 }
+0
-30
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/JacksonXmlResource.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import org.jboss.resteasy.annotations.providers.NoJackson;
3 import org.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8
9 @Path("/xml/products")
10 public class JacksonXmlResource {
11
12 @BadgerFish
13 @GET
14 @Produces("application/json")
15 @Path("{id}")
16 public JacksonXmlProduct getProduct() {
17 return new JacksonXmlProduct(333, "Iphone");
18 }
19
20 @GET
21 @Produces("application/json")
22 @NoJackson
23 public JacksonXmlProduct[] getProducts() {
24
25 JacksonXmlProduct[] products = {new JacksonXmlProduct(333, "Iphone"), new JacksonXmlProduct(44, "macbook")};
26 return products;
27 }
28
29 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/JacksonXmlResourceWithJAXB.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import javax.xml.bind.annotation.XmlElement;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement
6 public class JacksonXmlResourceWithJAXB {
7 String attr1;
8 String attr2;
9
10 @XmlElement(name = "attr_1")
11 public String getAttr1() {
12 return attr1;
13 }
14
15 public void setAttr1(String attr1) {
16 this.attr1 = attr1;
17 }
18
19 @XmlElement
20 public String getAttr2() {
21 return attr2;
22 }
23
24 public void setAttr2(String attr2) {
25 this.attr2 = attr2;
26 }
27 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/JacksonXmlResourceWithJacksonAnnotation.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import org.codehaus.jackson.annotate.JsonProperty;
3
4 import javax.xml.bind.annotation.XmlElement;
5
6 public class JacksonXmlResourceWithJacksonAnnotation {
7 String attr1;
8 String attr2;
9
10 @JsonProperty("attr_1")
11 public String getAttr1() {
12 return attr1;
13 }
14
15 public void setAttr1(String attr1) {
16 this.attr1 = attr1;
17 }
18
19 @XmlElement
20 public String getAttr2() {
21 return attr2;
22 }
23
24 public void setAttr2(String attr2) {
25 this.attr2 = attr2;
26 }
27 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/ProxyWithGenericReturnTypeJacksonAbstractParent.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import org.codehaus.jackson.annotate.JsonSubTypes;
3 import org.codehaus.jackson.annotate.JsonTypeInfo;
4
5 @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
6 @JsonSubTypes({
7 @JsonSubTypes.Type(value = ProxyWithGenericReturnTypeJacksonType1.class, name = "type1"),
8 @JsonSubTypes.Type(value = ProxyWithGenericReturnTypeJacksonType2.class, name = "type2")})
9 public abstract class ProxyWithGenericReturnTypeJacksonAbstractParent {
10
11 protected long id;
12
13 public long getId() {
14 return id;
15 }
16
17 public void setId(long id) {
18 this.id = id;
19 }
20 }
+0
-34
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/ProxyWithGenericReturnTypeJacksonInvocationHandler.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import java.lang.reflect.InvocationHandler;
3 import java.lang.reflect.Method;
4 import java.util.ArrayList;
5 import java.util.List;
6
7 public class ProxyWithGenericReturnTypeJacksonInvocationHandler implements InvocationHandler {
8 @Override
9 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
10 if ("resourceMethod".equals(method.getName())) {
11 List<ProxyWithGenericReturnTypeJacksonAbstractParent> l = new ArrayList<ProxyWithGenericReturnTypeJacksonAbstractParent>();
12 ProxyWithGenericReturnTypeJacksonType1 first = new ProxyWithGenericReturnTypeJacksonType1();
13 first.setId(1);
14 first.setName("MyName");
15 l.add(first);
16
17 ProxyWithGenericReturnTypeJacksonType2 second = new ProxyWithGenericReturnTypeJacksonType2();
18 second.setId(2);
19 second.setNote("MyNote");
20 l.add(second);
21 return l;
22 }
23
24 if ("resourceMethodOne".equals(method.getName())) {
25 ProxyWithGenericReturnTypeJacksonType1 first = new ProxyWithGenericReturnTypeJacksonType1();
26 first.setId(1);
27 first.setName("MyName");
28 return first;
29 }
30
31 return null;
32 }
33 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/ProxyWithGenericReturnTypeJacksonResource.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.Produces;
4 import java.lang.reflect.Proxy;
5
6 @Path("/")
7 public class ProxyWithGenericReturnTypeJacksonResource {
8 @Produces("text/plain")
9 @Path("test")
10 public ProxyWithGenericReturnTypeJacksonSubResourceSubIntf resourceLocator() {
11 Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
12 new Class[]{ProxyWithGenericReturnTypeJacksonSubResourceSubIntf.class},
13 new ProxyWithGenericReturnTypeJacksonInvocationHandler());
14
15 return ProxyWithGenericReturnTypeJacksonSubResourceSubIntf.class.cast(proxy);
16 }
17 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/ProxyWithGenericReturnTypeJacksonSubResourceIntf.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import java.util.List;
6
7 public interface ProxyWithGenericReturnTypeJacksonSubResourceIntf {
8 @GET
9 @Path("list")
10 @Produces("application/*+json")
11 List<ProxyWithGenericReturnTypeJacksonAbstractParent> resourceMethod();
12
13 @GET
14 @Path("one")
15 @Produces("application/*+json")
16 ProxyWithGenericReturnTypeJacksonAbstractParent resourceMethodOne();
17 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/ProxyWithGenericReturnTypeJacksonSubResourceSubIntf.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 public interface ProxyWithGenericReturnTypeJacksonSubResourceSubIntf extends ProxyWithGenericReturnTypeJacksonSubResourceIntf {
3 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/ProxyWithGenericReturnTypeJacksonType1.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 public class ProxyWithGenericReturnTypeJacksonType1 extends ProxyWithGenericReturnTypeJacksonAbstractParent {
3
4 protected String name;
5
6 public String getName() {
7 return name;
8 }
9
10 public void setName(String name) {
11 this.name = name;
12 }
13 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jackson/resource/ProxyWithGenericReturnTypeJacksonType2.java less more
0 package org.jboss.resteasy.test.providers.jackson.resource;
1
2 public class ProxyWithGenericReturnTypeJacksonType2 extends ProxyWithGenericReturnTypeJacksonAbstractParent {
3
4 protected String note;
5
6 public String getNote() {
7 return note;
8 }
9
10 public void setNote(String note) {
11 this.note = note;
12 }
13 }
+0
-87
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/AbstractJaxbClassTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.providers.jaxb.resource.AbstractJaxbClassPerson;
9 import org.jboss.resteasy.test.providers.jaxb.resource.AbstractJaxbClassCustomer;
10 import org.jboss.resteasy.test.providers.jaxb.resource.AbstractJaxbClassResource;
11 import org.jboss.resteasy.test.providers.jaxb.resource.AbstractJaxbClassCompanyCustomer;
12 import org.jboss.resteasy.test.providers.jaxb.resource.AbstractJaxbClassPrivatCustomer;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Before;
19 import org.junit.After;
20 import org.junit.Test;
21 import org.junit.Assert;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.core.Response;
26
27 /**
28 * @tpSubChapter Jaxb provider
29 * @tpChapter Integration tests
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class AbstractJaxbClassTest {
35
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(AbstractJaxbClassTest.class.getSimpleName());
41 return TestUtil.finishContainerPrepare(war, null, AbstractJaxbClassCompanyCustomer.class, AbstractJaxbClassCustomer.class,
42 AbstractJaxbClassPerson.class, AbstractJaxbClassPrivatCustomer.class, AbstractJaxbClassResource.class);
43 }
44
45 @Before
46 public void init() {
47 client = new ResteasyClientBuilder().build();
48 }
49
50 @After
51 public void after() throws Exception {
52 client.close();
53 }
54
55 private String generateURL(String path) {
56 return PortProviderUtil.generateURL(path, AbstractJaxbClassTest.class.getSimpleName());
57 }
58
59 private static final String customerXml = "<?xml version=\"1.0\"?>\n"
60 + "<abstractJaxbClassPrivatCustomer>\n"
61 + "<nachname>Test</nachname>\n"
62 + "<vorname>Theo</vorname>\n"
63 + "<seit>2001-01-31T00:00:00+01:00</seit>\n"
64 + "<adresse><plz>76133</plz><ort>Karlsruhe</ort><strasse>Moltkestrasse</strasse><hausnr>31</hausnr></adresse>\n"
65 + "</abstractJaxbClassPrivatCustomer>";
66
67 /**
68 * @tpTestDetails Test for Abstract jaxb class with @XmlSeeAlso annotation
69 * @tpInfo RESTEASY-126
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test
73 public void testPost() throws Exception {
74 ResteasyWebTarget target = client.target(generateURL(""));
75 String xmlInput = "<?xml version=\"1.0\"?><abstractJaxbClassPerson><name>bill</name></abstractJaxbClassPerson>";
76 Response response = target.request().post(Entity.xml(xmlInput));
77 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
78 response.close();
79
80 ResteasyWebTarget target2 = client.target(generateURL("/customer"));
81 Response response2 = target2.request().post(Entity.entity(customerXml, "application/xml"));
82 Assert.assertEquals(204, response2.getStatus());
83 response2.close();
84 }
85
86 }
+0
-124
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/BadContentTypeTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.providers.jaxb.resource.BadContentTypeTestBean;
10 import org.jboss.resteasy.test.providers.jaxb.resource.BadContenTypeTestResource;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.core.Response;
24
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertTrue;
27
28 /**
29 * @tpSubChapter Jaxb provider
30 * @tpChapter Integration tests
31 * @tpSince RESTEasy 3.0.16
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class BadContentTypeTest {
36
37 private static Logger logger = Logger.getLogger(BadContentTypeTest.class.getName());
38 static ResteasyClient client;
39
40 @Deployment
41 public static Archive<?> deploy() {
42 WebArchive war = TestUtil.prepareArchive(BadContentTypeTest.class.getSimpleName());
43 return TestUtil.finishContainerPrepare(war, null, BadContenTypeTestResource.class, BadContentTypeTestBean.class);
44 }
45
46 @Before
47 public void init() {
48 client = new ResteasyClientBuilder().build();
49 }
50
51 @After
52 public void after() throws Exception {
53 client.close();
54 }
55
56 private String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, BadContentTypeTest.class.getSimpleName());
58 }
59
60 /**
61 * @tpTestDetails Tests if correct Response code is returned when sending syntactically incorrect xml
62 * @tpInfo RESTEASY-519
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void testBadRequest() throws Exception {
67 ResteasyWebTarget target = client.target(generateURL("/test"));
68 Response response = target.request().post(Entity.entity("<junk", "application/xml"));
69 Assert.assertEquals("The returned response status is not the expected one",
70 Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
71 }
72
73 /**
74 * @tpTestDetails Tests if correct exception and MessageBodyWriter error is thrown when sending request for which no
75 * MessageBodyWriterExists
76 * @tpInfo RESTEASY-169
77 * @tpSince RESTEasy 3.0.16
78 */
79 @Test
80 public void testHtmlError() throws Exception {
81 ResteasyWebTarget target = client.target(generateURL("/test"));
82 Response response = target.request().header("Accept", "text/html").get();
83 String stringResp = response.readEntity(String.class);
84 logger.info("response: " + stringResp);
85 assertEquals("The returned response status is not the expected one",
86 HttpResponseCodes.SC_INTERNAL_SERVER_ERROR, response.getStatus());
87 assertTrue("The unexpected error response was thrown", stringResp.contains("media type: text/html"));
88 }
89
90 /**
91 * @tpTestDetails Tests if correct HTTP 406 status code is returned when the specified accept media type
92 * is not supported by the server
93 */
94 @Test
95 public void testNotAcceptable() throws Exception {
96 ResteasyWebTarget target = client.target(generateURL("/test/foo"));
97 Response response = target.request().header("Accept", "text/plain").get();
98 assertEquals("The returned response status is not the expected one",
99 HttpResponseCodes.SC_NOT_ACCEPTABLE, response.getStatus());
100 }
101
102 /**
103 * @tpTestDetails Tests of receiving Bad Request response code after html error
104 * @tpSince RESTEasy 3.0.16
105 */
106 @Test
107 public void testBadRequestAfterHtmlError() throws Exception {
108 ResteasyWebTarget target = client.target(generateURL("/test"));
109 Response response = target.request().post(Entity.entity("<junk", "application/xml"));
110 Assert.assertEquals("The returned response status is not the expected one",
111 Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
112 response.close();
113
114 response = target.request().header("Accept", "text/html").get();
115 String stringResp = response.readEntity(String.class);
116 logger.info("response: " + stringResp);
117 assertEquals("The returned response status is not the expected one",
118 HttpResponseCodes.SC_INTERNAL_SERVER_ERROR, response.getStatus());
119 assertTrue("The unexpected error response was thrown", stringResp.contains("media type: text/html"));
120
121 }
122
123 }
+0
-150
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/CharSetRE1066Test.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.core.Dispatcher;
10 import org.jboss.resteasy.spi.ResteasyDeployment;
11 import org.jboss.resteasy.test.providers.jaxb.resource.CharSetFavoriteMovieXmlRootElement;
12 import org.jboss.resteasy.test.providers.jaxb.resource.CharSetMovieResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.client.Invocation.Builder;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.Response;
28 import java.nio.charset.Charset;
29 import java.util.HashMap;
30 import java.util.Map;
31
32 /**
33 * @tpSubChapter Jaxb provider
34 * @tpChapter Integration tests
35 * @tpTestCaseDetails Regression test for RESTEASY-1066.
36 * @tpSince RESTEasy 3.0.16
37 */
38 @RunWith(Arquillian.class)
39 @RunAsClient
40 public class CharSetRE1066Test
41 {
42 protected static ResteasyDeployment deployment;
43 protected static Dispatcher dispatcher;
44 public static final MediaType APPLICATION_XML_UTF16_TYPE;
45 public static final MediaType TEXT_PLAIN_UTF16_TYPE;
46 public static final MediaType WILDCARD_UTF16_TYPE;
47 public static final String APPLICATION_XML_UTF16 = "application/xml;charset=UTF-16";
48 public static final String TEXT_PLAIN_UTF16 = "text/plain;charset=UTF-16";
49 public static final String WILDCARD_UTF16 = "*/*;charset=UTF-16";
50
51
52 private final Logger log = Logger.getLogger(CharSetRE1066Test.class.getName());
53 static ResteasyClient client;
54
55 @Deployment
56 public static Archive<?> deploy() {
57 WebArchive war = TestUtil.prepareArchive(CharSetRE1066Test.class.getSimpleName());
58 war.addClass(CharSetRE1066Test.class);
59 return TestUtil.finishContainerPrepare(war, null, CharSetMovieResource.class, CharSetFavoriteMovieXmlRootElement.class);
60 }
61
62 @Before
63 public void before() {
64 client = new ResteasyClientBuilder().build();
65 }
66
67 @After
68 public void after() {
69 client.close();
70 client = null;
71 }
72
73 private String generateURL(String path) {
74 return PortProviderUtil.generateURL(path, CharSetRE1066Test.class.getSimpleName());
75 }
76
77 static
78 {
79 Map<String, String> params = new HashMap<String, String>();
80 params.put("charset", "UTF-16");
81 APPLICATION_XML_UTF16_TYPE = new MediaType("application", "xml", params);
82 TEXT_PLAIN_UTF16_TYPE = new MediaType("text", "plain", params);
83 WILDCARD_UTF16_TYPE = new MediaType("*", "*", params);
84 }
85
86
87
88 @Test
89 public void testXmlDefault() throws Exception
90 {
91 ResteasyWebTarget target = client.target(generateURL("/xml/default"));
92 Builder request = target.request();
93 request.accept(MediaType.APPLICATION_XML_TYPE);
94
95 String str = "<?xml version=\"1.0\"?>\r"
96 + "<charSetFavoriteMovieXmlRootElement><title>La Règle du Jeu</title></charSetFavoriteMovieXmlRootElement>";
97 log.info(str);
98 log.info("client default charset: " + Charset.defaultCharset());
99 log.info("Sending request");
100
101 Response response = request.post(Entity.entity(str, MediaType.APPLICATION_XML_TYPE));
102 log.info("Received response");
103
104 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
105 CharSetFavoriteMovieXmlRootElement entity = response.readEntity(CharSetFavoriteMovieXmlRootElement.class);
106 log.info("Result: " + entity);
107 log.info("title: " + entity.getTitle());
108 Assert.assertEquals("La Règle du Jeu", entity.getTitle());
109 }
110
111 @Test
112 public void testXmlProduces() throws Exception
113 {
114 ResteasyWebTarget target = client.target(generateURL("/xml/produces"));
115 Builder request = target.request();
116
117 String str = "<?xml version=\"1.0\"?>\r"
118 + "<charSetFavoriteMovieXmlRootElement><title>La Règle du Jeu</title></charSetFavoriteMovieXmlRootElement>";
119 log.info(str);
120 log.info("client default charset: " + Charset.defaultCharset());
121
122 Response response = request.post(Entity.entity(str, APPLICATION_XML_UTF16_TYPE));
123 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
124 CharSetFavoriteMovieXmlRootElement entity = response.readEntity(CharSetFavoriteMovieXmlRootElement.class);
125 log.info("Result: " + entity);
126 log.info("title: " + entity.getTitle());
127 Assert.assertEquals("La Règle du Jeu", entity.getTitle());
128 }
129
130 @Test
131 public void testXmlAccepts() throws Exception
132 {
133 ResteasyWebTarget target = client.target(generateURL("/xml/accepts"));
134 Builder request = target.request();
135 request.accept(APPLICATION_XML_UTF16_TYPE);
136
137 String str = "<?xml version=\"1.0\"?>\r"
138 + "<charSetFavoriteMovieXmlRootElement><title>La Règle du Jeu</title></charSetFavoriteMovieXmlRootElement>";
139 log.info(str);
140 log.info("client default charset: " + Charset.defaultCharset());
141
142 Response response = request.post(Entity.entity(str, APPLICATION_XML_UTF16_TYPE));
143 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
144 CharSetFavoriteMovieXmlRootElement entity = response.readEntity(CharSetFavoriteMovieXmlRootElement.class);
145 log.info("Result: " + entity);
146 log.info("title: " + entity.getTitle());
147 Assert.assertEquals("La Règle du Jeu", entity.getTitle());
148 }
149 }
+0
-96
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/CharSetTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.providers.jaxb.resource.CharSetResource;
10 import org.jboss.resteasy.test.providers.jaxb.resource.CharSetCustomer;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19 import org.jboss.resteasy.utils.TestUtil;
20 import org.jboss.resteasy.utils.PortProviderUtil;
21
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.core.MediaType;
24 import javax.ws.rs.core.Response;
25
26 /**
27 * @tpSubChapter Jaxb provider
28 * @tpChapter Integration tests
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class CharSetTest {
34
35 private final Logger logger = Logger.getLogger(CharSetResource.class.getName());
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(CharSetTest.class.getSimpleName());
41 war.addClass(CharSetTest.class);
42 return TestUtil.finishContainerPrepare(war, null, CharSetCustomer.class, CharSetResource.class);
43 }
44
45 @Before
46 public void init() {
47 client = new ResteasyClientBuilder().build();
48 }
49
50 @After
51 public void after() throws Exception {
52 client.close();
53 client = null;
54 }
55
56 private String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, CharSetTest.class.getSimpleName());
58 }
59
60 /**
61 * @tpTestDetails Client sends POST request with jaxb annotated object entity and the targeted resource receives jaxb
62 * object with corect encoding.
63 * @tpPassCrit The jaxb object xml element is same as original
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testReceiveJaxbObjectAsItis() throws Exception {
68 ResteasyWebTarget target = client.target(generateURL("/test/string"));
69 CharSetCustomer cust = new CharSetCustomer();
70 String name = "bill\u00E9";
71 cust.setName(name);
72 Response response = target.request().accept("application/xml").post(Entity.entity(cust, MediaType.APPLICATION_XML_TYPE));
73 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
74 response.close();
75 }
76
77 /**
78 * @tpTestDetails Client sends POST request with jaxb annotated object entity and the targeted resource receives
79 * xml string.
80 * @tpPassCrit Jaxb object is unmarshalled to the expected xml string with correct encoding
81 * @tpSince RESTEasy 3.0.16
82 */
83 @Test
84 public void testReceiveJaxbObjectAsString() throws Exception {
85 ResteasyWebTarget target = client.target(generateURL("/test"));
86 CharSetCustomer cust = new CharSetCustomer();
87 String name = "bill\u00E9";
88 logger.info("client name: " + name);
89 logger.info("bytes string: " + new String(name.getBytes("UTF-8"), "UTF-8"));
90 cust.setName(name);
91 Response response = target.request().accept("application/xml").post(Entity.entity(cust, MediaType.APPLICATION_XML_TYPE));
92 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
93 response.close();
94 }
95 }
+0
-89
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/CharacterSetTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.providers.jaxb.resource.CharacterSetResource;
9 import org.jboss.resteasy.test.providers.jaxb.resource.CharacterSetData;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Before;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.core.Response;
20 import java.net.URISyntaxException;
21
22 import static org.junit.Assert.assertEquals;
23 import static org.junit.Assert.assertTrue;
24
25
26 /**
27 * @tpSubChapter Jaxb provider
28 * @tpChapter Integration tests
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class CharacterSetTest {
34
35 private final String[] characterSets = {"US-ASCII", "UTF-8", "ISO-8859-1"};
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(CharacterSetTest.class.getSimpleName());
41 return TestUtil.finishContainerPrepare(war, null, CharacterSetData.class, CharacterSetResource.class);
42 }
43
44 @Before
45 public void init() {
46 client = new ResteasyClientBuilder().build();
47 }
48
49 @After
50 public void after() throws Exception {
51 client.close();
52 }
53
54 private String generateURL(String path) {
55 return PortProviderUtil.generateURL(path, CharacterSetTest.class.getSimpleName());
56 }
57
58 /**
59 * @tpTestDetails Tests if correct Variant is chosen for given combination of mediatype xml and charsets.
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void variantSelection() throws URISyntaxException {
64 assertCharset("/variant-selection");
65 }
66
67 private void assertCharset(String path) throws URISyntaxException {
68 for (String characterSet : characterSets) {
69 ResteasyWebTarget target = client.target(generateURL(path));
70 Response response = target.request().accept("application/xml").header("Accept-Charset", characterSet).get();
71
72 assertEquals("Status code", 200, response.getStatus());
73
74 String contentType = response.getHeaders().getFirst("Content-Type").toString();
75 String charsetPattern = "application/xml\\s*;\\s*charset\\s*=\\s*\"?" + characterSet + "\"?";
76 String charsetErrorMessage = contentType + " does not match " + charsetPattern;
77 assertTrue(charsetErrorMessage, contentType.matches(charsetPattern));
78
79 String xml = response.readEntity(String.class);
80 String encodingPattern = "<\\?xml[^>]*encoding\\s*=\\s*['\"]" + characterSet + "['\"].*";
81 String encodingErrorMessage = xml + " does not match " + encodingPattern;
82 assertTrue(encodingErrorMessage, xml.matches(encodingPattern));
83
84 response.close();
85 }
86 }
87
88 }
+0
-163
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/CollectionCoreTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.providers.jaxb.resource.CollectionCustomer;
10 import org.jboss.resteasy.test.providers.jaxb.resource.CollectionNamespacedResource;
11 import org.jboss.resteasy.test.providers.jaxb.resource.CollectionResource;
12 import org.jboss.resteasy.test.providers.jaxb.resource.CollectionNamespacedCustomer;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.client.Invocation;
26 import javax.ws.rs.core.Response;
27
28 import static org.hamcrest.CoreMatchers.containsString;
29
30 /**
31 * @tpSubChapter Jaxb provider
32 * @tpChapter Integration tests
33 * @tpTestCaseDetails Check jaxb requests with collection
34 * @tpSince RESTEasy 3.0.16
35 */
36 @RunWith(Arquillian.class)
37 @RunAsClient
38 public class CollectionCoreTest {
39 private static final String WRONG_RESPONSE = "Response contains wrong data";
40 protected static final Logger logger = LogManager.getLogger(CollectionCoreTest.class.getName());
41
42 static ResteasyClient client;
43
44 @Deployment
45 public static Archive<?> deploy() {
46 WebArchive war = TestUtil.prepareArchive(CollectionCoreTest.class.getSimpleName());
47 war.addClasses(CollectionCustomer.class, CollectionNamespacedCustomer.class);
48 return TestUtil.finishContainerPrepare(war, null, CollectionResource.class, CollectionNamespacedResource.class);
49 }
50
51 @Before
52 public void init() {
53 client = new ResteasyClientBuilder().build();
54 }
55
56 @After
57 public void after() throws Exception {
58 client.close();
59 }
60
61 private String generateURL(String path) {
62 return PortProviderUtil.generateURL(path, CollectionCoreTest.class.getSimpleName());
63 }
64
65 /**
66 * @tpTestDetails Test array response
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void testArray() throws Exception {
71 Invocation.Builder request = client.target(generateURL("/array")).request();
72 Response response = request.get();
73 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
74 String str = response.readEntity(String.class);
75 logger.info(String.format("Response: %s", str));
76 response.close();
77 response = request.put(Entity.entity(str, "application/xml"));
78 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
79 response.close();
80 }
81
82 /**
83 * @tpTestDetails Test list response
84 * @tpSince RESTEasy 3.0.16
85 */
86 @Test
87 public void testList() throws Exception {
88 Invocation.Builder request = client.target(generateURL("/list")).request();
89 Response response = request.get();
90 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
91 String str = response.readEntity(String.class);
92 logger.info(String.format("Response: %s", str));
93 response.close();
94 response = request.put(Entity.entity(str, "application/xml"));
95 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
96 response.close();
97 }
98
99 /**
100 * @tpTestDetails Test GenericEntity of list response
101 * @tpSince RESTEasy 3.0.16
102 */
103 @Test
104 public void testResponse() throws Exception {
105 Invocation.Builder request = client.target(generateURL("/list/response")).request();
106 Response response = request.get();
107 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
108 logger.info(String.format("Response: %s", response.readEntity(String.class)));
109 }
110
111 /**
112 * @tpTestDetails Test array of customers with namespace in XML
113 * @tpSince RESTEasy 3.0.16
114 */
115 @Test
116 public void testNamespacedArray() throws Exception {
117 Invocation.Builder request = client.target(generateURL("/namespaced/array")).request();
118 Response response = request.get();
119 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
120 String str = response.readEntity(String.class);
121 logger.info(String.format("Response: %s", str));
122 response.close();
123 response = request.put(Entity.entity(str, "application/xml"));
124 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
125 response.close();
126 Assert.assertThat(WRONG_RESPONSE, str, containsString("http://customer.com"));
127 }
128
129 /**
130 * @tpTestDetails Test GenericEntity with list of customers with namespace in XML
131 * @tpSince RESTEasy 3.0.16
132 */
133 @Test
134 public void testNamespacedList() throws Exception {
135 Invocation.Builder request = client.target(generateURL("/namespaced/list")).request();
136 Response response = request.get();
137 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
138 String str = response.readEntity(String.class);
139 logger.info(String.format("Response: %s", str));
140 response.close();
141 response = request.put(Entity.entity(str, "application/xml"));
142 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
143 response.close();
144 Assert.assertThat(WRONG_RESPONSE, str, containsString("http://customer.com"));
145 }
146
147 /**
148 * @tpTestDetails Test list of customers with namespace in XML
149 * @tpSince RESTEasy 3.0.16
150 */
151 @Test
152 public void testNamespacedResponse() throws Exception {
153 Invocation.Builder request = client.target(generateURL("/namespaced/list/response")).request();
154 Response response = request.get();
155 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
156 String str = response.readEntity(String.class);
157 logger.info(String.format("Response: %s", str));
158 response.close();
159 Assert.assertThat(WRONG_RESPONSE, str, containsString("http://customer.com"));
160 }
161
162 }
+0
-72
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/CustomOverrideTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.providers.jaxb.resource.CustomOverrideWriter;
10 import org.jboss.resteasy.test.providers.jaxb.resource.CustomOverrideResource;
11 import org.jboss.resteasy.test.providers.jaxb.resource.CustomOverrideFoo;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.After;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 /**
23 * @tpSubChapter Jaxb provider
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class CustomOverrideTest {
30
31 private static Logger logger = Logger.getLogger(CustomOverrideTest.class.getName());
32 static ResteasyClient client;
33
34 @Deployment
35 public static Archive<?> deploy() {
36 WebArchive war = TestUtil.prepareArchive(CustomOverrideTest.class.getSimpleName());
37 return TestUtil.finishContainerPrepare(war, null, CustomOverrideResource.class, CustomOverrideWriter.class,
38 CustomOverrideFoo.class);
39 }
40
41 @Before
42 public void init() {
43 client = new ResteasyClientBuilder().build();
44 }
45
46 @After
47 public void after() throws Exception {
48 client.close();
49 }
50
51 private String generateURL(String path) {
52 return PortProviderUtil.generateURL(path, CustomOverrideTest.class.getSimpleName());
53 }
54
55 /**
56 * @tpTestDetails Test for same resource path for media type xml and "text/x-vcard" with custom MessageBodyWriter
57 * @tpInfo RESTEASY-510
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testRegression() throws Exception {
62 ResteasyWebTarget target = client.target(generateURL("/test"));
63 String response = target.request().accept("text/x-vcard").get(String.class);
64 logger.info(response);
65 Assert.assertEquals("---bill---", response);
66
67 response = target.request().accept("application/xml").get(String.class);
68 Assert.assertTrue(response.contains("customOverrideFoo"));
69 logger.info(response);
70 }
71 }
+0
-75
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/EmptyContentTypeTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.providers.jaxb.resource.EmptyContentTypeFoo;
9 import org.jboss.resteasy.test.providers.jaxb.resource.EmptyContentTypeResource;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.client.Entity;
21 import javax.ws.rs.core.Response;
22
23 /**
24 * @tpSubChapter Jaxb provider
25 * @tpChapter Integration tests
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class EmptyContentTypeTest {
31
32 static ResteasyClient client;
33
34 @Deployment
35 public static Archive<?> deploy() {
36 WebArchive war = TestUtil.prepareArchive(EmptyContentTypeTest.class.getSimpleName());
37 return TestUtil.finishContainerPrepare(war, null, EmptyContentTypeResource.class, EmptyContentTypeFoo.class);
38 }
39
40 @Before
41 public void init() {
42 client = new ResteasyClientBuilder().build();
43 }
44
45 @After
46 public void after() throws Exception {
47 client.close();
48 }
49
50 private String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, EmptyContentTypeTest.class.getSimpleName());
52 }
53
54 /**
55 * @tpTestDetails Test for the resource with two post methods, one consumes xml content type the other consumes empty
56 * content type
57 * @tpInfo RESTEASY-518
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testEmptyContentType() throws Exception {
62 ResteasyWebTarget target = client.target(generateURL("/test"));
63 EmptyContentTypeFoo foo = new EmptyContentTypeFoo();
64 foo.setName("Bill");
65 Response response = target.request().post(Entity.entity(foo, "application/xml"));
66 Assert.assertEquals("The response from the server doesn't match the expected one",
67 response.readEntity(String.class), "Bill");
68
69 Response response2 = target.request().post(null);
70 Assert.assertEquals("The response from the server doesn't match the expected one",
71 response2.readEntity(String.class), "NULL");
72 }
73
74 }
+0
-74
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/ExceptionMapperJaxbTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.providers.jaxb.resource.AbstractJaxbClassPerson;
10 import org.jboss.resteasy.test.providers.jaxb.resource.ExceptionMapperJaxbMapper;
11 import org.jboss.resteasy.test.providers.jaxb.resource.ExceptionMapperJaxbResource;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.Assert;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Jaxb provider
27 * @tpChapter Integration tests
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class ExceptionMapperJaxbTest {
33
34 private static Logger logger = Logger.getLogger(ExceptionMapperJaxbTest.class.getName());
35 static ResteasyClient client;
36
37 @Deployment
38 public static Archive<?> deploy() {
39 WebArchive war = TestUtil.prepareArchive(ExceptionMapperJaxbTest.class.getSimpleName());
40 return TestUtil.finishContainerPrepare(war, null, ExceptionMapperJaxbMapper.class, ExceptionMapperJaxbResource.class,
41 AbstractJaxbClassPerson.class);
42 }
43
44 @Before
45 public void init() {
46 client = new ResteasyClientBuilder().build();
47 }
48
49 @After
50 public void after() throws Exception {
51 client.close();
52 }
53
54 private String generateURL(String path) {
55 return PortProviderUtil.generateURL(path, ExceptionMapperJaxbTest.class.getSimpleName());
56 }
57
58 /**
59 * @tpTestDetails Test for custom JAXBUnmarshalException excetion mapper
60 * @tpInfo RESTEASY-519
61 * @tpSince RESTEasy 3.0.16
62 */
63 @Test
64 public void testFailure() throws Exception {
65 ResteasyWebTarget target = client.target(generateURL("/test"));
66 Response response = target.request().post(Entity.entity("<person", "application/xml"));
67 Assert.assertEquals(400, response.getStatus());
68 String output = response.readEntity(String.class);
69 logger.info(output);
70 }
71
72
73 }
+0
-95
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/GenericResourceTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.providers.jaxb.resource.GenericResourceModel;
9 import org.jboss.resteasy.test.providers.jaxb.resource.GenericResourceResource;
10 import org.jboss.resteasy.test.providers.jaxb.resource.GenericResourceResource2;
11 import org.jboss.resteasy.test.providers.jaxb.resource.GenericResourceOtherAbstractResource;
12 import org.jboss.resteasy.test.providers.jaxb.resource.GenericResourceAbstractResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.client.WebTarget;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @tpSubChapter Jaxb provider
30 * @tpChapter Integration tests
31 * @tpTestCaseDetails Regression test for RESTEASY-1125. Jaxb message body reader not recognized when using generics in
32 * complex inheritance structure
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class GenericResourceTest {
38
39 String str = "<genericResourceModel></genericResourceModel>";
40
41 static ResteasyClient client;
42 protected static final Logger logger = Logger.getLogger(KeepCharsetTest.class.getName());
43
44 @Deployment
45 public static Archive<?> deploy() {
46 WebArchive war = TestUtil.prepareArchive(GenericResourceTest.class.getSimpleName());
47 return TestUtil.finishContainerPrepare(war, null, GenericResourceResource.class, GenericResourceResource2.class,
48 GenericResourceModel.class, GenericResourceOtherAbstractResource.class, GenericResourceAbstractResource.class);
49 }
50
51 @Before
52 public void init() {
53 client = new ResteasyClientBuilder().build();
54 }
55
56 @After
57 public void after() throws Exception {
58 client.close();
59 }
60
61 private String generateURL(String path) {
62 return PortProviderUtil.generateURL(path, GenericResourceTest.class.getSimpleName());
63 }
64
65 /**
66 * @tpTestDetails Tests Jaxb object with resource using inheritance, generics and abstract classes
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void testGenericInheritingResource() throws Exception {
71 WebTarget target = client.target(generateURL("/test"));
72 Response response = target.request().post(Entity.entity(str, "application/xml"));
73 logger.info("status: " + response.getStatus());
74 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
75 String answer = response.readEntity(String.class);
76 Assert.assertEquals("The response from the server is not the expected one", "Success!", answer);
77 logger.info(answer);
78 }
79
80 /**
81 * @tpTestDetails Tests Jaxb object with resource using inheritance, generics and abstract classes
82 * @tpSince RESTEasy 3.0.16
83 */
84 @Test
85 public void testGenericResource() throws Exception {
86 WebTarget target = client.target(generateURL("/test2"));
87 Response response = target.request().post(Entity.entity(str, "application/xml"));
88 logger.info("status: " + response.getStatus());
89 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
90 String answer = response.readEntity(String.class);
91 Assert.assertEquals("The response from the server is not the expected one", "Success!", answer);
92 logger.info(answer);
93 }
94 }
+0
-98
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/GenericSuperInterfaceTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
5 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceAbstractBackendCollectionResource;
6 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceAbstractBackendResource;
7 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceAbstractBackendSubResource;
8 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceAction;
9 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceAssignedPermissionsResource;
10 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceBackendDataCenterResource;
11 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceBackendDataCentersResource;
12 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceBackendResource;
13 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceBaseBackendResource;
14 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceBaseResource;
15 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceBaseResources;
16 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceBusinessEntity;
17 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceDataCenter;
18 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceDataCenterResource;
19 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceDataCenters;
20 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceDataCentersResource;
21 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceGuid;
22 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceINotifyPropertyChanged;
23 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceIVdcQueryable;
24 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceTop;
25 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceUpdatableResource;
26 import org.jboss.resteasy.test.providers.jaxb.resource.GenericSuperInterfaceStoragePool;
27 import org.jboss.resteasy.util.Types;
28 import org.jboss.resteasy.utils.PortProviderUtil;
29 import org.jboss.resteasy.utils.TestUtil;
30 import org.jboss.shrinkwrap.api.Archive;
31 import org.jboss.shrinkwrap.api.spec.WebArchive;
32 import org.junit.Assert;
33 import org.junit.Test;
34 import org.junit.runner.RunWith;
35
36 import java.lang.reflect.Method;
37
38 /**
39 * @tpSubChapter Jaxb provider
40 * @tpChapter Integration tests
41 * @tpTestCaseDetails Regression test for RESTEASY-636
42 * @tpSince RESTEasy 3.0.16
43 */
44 @RunWith(Arquillian.class)
45 public class GenericSuperInterfaceTest {
46 static ResteasyClient client;
47
48 @Deployment
49 public static Archive<?> deploy() {
50 WebArchive war = TestUtil.prepareArchive(GenericSuperInterfaceTest.class.getSimpleName());
51 war.addClasses(GenericSuperInterfaceBackendDataCentersResource.class,
52 GenericSuperInterfaceAbstractBackendCollectionResource.class,
53 GenericSuperInterfaceAbstractBackendResource.class,
54 GenericSuperInterfaceAbstractBackendSubResource.class,
55 GenericSuperInterfaceAction.class, GenericSuperInterfaceAssignedPermissionsResource.class,
56 GenericSuperInterfaceBackendDataCenterResource.class,
57 GenericSuperInterfaceBackendDataCentersResource.class,
58 GenericSuperInterfaceBackendResource.class,
59 GenericSuperInterfaceBaseResource.class, GenericSuperInterfaceBaseResources.class,
60 GenericSuperInterfaceBusinessEntity.class,
61 GenericSuperInterfaceDataCenter.class, GenericSuperInterfaceDataCenterResource.class,
62 GenericSuperInterfaceDataCenters.class,
63 GenericSuperInterfaceDataCentersResource.class, GenericSuperInterfaceGuid.class,
64 GenericSuperInterfaceINotifyPropertyChanged.class, GenericSuperInterfaceIVdcQueryable.class,
65 GenericSuperInterfaceStoragePool.class, GenericSuperInterfaceUpdatableResource.class,
66 GenericSuperInterfaceBaseBackendResource.class,
67 TestUtil.class, PortProviderUtil.class);
68 return TestUtil.finishContainerPrepare(war, null, GenericSuperInterfaceTop.class);
69 }
70
71 /**
72 * @tpTestDetails Test on server.
73 * @tpSince RESTEasy 3.0.16
74 */
75 @Test
76 public void testGetImplementationReflection() throws Exception {
77 Class updatableResource = GenericSuperInterfaceBackendDataCenterResource.class.getInterfaces()[0].getInterfaces()[0];
78 Assert.assertEquals(updatableResource, GenericSuperInterfaceUpdatableResource.class);
79 Method update = null;
80 for (Method method : updatableResource.getMethods()) {
81 if (method.getName().equals("update")) {
82 update = method;
83 }
84 }
85 Assert.assertNotNull("Updated method was not found", update);
86
87 Method implemented = Types.getImplementingMethod(GenericSuperInterfaceBackendDataCenterResource.class, update);
88
89 Method actual = null;
90 for (Method method : GenericSuperInterfaceBackendDataCenterResource.class.getMethods()) {
91 if (method.getName().equals("update") && !method.isSynthetic()) {
92 actual = method;
93 }
94 }
95 Assert.assertEquals("Interface was not detected", implemented, actual);
96 }
97 }
+0
-72
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/InheritanceTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.providers.jaxb.resource.InheritanceAnimal;
9 import org.jboss.resteasy.test.providers.jaxb.resource.InheritanceZoo;
10 import org.jboss.resteasy.test.providers.jaxb.resource.InheritanceCat;
11 import org.jboss.resteasy.test.providers.jaxb.resource.InheritanceDog;
12 import org.jboss.resteasy.test.providers.jaxb.resource.InheritanceResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.core.Response;
25
26 /**
27 * @tpSubChapter Jaxb provider
28 * @tpChapter Integration tests
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class InheritanceTest {
34
35 static ResteasyClient client;
36
37 @Deployment
38 public static Archive<?> deploy() {
39 WebArchive war = TestUtil.prepareArchive(InheritanceTest.class.getSimpleName());
40 return TestUtil.finishContainerPrepare(war, null, InheritanceAnimal.class, InheritanceCat.class, InheritanceDog.class,
41 InheritanceZoo.class, InheritanceResource.class);
42 }
43
44 @Before
45 public void init() {
46 client = new ResteasyClientBuilder().build();
47 }
48
49 @After
50 public void after() throws Exception {
51 client.close();
52 }
53
54 private String generateURL(String path) {
55 return PortProviderUtil.generateURL(path, InheritanceTest.class.getSimpleName());
56 }
57
58 /**
59 * @tpTestDetails Tests Jaxb object with inheritance structure
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void testInheritance() throws Exception {
64 ResteasyWebTarget target = client.target(generateURL("/zoo"));
65 Response response = target.request().get();
66 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
67 InheritanceZoo zoo = response.readEntity(InheritanceZoo.class);
68 Assert.assertEquals("The number of animals in the zoo doesn't match the expected count", 2, zoo.getAnimals().size());
69 }
70
71 }
+0
-101
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/JaxbCacheTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.logging.Logger;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.plugins.providers.jaxb.JAXBContextFinder;
7 import org.jboss.resteasy.spi.ResteasyProviderFactory;
8 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbCacheChild;
9 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbCacheParent;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.core.MediaType;
18 import javax.ws.rs.ext.ContextResolver;
19 import javax.ws.rs.ext.Providers;
20 import javax.xml.bind.JAXBContext;
21
22 /**
23 * @tpSubChapter Jaxb provider
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 public class JaxbCacheTest {
29
30 static ResteasyClient client;
31 private static Logger logger = Logger.getLogger(JaxbCacheTest.class.getName());
32
33 @Deployment
34 public static Archive<?> deploy() {
35 WebArchive war = TestUtil.prepareArchive(JaxbCacheTest.class.getSimpleName());
36 war.addClass(JaxbCacheTest.class);
37 return TestUtil.finishContainerPrepare(war, null, JaxbCacheParent.class, JaxbCacheChild.class);
38 }
39
40 /**
41 * @tpTestDetails Gets contextResolver for JAXBContextFinder class and mediatype "APPLICATION_XML_TYPE" or "APPLICATION_ATOM_XML_TYPE",
42 * then gets calls findCachedContext() twice to get JAXBContext and ensures that the result is the same
43 * @tpSince RESTEasy 3.0.16
44 */
45 @Test
46 public void testCache() throws Exception {
47 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
48 ResteasyProviderFactory.pushContext(Providers.class, factory);
49 {
50 ContextResolver<JAXBContextFinder> resolver = factory.getContextResolver(JAXBContextFinder.class, MediaType.APPLICATION_XML_TYPE);
51 JAXBContextFinder finder = resolver.getContext(JaxbCacheChild.class);
52 JAXBContext ctx = finder.findCachedContext(JaxbCacheChild.class, MediaType.APPLICATION_XML_TYPE, null);
53
54 JAXBContext ctx2 = finder.findCachedContext(JaxbCacheChild.class, MediaType.APPLICATION_XML_TYPE, null);
55
56 Assert.assertTrue(ctx == ctx2);
57 }
58
59 {
60 ContextResolver<JAXBContextFinder> resolver = factory.getContextResolver(JAXBContextFinder.class, MediaType.APPLICATION_ATOM_XML_TYPE);
61 JAXBContextFinder finder = resolver.getContext(JaxbCacheChild.class);
62 Assert.assertNotNull(finder);
63 JAXBContext ctx = finder.findCachedContext(JaxbCacheChild.class, MediaType.APPLICATION_ATOM_XML_TYPE, null);
64
65 JAXBContext ctx2 = finder.findCachedContext(JaxbCacheChild.class, MediaType.APPLICATION_ATOM_XML_TYPE, null);
66
67 Assert.assertTrue(ctx == ctx2);
68 }
69 }
70
71 /**
72 * @tpTestDetails Gets contextResolver for JAXBContextFinder class and mediatype "APPLICATION_XML_TYPE" or "APPLICATION_ATOM_XML_TYPE",
73 * thrn gets calls findCacheContext() twice to get JAXBContext and ensures that the result is the same
74 * @tpSince RESTEasy 3.0.16
75 */
76 @Test
77 public void testCache2() throws Exception {
78 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
79 ResteasyProviderFactory.pushContext(Providers.class, factory);
80 {
81 ContextResolver<JAXBContextFinder> resolver = factory.getContextResolver(JAXBContextFinder.class, MediaType.APPLICATION_XML_TYPE);
82 JAXBContextFinder finder = resolver.getContext(JaxbCacheChild.class);
83 JAXBContext ctx = finder.findCacheContext(MediaType.APPLICATION_XML_TYPE, null, JaxbCacheChild.class, JaxbCacheParent.class);
84
85 JAXBContext ctx2 = finder.findCacheContext(MediaType.APPLICATION_XML_TYPE, null, JaxbCacheChild.class, JaxbCacheParent.class);
86
87 Assert.assertTrue(ctx == ctx2);
88 }
89
90 {
91 ContextResolver<JAXBContextFinder> resolver = factory.getContextResolver(JAXBContextFinder.class, MediaType.APPLICATION_ATOM_XML_TYPE);
92 JAXBContextFinder finder = resolver.getContext(JaxbCacheChild.class);
93 JAXBContext ctx = finder.findCacheContext(MediaType.APPLICATION_ATOM_XML_TYPE, null, JaxbCacheChild.class, JaxbCacheParent.class);
94
95 JAXBContext ctx2 = finder.findCacheContext(MediaType.APPLICATION_ATOM_XML_TYPE, null, JaxbCacheChild.class, JaxbCacheParent.class);
96
97 Assert.assertTrue(ctx == ctx2);
98 }
99 }
100 }
+0
-161
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/JaxbCollectionTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbCollectionFoo;
9 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbCollectionNamespacedFoo;
10 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbCollectionNamespacedResource;
11 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbCollectionResource;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.After;
18 import org.junit.Assert;
19 import org.junit.Before;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 import javax.ws.rs.client.Entity;
24 import javax.ws.rs.core.Response;
25 import java.util.List;
26
27 /**
28 * @tpSubChapter Jaxb provider
29 * @tpChapter Integration tests
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class JaxbCollectionTest {
35
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(JaxbCollectionTest.class.getSimpleName());
41 war.addClass(JaxbCollectionTest.class);
42 return TestUtil.finishContainerPrepare(war, null, JaxbCollectionResource.class, JaxbCollectionNamespacedResource.class,
43 JaxbCollectionFoo.class, JaxbCollectionNamespacedFoo.class);
44 }
45
46 @Before
47 public void init() {
48 client = new ResteasyClientBuilder().build();
49 }
50
51 @After
52 public void after() throws Exception {
53 client.close();
54 }
55
56 private String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, JaxbCollectionTest.class.getSimpleName());
58 }
59
60 /**
61 * @tpTestDetails Client sends POST request with xml entity, the request is processed by resource, which can process
62 * JAXB objects wrapped in collection element.
63 * @tpPassCrit The Response contains correct number of elements and correct values
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testNakedArray() throws Exception {
68 String xml = "<resteasy:collection xmlns:resteasy=\"http://jboss.org/resteasy\">"
69 + "<foo test=\"hello\"/></resteasy:collection>";
70
71 ResteasyWebTarget target = client.target(generateURL("/array"));
72 Response response = target.request().accept("application/xml").post(Entity.xml(xml));
73 List<JaxbCollectionFoo> list = response.readEntity(new javax.ws.rs.core.GenericType<List<JaxbCollectionFoo>>() {
74 });
75 Assert.assertEquals("The response doesn't contain 1 item, which is expected", 1, list.size());
76 Assert.assertEquals("The response doesn't contain correct element value", list.get(0).getTest(), "hello");
77 response.close();
78 }
79
80 /**
81 * @tpTestDetails Client sends POST request with xml entity, the request is processed by resource, which can process
82 * JAXB objects wrapped in collection element. The resource has changed the collection element name using @Wrapped
83 * annotation on the resource to 'list'.
84 * @tpPassCrit The Response contains correct number of elements and correct values
85 * @tpSince RESTEasy 3.0.16
86 */
87 @Test
88 public void testList() throws Exception {
89 String xml = "<list>"
90 + "<foo test=\"hello\"/></list>";
91
92 ResteasyWebTarget target = client.target(generateURL("/list"));
93 Response response = target.request().post(Entity.xml(xml));
94 JaxbCollectionFoo[] list = response.readEntity(new javax.ws.rs.core.GenericType<JaxbCollectionFoo[]>() {
95 });
96 Assert.assertEquals("The response doesn't contain 1 item, which is expected", 1, list.length);
97 Assert.assertEquals("The response doesn't contain correct element value", list[0].getTest(), "hello");
98 response.close();
99
100 }
101
102 /**
103 * @tpTestDetails Client sends POST request with xml entity, the request is processed by resource, which can process
104 * JAXB objects wrapped in collection element. The XML element of name 'foo' has changed namespace to 'http://foo.com'.
105 * @tpPassCrit The Response contains correct number of elements and correct values
106 * @tpSince RESTEasy 3.0.16
107 */
108 @Test
109 public void testNamespacedNakedArray() throws Exception {
110 String xml = "<collection xmlns:foo=\"http://foo.com\">"
111 + "<foo:foo test=\"hello\"/></collection>";
112
113 ResteasyWebTarget target = client.target(generateURL("/namespaced/array"));
114 Response response = target.request().post(Entity.xml(xml));
115 List<JaxbCollectionNamespacedFoo> list = response.readEntity(new javax.ws.rs.core.GenericType<List<JaxbCollectionNamespacedFoo>>() {
116 });
117 Assert.assertEquals("The response doesn't contain 1 item, which is expected", 1, list.size());
118 Assert.assertEquals("The response doesn't contain correct element value", list.get(0).getTest(), "hello");
119 response.close();
120
121 }
122
123 /**
124 * @tpTestDetails Client sends POST request with xml entity, the request is processed by resource, which can process
125 * JAXB objects wrapped in collection element. The resource has changed the collection element name using @Wrapped
126 * annotation on the resource to 'list'. The XML element of name 'foo' has changed namespace to 'http://foo.com'.
127 * @tpPassCrit The Response contains correct number of elements and correct values
128 * @tpSince RESTEasy 3.0.16
129 */
130 @Test
131 public void testNamespacedList() throws Exception {
132 String xml = "<list xmlns:foo=\"http://foo.com\">"
133 + "<foo:foo test=\"hello\"/></list>";
134
135 ResteasyWebTarget target = client.target(generateURL("/namespaced/list"));
136 Response response = target.request().post(Entity.xml(xml));
137 JaxbCollectionNamespacedFoo[] list = response.readEntity(new javax.ws.rs.core.GenericType<JaxbCollectionNamespacedFoo[]>() {
138 });
139 Assert.assertEquals("The response doesn't contain 1 item, which is expected", 1, list.length);
140 Assert.assertEquals("The response doesn't contain correct element value", list[0].getTest(), "hello");
141 response.close();
142 }
143
144 /**
145 * @tpTestDetails Client sends POST request with xml entity containing wrong element name for collection.
146 * @tpPassCrit Response with code BAD REQUEST
147 * @tpSince RESTEasy 3.0.16
148 */
149 @Test
150 public void testBadList() throws Exception {
151 String xml = "<bad-list>"
152 + "<foo test=\"hello\"/></bad-list>";
153
154 ResteasyWebTarget target = client.target(generateURL("/list"));
155 Response response = target.request().post(Entity.xml(xml));
156 Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus());
157 response.close();
158 }
159
160 }
+0
-76
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/JaxbElementTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbElementEntityMessageReader;
8 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbElementEntityMessageWriter;
9 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbElementResource;
10 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbElementReadableWritableEntity;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.Assert;
20 import org.junit.runner.RunWith;
21 import javax.ws.rs.client.Entity;
22 import javax.ws.rs.core.Response;
23 import javax.xml.bind.JAXBElement;
24 import javax.xml.namespace.QName;
25
26
27 /**
28 * @tpSubChapter Jaxb provider
29 * @tpChapter Integration tests
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class JaxbElementTest {
35
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(JaxbElementTest.class.getSimpleName());
41 war.addClass(JaxbCollectionTest.class);
42 return TestUtil.finishContainerPrepare(war, null, JaxbElementEntityMessageReader.class, JaxbElementEntityMessageWriter.class,
43 JaxbElementResource.class, JaxbElementReadableWritableEntity.class);
44 }
45
46 @Before
47 public void init() {
48 client = new ResteasyClientBuilder().build();
49 }
50
51 @After
52 public void after() throws Exception {
53 client.close();
54 }
55
56 private String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, JaxbElementTest.class.getSimpleName());
58 }
59
60 /**
61 * @tpTestDetails Creates entity type JAXBElement and sends it to the server, user defined Writer and Reader implementing
62 * custom type is used
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void testWriter() {
67 JAXBElement<String> element = new JAXBElement<String>(new QName(""),
68 String.class, JaxbElementResource.class.getName());
69 Response response = client.target(generateURL("/resource/standardwriter")).request().post(Entity.xml(element));
70 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
71 response.close();
72 }
73
74
75 }
+0
-191
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/JaxbMarshallingSoakTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.logging.Logger;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbMarshallingSoakAsyncService;
9 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbMarshallingSoakItem;
10 import org.jboss.resteasy.util.HttpResponseCodes;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.resteasy.utils.TimeoutUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.core.Response;
24 import javax.xml.bind.JAXBContext;
25 import javax.xml.bind.JAXBException;
26 import java.io.ByteArrayInputStream;
27 import java.util.HashMap;
28 import java.util.Map;
29 import java.util.concurrent.CountDownLatch;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.atomic.AtomicInteger;
34
35 /**
36 * @tpSubChapter Jaxb provider
37 * @tpChapter Integration tests
38 * @tpTestCaseDetails JAXB shouldn't have a concurrent problem and should unmarshall a Map property all the time
39 * @tpSince RESTEasy 3.0.16
40 */
41 @RunWith(Arquillian.class)
42 public class JaxbMarshallingSoakTest {
43 private static Logger logger = Logger.getLogger(JaxbMarshallingSoakTest.class);
44 public static int iterator = 500;
45 public static AtomicInteger counter = new AtomicInteger();
46 public static CountDownLatch latch;
47 public static JAXBContext ctx;
48 public static String itemString;
49 int timeout = TimeoutUtil.adjust(60);
50
51 static ResteasyClient client;
52
53 @Before
54 public void init() {
55 client = new ResteasyClientBuilder()
56 .establishConnectionTimeout(5000, TimeUnit.MILLISECONDS)
57 .connectionCheckoutTimeout(5000, TimeUnit.MILLISECONDS)
58 .socketTimeout(5000, TimeUnit.MILLISECONDS)
59 .maxPooledPerRoute(500)
60 .build();
61 }
62
63 @After
64 public void after() throws Exception {
65 client.close();
66 }
67
68 @Deployment
69 public static Archive<?> createTestArchive() {
70 WebArchive war = TestUtil.prepareArchive(JaxbMarshallingSoakTest.class.getSimpleName());
71 war.addClasses(JaxbMarshallingSoakItem.class, TestUtil.class, PortProviderUtil.class, TimeoutUtil.class);
72 Map<String, String> contextParam = new HashMap<>();
73 contextParam.put("resteasy.async.job.service.enabled", "true");
74 return TestUtil.finishContainerPrepare(war, contextParam, JaxbMarshallingSoakAsyncService.class);
75 }
76
77 private String generateURL(String path) {
78 return PortProviderUtil.generateURL(path, JaxbMarshallingSoakTest.class.getSimpleName());
79 }
80
81 /**
82 * @tpTestDetails Test with client.
83 * @tpSince RESTEasy 3.0.16
84 */
85 @Test
86 public void basicTest() throws Exception {
87 latch = new CountDownLatch(iterator);
88 ctx = JAXBContext.newInstance(JaxbMarshallingSoakItem.class);
89 counter.set(0);
90 itemString = setString();
91 logger.info(String.format("Request: %s", itemString));
92 for (int i = 0; i < iterator; i++) {
93 ResteasyWebTarget target = client.target(generateURL("/mpac/add?oneway=true"));
94 Response response = target.request().post(Entity.entity(itemString, "application/xml"));
95 Assert.assertEquals(HttpResponseCodes.SC_ACCEPTED, response.getStatus());
96 response.close();
97 }
98 latch.await(10, TimeUnit.SECONDS);
99 String message = String.format(new StringBuilder().append("RESTEasy should successes with marshalling %d times.")
100 .append("But RESTEasy successes only %d times.").toString(), iterator, counter.get());
101 Assert.assertEquals(message, iterator, counter.get());
102 }
103
104 /**
105 * @tpTestDetails Server test.
106 * @tpSince RESTEasy 3.0.16
107 */
108 @Test
109 public void compare() throws Exception {
110 itemString = setString();
111 ctx = JAXBContext.newInstance(JaxbMarshallingSoakItem.class);
112
113 counter.set(0);
114
115 Thread[] threads = new Thread[iterator];
116 for (int i = 0; i < iterator; i++) {
117 Thread thread = new Thread() {
118 @Override
119 public void run() {
120 byte[] bytes = itemString.getBytes();
121 ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
122 JaxbMarshallingSoakItem item = null;
123 try {
124 item = (JaxbMarshallingSoakItem) ctx.createUnmarshaller().unmarshal(bais);
125 } catch (JAXBException e) {
126 throw new RuntimeException(e);
127 }
128 item.toString();
129 counter.incrementAndGet();
130
131 }
132 };
133 threads[i] = thread;
134 }
135 ExecutorService threadPool = Executors.newFixedThreadPool(100);
136 for (int i = 0; i < iterator; i++) {
137 threadPool.submit(threads[i]);
138 }
139 threadPool.shutdown();
140 try {
141 if (!threadPool.awaitTermination(timeout, TimeUnit.SECONDS)) {
142 Assert.fail(String.format("Clients did not terminate in %s seconds", timeout));
143 }
144 } catch (InterruptedException e) {
145 Assert.fail("ExecutorService[threadPool] was interrupted");
146 }
147 String message = String.format(new StringBuilder().append("RESTEasy should successes with marshalling %d times.")
148 .append("But RESTEasy successes only %d times.").toString(), iterator, counter.get());
149 Assert.assertEquals(message, iterator, counter.get());
150 }
151
152 private String setString() {
153 StringBuffer sbuffer = new StringBuffer();
154 sbuffer.append("<item>");
155 sbuffer.append("<price>1000</price>");
156 sbuffer.append("<description>Allah Hafiz</description>");
157 sbuffer.append("<requestID>");
158 sbuffer.append("i");
159 sbuffer.append("</requestID>");
160
161 sbuffer.append("<dummy1>DUMMY1</dummy1>");
162 sbuffer.append("<dummy2>DUMMY2</dummy2>");
163 sbuffer.append("<dummy3>DUMMY3</dummy3>");
164 sbuffer.append("<dummy4>DUMMY4</dummy4>");
165 sbuffer.append("<dummy5>DUMMY5</dummy5>");
166 sbuffer.append("<dummy6>DUMMY6</dummy6>");
167 sbuffer.append("<dummy7>DUMMY7</dummy7>");
168 sbuffer.append("<dummy8>DUMMY8</dummy8>");
169
170 sbuffer.append("<harness>");
171 sbuffer.append("<entry>");
172 sbuffer.append("<key>P_REGIONCD</key>");
173 sbuffer.append("<value>325</value>");
174 sbuffer.append("</entry>");
175 sbuffer.append("<entry>");
176 sbuffer.append("<key>P_COUNTYMUN</key>");
177 sbuffer.append("<value>447</value>");
178 sbuffer.append("</entry>");
179 sbuffer.append("<entry>f");
180 sbuffer.append("<key>p_SrcView</key>");
181 sbuffer.append("<value>C</value>");
182 sbuffer.append("</entry>");
183 sbuffer.append("</harness>");
184
185 sbuffer.append("</item>");
186 return sbuffer.toString();
187 }
188 }
189
190
+0
-158
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/JaxbXmlRootElementProviderTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbElementClient;
10 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbJsonXmlRootElementClient;
11 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbXmlRootElementClient;
12 import org.jboss.resteasy.test.providers.jaxb.resource.Parent;
13 import org.jboss.resteasy.test.providers.jaxb.resource.Child;
14 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbJsonElementClient;
15 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbJunkXmlOrderClient;
16 import org.jboss.resteasy.test.providers.jaxb.resource.JaxbXmlRootElementProviderResource;
17 import org.jboss.resteasy.utils.PortProviderUtil;
18 import org.jboss.resteasy.utils.TestUtil;
19 import org.jboss.shrinkwrap.api.Archive;
20 import org.jboss.shrinkwrap.api.spec.WebArchive;
21 import org.junit.After;
22 import org.junit.Assert;
23 import org.junit.Before;
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26
27 import javax.ws.rs.client.ResponseProcessingException;
28 import javax.xml.bind.JAXBElement;
29 import javax.xml.namespace.QName;
30
31 /**
32 * @tpSubChapter Jaxb provider
33 * @tpChapter Integration tests
34 * @tpSince RESTEasy 3.0.16
35 */
36 @RunWith(Arquillian.class)
37 @RunAsClient
38 public class JaxbXmlRootElementProviderTest {
39
40 private String JAXB_URL = generateURL("/jaxb");
41 private static final String JSON_PARENT = "JSON Parent";
42 private static final String XML_PARENT = "XML Parent";
43 private static Logger logger = Logger.getLogger(XmlHeaderTest.class.getName());
44
45 private static final String ERR_PARENT_NULL = "Parent is null";
46 private static final String ERR_PARENT_NAME = "The name of the parent is not the expected one";
47
48 static ResteasyClient client;
49 private JaxbXmlRootElementClient jaxbClient;
50 private JaxbElementClient jaxbElementClient;
51 private JaxbJsonXmlRootElementClient jsonClient;
52 private JaxbJsonElementClient jsonElementClient;
53 private JaxbJunkXmlOrderClient junkClient;
54
55 @Deployment
56 public static Archive<?> deploy() {
57 WebArchive war = TestUtil.prepareArchive(JaxbXmlRootElementProviderTest.class.getSimpleName());
58 war.addClass(Parent.class);
59 war.addClass(Child.class);
60 return TestUtil.finishContainerPrepare(war, null, JaxbXmlRootElementProviderResource.class);
61 }
62
63 @Before
64 public void init() {
65 client = new ResteasyClientBuilder().build();
66 jaxbClient = ProxyBuilder.builder(JaxbXmlRootElementClient.class, client.target(JAXB_URL)).build();
67 jaxbElementClient = ProxyBuilder.builder(JaxbElementClient.class, client.target(JAXB_URL)).build();
68 jsonClient = ProxyBuilder.builder(JaxbJsonXmlRootElementClient.class, client.target(JAXB_URL)).build();
69 jsonElementClient = ProxyBuilder.builder(JaxbJsonElementClient.class, client.target(JAXB_URL)).build();
70 junkClient = ProxyBuilder.builder(JaxbJunkXmlOrderClient.class, client.target(JAXB_URL)).build();
71 }
72
73 @After
74 public void after() throws Exception {
75 client.close();
76 }
77
78 private String generateURL(String path) {
79 return PortProviderUtil.generateURL(path, JaxbXmlRootElementProviderTest.class.getSimpleName());
80 }
81
82 /**
83 * @tpTestDetails Resteasy proxy client sends get request for jaxb annotated class, the response is expected to be in xml format
84 * @tpSince RESTEasy 3.0.16
85 */
86 @Test
87 public void testGetParent() {
88 Parent parent = jaxbClient.getParent(XML_PARENT);
89 Assert.assertEquals(ERR_PARENT_NAME, parent.getName(), XML_PARENT);
90 }
91
92 /**
93 * @tpTestDetails Resteasy proxy client sends get request for jaxb annotated class, the response is expected to be in xml format,
94 * client proxy with @Produces ""application/junk+xml" is used
95 * @tpSince RESTEasy 3.0.16
96 */
97 @Test
98 public void testGetParentJunk() {
99 Parent parent = junkClient.getParent(XML_PARENT);
100 Assert.assertEquals(ERR_PARENT_NAME, parent.getName(), XML_PARENT);
101 }
102
103 /**
104 * @tpTestDetails Resteasy proxy client sends get request for jaxb annotated class, the response is expected to convert
105 * into JAXBElement<Parent>
106 * @tpSince RESTEasy 3.0.16
107 */
108 @Test
109 public void testGetParentElement() {
110 JAXBElement<Parent> element = jaxbElementClient.getParent(XML_PARENT);
111 Parent parent = element.getValue();
112 Assert.assertEquals(ERR_PARENT_NAME, parent.getName(), XML_PARENT);
113 }
114
115 /**
116 * @tpTestDetails Resteasy proxy client sends get request for jaxb annotated class, the response is expected to be in
117 * json format. Regression test for JBEAP-3530.
118 * @tpSince RESTEasy 3.0.16
119 */
120 @Test
121 public void testGetParentJson() throws Exception {
122 Parent parent = null;
123 try {
124 parent = jsonClient.getParent(JSON_PARENT);
125 } catch (ResponseProcessingException exc) {
126 Assert.fail(String.format("Regression of JBEAP-3530, see %s", exc.getCause().toString()));
127 }
128 Assert.assertNotNull(ERR_PARENT_NULL, parent);
129 Assert.assertEquals(ERR_PARENT_NAME, parent.getName(), JSON_PARENT);
130
131 String mapped = jsonClient.getParentString(JSON_PARENT);
132 Assert.assertEquals("Wrong response from the server",
133 "{\"name\":\"JSON Parent\",\"child\":[{\"name\":\"Child 1\"},{\"name\":\"Child 2\"},{\"name\":\"Child 3\"}]}", mapped);
134 }
135
136 /**
137 * @tpTestDetails Resteasy proxy client sends post request with jaxb annotated object
138 * @tpSince RESTEasy 3.0.16
139 */
140 @Test
141 public void testPostParent() {
142 jaxbClient.postParent(Parent.createTestParent("TEST"));
143 }
144
145 /**
146 * @tpTestDetails Resteasy proxy client sends post request with JAXBElement object containing jaxb annotated object instance
147 * @tpSince RESTEasy 3.0.16
148 */
149 @Test
150 public void testPostParentElement() {
151 Parent parent = Parent.createTestParent("TEST ELEMENT");
152 JAXBElement<Parent> parentElement = new JAXBElement<Parent>(new QName("parent"),
153 Parent.class, parent);
154 jaxbElementClient.postParent(parentElement);
155 }
156
157 }
+0
-184
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/KeepCharsetTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import java.nio.charset.Charset;
3 import java.util.HashMap;
4 import java.util.Map;
5
6 import javax.ws.rs.client.Entity;
7 import javax.ws.rs.client.WebTarget;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Response;
10
11 import org.jboss.arquillian.container.test.api.Deployment;
12 import org.jboss.arquillian.container.test.api.RunAsClient;
13 import org.jboss.arquillian.junit.Arquillian;
14 import org.jboss.logging.Logger;
15 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
16 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
17 import org.jboss.resteasy.test.providers.jaxb.resource.KeepCharsetFavoriteMovieXmlRootElement;
18 import org.jboss.resteasy.test.providers.jaxb.resource.KeepCharsetMovieResource;
19 import org.jboss.resteasy.util.HttpResponseCodes;
20 import org.jboss.resteasy.utils.PortProviderUtil;
21 import org.jboss.resteasy.utils.TestUtil;
22 import org.jboss.shrinkwrap.api.Archive;
23 import org.jboss.shrinkwrap.api.spec.WebArchive;
24 import org.junit.After;
25 import org.junit.Assert;
26 import org.junit.Before;
27 import org.junit.Test;
28 import org.junit.runner.RunWith;
29
30 /**
31 * @tpSubChapter Jaxb provider
32 * @tpChapter Integration tests
33 * @tpTestCaseDetails Regression test for RESTEASY-1066. If the content-type of the response is not specified in the request,
34 * @tpSince RESTEasy 3.0.16
35 */
36 @RunWith(Arquillian.class)
37 @RunAsClient
38 public class KeepCharsetTest {
39
40 protected final Logger logger = Logger.getLogger(KeepCharsetTest.class.getName());
41 static ResteasyClient client;
42 protected static final MediaType APPLICATION_XML_UTF16_TYPE;
43
44 private static final String EXPAND = "war_expand";
45 private static final String NO_EXPAND = "war_no_expand";
46 private static final String entityXml = "<?xml version=\"1.0\"?>\r"
47 + "<keepCharsetFavoriteMovieXmlRootElement><title>La Règle du Jeu</title></keepCharsetFavoriteMovieXmlRootElement>";
48
49 static {
50 Map<String, String> params = new HashMap<String, String>();
51 params.put("charset", "UTF-16");
52 APPLICATION_XML_UTF16_TYPE = new MediaType("application", "xml", params);
53 }
54
55 @Deployment(name = NO_EXPAND)
56 public static Archive<?> deployExpandFalse() {
57 Map<String, String> params = new HashMap<String, String>();
58 WebArchive war = TestUtil.prepareArchive(NO_EXPAND);
59 params.put("charset", "UTF-16");
60 params.put("resteasy.document.expand.entity.references", "false");
61 return TestUtil.finishContainerPrepare(war, params, KeepCharsetMovieResource.class, KeepCharsetFavoriteMovieXmlRootElement.class);
62 }
63
64 @Deployment(name = EXPAND)
65 public static Archive<?> deployExpandTrue() {
66 Map<String, String> params = new HashMap<String, String>();
67 WebArchive war = TestUtil.prepareArchive(EXPAND);
68 params.put("charset", "UTF-16");
69 params.put("resteasy.document.expand.entity.references", "true");
70 return TestUtil.finishContainerPrepare(war, params, KeepCharsetMovieResource.class, KeepCharsetFavoriteMovieXmlRootElement.class);
71 }
72
73 @Before
74 public void init() {
75 client = new ResteasyClientBuilder().build();
76 }
77
78 @After
79 public void after() throws Exception {
80 client.close();
81 }
82
83 /**
84 * @tpTestDetails Client sends POST request with jaxb annotated object entity. Request encoding is different than from
85 * encoding of the server. Default encoding is used and entity expansion is set to true.
86 * @tpPassCrit The response is returned in encoding of the original request not in encoding of the server.
87 * @tpSince RESTEasy 3.0.16
88 */
89 @Test
90 public void testXmlDefaultExpand() throws Exception {
91 xmlDefault(EXPAND);
92 }
93
94 /**
95 * @tpTestDetails Client sends POST request with jaxb annotated object entity. Request encoding is different than from
96 * encoding of the server. Default encoding is used and entity expansion is set to false.
97 * @tpPassCrit The response is returned in encoding of the original request not in encoding of the server.
98 * @tpSince RESTEasy 3.0.16
99 */
100 @Test
101 public void testXmlDefaultNoExpand() throws Exception {
102 xmlDefault(NO_EXPAND);
103 }
104
105 private void xmlDefault(String path) throws Exception {
106 WebTarget target = client.target(PortProviderUtil.generateURL("/xml/default", path));
107 logger.info(entityXml);
108 logger.info("client default charset: " + Charset.defaultCharset());
109 logger.info("Sending request");
110 Response response = target.request().accept(MediaType.APPLICATION_XML_TYPE).post(Entity.entity(entityXml, MediaType.APPLICATION_XML_TYPE));
111 logger.info("Received response");
112 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
113 KeepCharsetFavoriteMovieXmlRootElement entity = response.readEntity(KeepCharsetFavoriteMovieXmlRootElement.class);
114 logger.info("Result: " + entity);
115 Assert.assertEquals("Incorrect xml entity was returned from the server", "La Règle du Jeu", entity.getTitle());
116 }
117
118 /**
119 * @tpTestDetails Client sends POST request with jaxb annotated object entity. Request encoding is different than from
120 * encoding of the server. Encoding is set up in resource produces annotation and entity expansion is set to true.
121 * @tpPassCrit The response is returned in encoding of the original request not in encoding of the server.
122 * @tpSince RESTEasy 3.0.16
123 */
124 @Test
125 public void testXmlProducesExpand() throws Exception {
126 XmlProduces(EXPAND);
127 }
128
129 /**
130 * @tpTestDetails Client sends POST request with jaxb annotated object entity. Request encoding is different than from
131 * encoding of the server. Encoding is set up in resource produces annotation and entity expansion is set to false.
132 * @tpPassCrit The response is returned in encoding of the original request not in encoding of the server.
133 * @tpSince RESTEasy 3.0.16
134 */
135 @Test
136 public void testXmlProducesNoExpand() throws Exception {
137 XmlProduces(NO_EXPAND);
138 }
139
140 private void XmlProduces(String path) throws Exception {
141 WebTarget target = client.target(PortProviderUtil.generateURL("/xml/produces", path));
142 logger.info(entityXml);
143 logger.info("client default charset: " + Charset.defaultCharset());
144 Response response = target.request().post(Entity.entity(entityXml, APPLICATION_XML_UTF16_TYPE));
145 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
146 KeepCharsetFavoriteMovieXmlRootElement entity = response.readEntity(KeepCharsetFavoriteMovieXmlRootElement.class);
147 logger.info("Result: " + entity);
148 Assert.assertEquals("Incorrect xml entity was returned from the server", "La Règle du Jeu", entity.getTitle());
149 }
150
151 /**
152 * @tpTestDetails Client sends POST request with jaxb annotated object entity. Request encoding is different than from
153 * encoding of the server. Encoding is set up in the request accepts header and entity expansion is set to true.
154 * @tpPassCrit The response is returned in encoding of the original request not in encoding of the server.
155 * @tpSince RESTEasy 3.0.16
156 */
157 @Test
158 public void testXmlAcceptsExpand() throws Exception {
159 XmlAccepts(EXPAND);
160 }
161
162 /**
163 * @tpTestDetails Client sends POST request with jaxb annotated object entity. Request encoding is different than from
164 * encoding of the server. Encoding is set up in the request accepts header and entity expansion is set to false.
165 * @tpPassCrit The response is returned in encoding of the original request not in encoding of the server.
166 * @tpSince RESTEasy 3.0.16
167 */
168 @Test
169 public void testXmlAcceptsNoExpand() throws Exception {
170 XmlAccepts(NO_EXPAND);
171 }
172
173 private void XmlAccepts(String path) throws Exception {
174 WebTarget target = client.target(PortProviderUtil.generateURL("/xml/accepts", path));
175 logger.info(entityXml);
176 logger.info("client default charset: " + Charset.defaultCharset());
177 Response response = target.request().accept(APPLICATION_XML_UTF16_TYPE).post(Entity.entity(entityXml, APPLICATION_XML_UTF16_TYPE));
178 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
179 KeepCharsetFavoriteMovieXmlRootElement entity = response.readEntity(KeepCharsetFavoriteMovieXmlRootElement.class);
180 logger.info("Result: " + entity);
181 Assert.assertEquals("Incorrect xml entity was returned from the server", "La Règle du Jeu", entity.getTitle());
182 }
183 }
+0
-65
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/LinkJaxbTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.providers.jaxb.resource.LinkJaxbCustomer;
9 import org.jboss.resteasy.test.providers.jaxb.resource.LinkJaxbResource;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Before;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Client;
20 import javax.ws.rs.client.ClientBuilder;
21
22 /**
23 * @tpSubChapter Jaxb provider
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class LinkJaxbTest {
30
31 private static Logger logger = Logger.getLogger(LinkJaxbTest.class.getName());
32 static ResteasyClient client;
33
34 @Deployment
35 public static Archive<?> deploy() {
36 WebArchive war = TestUtil.prepareArchive(LinkJaxbTest.class.getSimpleName());
37 return TestUtil.finishContainerPrepare(war, null, LinkJaxbCustomer.class, LinkJaxbResource.class);
38 }
39
40 @Before
41 public void init() {
42 client = new ResteasyClientBuilder().build();
43 }
44
45 @After
46 public void after() throws Exception {
47 client.close();
48 }
49
50 private String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, LinkJaxbTest.class.getSimpleName());
52 }
53
54 /**
55 * @tpTestDetails Test for javax.ws.rs.core.Link class with Jaxb object
56 * @tpSince RESTEasy 3.0.16
57 */
58 @Test
59 public void testCustomer() throws Exception {
60 Client client = ClientBuilder.newClient();
61 String str = client.target(generateURL("")).request().get(String.class);
62 logger.info(str);
63 }
64 }
+0
-211
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/MapTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.providers.jaxb.resource.MapFoo;
10 import org.jboss.resteasy.test.providers.jaxb.resource.MapJaxb;
11 import org.jboss.resteasy.test.providers.jaxb.resource.MapResource;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.After;
18 import org.junit.Assert;
19 import org.junit.Before;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22 import org.w3c.dom.Element;
23
24 import javax.ws.rs.client.Entity;
25
26 import javax.ws.rs.core.GenericType;
27 import javax.ws.rs.core.Response;
28 import javax.xml.bind.JAXBContext;
29 import javax.xml.bind.JAXBElement;
30 import javax.xml.namespace.QName;
31 import javax.xml.transform.stream.StreamSource;
32 import java.io.ByteArrayInputStream;
33 import java.io.StringWriter;
34 import java.util.Map;
35
36 /**
37 * @tpSubChapter Jaxb provider
38 * @tpChapter Integration tests
39 * @tpSince RESTEasy 3.0.16
40 */
41 @RunWith(Arquillian.class)
42 @RunAsClient
43 public class MapTest {
44
45 private static Logger logger = Logger.getLogger(MapTest.class.getName());
46 static ResteasyClient client;
47
48 @Deployment
49 public static Archive<?> deploy() {
50 WebArchive war = TestUtil.prepareArchive(MapTest.class.getSimpleName());
51 return TestUtil.finishContainerPrepare(war, null, MapFoo.class, MapJaxb.class, MapResource.class);
52 }
53
54 @Before
55 public void init() {
56 client = new ResteasyClientBuilder().build();
57 }
58
59 @After
60 public void after() throws Exception {
61 client.close();
62 }
63
64 private String generateURL(String path) {
65 return PortProviderUtil.generateURL(path, MapTest.class.getSimpleName());
66 }
67
68 /**
69 * @tpTestDetails Tests marshalling and unmarshalling jaxb object into/from map
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test
73 public void testMap() throws Exception {
74 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
75 + "<resteasy:map xmlns=\"http://foo.com\" xmlns:resteasy=\"http://jboss.org/resteasy\">"
76 + "<resteasy:entry key=\"bill\"><mapFoo name=\"hello\"/></resteasy:entry>"
77 + "</resteasy:map>";
78
79 JAXBContext ctx = JAXBContext.newInstance(MapJaxb.class, MapJaxb.Entry.class, MapFoo.class);
80
81 MapJaxb map = new MapJaxb("entry", "key", "http://jboss.org/resteasy");
82 map.addEntry("bill", new MapFoo("hello"));
83
84 JAXBElement<MapJaxb> element = new JAXBElement<MapJaxb>(new QName("http://jboss.org/resteasy", "map", "resteasy"), MapJaxb.class, map);
85
86
87 StringWriter writer = new StringWriter();
88 ctx.createMarshaller().marshal(element, writer);
89 Assert.assertEquals(xml, writer.toString());
90
91 ByteArrayInputStream is = new ByteArrayInputStream(writer.toString().getBytes());
92 StreamSource source = new StreamSource(is);
93 JAXBContext ctx2 = JAXBContext.newInstance(MapJaxb.class);
94 element = ctx2.createUnmarshaller().unmarshal(source, MapJaxb.class);
95
96 Element entry = (Element) element.getValue().getValue().get(0);
97
98 JAXBContext ctx3 = JAXBContext.newInstance(MapJaxb.Entry.class);
99 JAXBElement<MapJaxb.Entry> e = ctx3.createUnmarshaller().unmarshal(entry, MapJaxb.Entry.class);
100 }
101
102 /**
103 * @tpTestDetails Tests Jaxb object which is send to the server and from server, the response is read by using GenericType
104 * @tpSince RESTEasy 3.0.16
105 */
106 @Test
107 public void testProvider() throws Exception {
108 String xml = "<resteasy:map xmlns:resteasy=\"http://jboss.org/resteasy\">"
109 + "<resteasy:entry key=\"bill\" xmlns=\"http://foo.com\">"
110 + "<mapFoo name=\"bill\"/></resteasy:entry>"
111 + "<resteasy:entry key=\"monica\" xmlns=\"http://foo.com\">"
112 + "<mapFoo name=\"monica\"/></resteasy:entry>"
113 + "</resteasy:map>";
114
115 ResteasyWebTarget target = client.target(generateURL("/map"));
116
117 Map<String, MapFoo> entity = target.request().post(Entity.xml(xml), new GenericType<Map<String, MapFoo>>() {
118 });
119 Assert.assertEquals("The response from the server has unexpected content", 2, entity.size());
120 Assert.assertNotNull("The response from the server has unexpected content", entity.get("bill"));
121 Assert.assertNotNull("The response from the server has unexpected content", entity.get("monica"));
122 Assert.assertEquals("The response from the server has unexpected content", entity.get("bill").getName(), "bill");
123 Assert.assertEquals("The response from the server has unexpected content", entity.get("monica").getName(), "monica");
124
125 String entityString = target.request().post(Entity.xml(xml), String.class);
126 logger.info(entityString);
127
128
129 }
130
131 /**
132 * @tpTestDetails Tests Jaxb object which is send to the server and from server, the response is read by using GenericType,
133 * The tested entity contains integer key types
134 * @tpSince RESTEasy 3.0.16
135 */
136 @Test
137 public void testProviderMapIntegerFoo() throws Exception {
138 String xml = "<resteasy:map xmlns:resteasy=\"http://jboss.org/resteasy\">"
139 + "<resteasy:entry key=\"1\" xmlns=\"http://foo.com\">"
140 + "<mapFoo name=\"bill\"/></resteasy:entry>"
141 + "<resteasy:entry key=\"2\" xmlns=\"http://foo.com\">"
142 + "<mapFoo name=\"monica\"/></resteasy:entry>"
143 + "</resteasy:map>";
144
145 ResteasyWebTarget target = client.target(generateURL("/map/integerFoo"));
146 Response response = target.request().post(Entity.xml(xml));
147 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
148
149 Map<String, MapFoo> entity = response.readEntity(new GenericType<Map<String, MapFoo>>() { } );
150 Assert.assertEquals("The response from the server has unexpected content", 2, entity.size());
151 Assert.assertNotNull("The response from the server has unexpected content", entity.get("1"));
152 Assert.assertNotNull("The response from the server has unexpected content", entity.get("2"));
153 Assert.assertEquals("The response from the server has unexpected content", entity.get("1").getName(), "bill");
154 Assert.assertEquals("The response from the server has unexpected content", entity.get("2").getName(), "monica");
155
156 String entityString = target.request().post(Entity.xml(xml), String.class);
157
158 String result = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
159 + "<map xmlns:ns2=\"http://foo.com\">"
160 + "<entry key=\"1\"><ns2:mapFoo name=\"bill\"/></entry>"
161 + "<entry key=\"2\"><ns2:mapFoo name=\"monica\"/></entry>"
162 + "</map>";
163 Assert.assertEquals(result, entityString);
164 }
165
166
167 /**
168 * @tpTestDetails Tests Jaxb object which is send to the server and from server, the response is read by using GenericType,
169 * the resource is annotated with @WrappedMap annotation
170 * @tpSince RESTEasy 3.0.16
171 */
172 @Test
173 public void testWrapped() throws Exception {
174 String xml = "<map xmlns:mapFoo=\"http://foo.com\">"
175 + "<entry key=\"bill\">"
176 + "<mapFoo:mapFoo name=\"bill\"/></entry>"
177 + "<entry key=\"monica\">"
178 + "<mapFoo:mapFoo name=\"monica\"/></entry>"
179 + "</map>";
180
181 ResteasyWebTarget target = client.target(generateURL("/map/wrapped"));
182 Map<String, MapFoo> entity = target.request().post(Entity.xml(xml), new GenericType<Map<String, MapFoo>>() { });
183
184 Assert.assertEquals("The response from the server has unexpected content", 2, entity.size());
185 Assert.assertNotNull("The response from the server has unexpected content", entity.get("bill"));
186 Assert.assertNotNull("The response from the server has unexpected content", entity.get("monica"));
187 Assert.assertEquals("The response from the server has unexpected content", entity.get("bill").getName(), "bill");
188 Assert.assertEquals("The response from the server has unexpected content", entity.get("monica").getName(), "monica");
189
190 }
191
192 /**
193 * @tpTestDetails Tests that Jaxb object with wrong structure returns bad request (400) response code
194 * @tpSince RESTEasy 3.0.16
195 */
196 @Test
197 public void testBadWrapped() throws Exception {
198 String xml = "<resteasy:map xmlns:resteasy=\"http://jboss.org/resteasy\">"
199 + "<resteasy:entry key=\"bill\" xmlns=\"http://foo.com\">"
200 + "<mapFoo name=\"bill\"/></resteasy:entry>"
201 + "<resteasy:entry key=\"monica\" xmlns=\"http://foo.com\">"
202 + "<mapFoo name=\"monica\"/></resteasy:entry>"
203 + "</resteasy:map>";
204
205 ResteasyWebTarget target = client.target(generateURL("/map/wrapped"));
206 Response response = target.request().post(Entity.xml(xml));
207 Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus());
208
209 }
210 }
+0
-100
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/ParsingTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.providers.jaxb.resource.parsing.ParsingAbstractData;
8 import org.jboss.resteasy.test.providers.jaxb.resource.parsing.ParsingDataCollectionPackage;
9 import org.jboss.resteasy.test.providers.jaxb.resource.parsing.ParsingDataCollectionRecord;
10 import org.jboss.resteasy.test.providers.jaxb.resource.parsing.ObjectFactory;
11 import org.jboss.resteasy.test.providers.jaxb.resource.parsing.ParsingStoreResource;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.After;
18 import org.junit.Assert;
19 import org.junit.Before;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 import javax.ws.rs.client.Entity;
24 import javax.ws.rs.core.Response;
25
26 /**
27 * @tpSubChapter Jaxb provider
28 * @tpChapter Integration tests
29 * @tpTestCaseDetails Regression test for RESTEASY-143
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class ParsingTest {
35
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(ParsingTest.class.getSimpleName());
41 war.addClass(ParsingAbstractData.class);
42 war.addClass(ParsingDataCollectionPackage.class);
43 war.addClass(ParsingDataCollectionRecord.class);
44 war.addClass(ObjectFactory.class);
45 return TestUtil.finishContainerPrepare(war, null, ParsingStoreResource.class);
46 }
47
48 @Before
49 public void init() {
50 client = new ResteasyClientBuilder().build();
51 }
52
53 @After
54 public void after() throws Exception {
55 client.close();
56 }
57
58 private String generateURL(String path) {
59 return PortProviderUtil.generateURL(path, ParsingTest.class.getSimpleName());
60 }
61
62 private static final String XML_CONTENT_DEFAULT_NS = "<ParsingDataCollectionPackage xmlns=\"http://www.example.org/ParsingDataCollectionPackage\">\n"
63 + " <sourceID>System A</sourceID>\n"
64 + " <eventID>Exercise B</eventID>\n"
65 + " <dataRecords>\n"
66 + " <ParsingDataCollectionRecord>\n"
67 + " <timestamp>2008-08-13T12:24:00</timestamp>\n"
68 + " <collectedData>Operator pushed easy button</collectedData>\n"
69 + " </ParsingDataCollectionRecord>\n" + " </dataRecords>\n" + "</ParsingDataCollectionPackage>";
70 private static final String XML_CONTENT = "<ns:ParsingDataCollectionPackage xmlns:ns=\"http://www.example.org/ParsingDataCollectionPackage\">\n"
71 + " <sourceID>System A</sourceID>\n"
72 + " <eventID>Exercise B</eventID>\n"
73 + " <dataRecords>\n"
74 + " <ParsingDataCollectionRecord>\n"
75 + " <timestamp>2008-08-13T12:24:00</timestamp>\n"
76 + " <collectedData>Operator pushed easy button</collectedData>\n"
77 + " </ParsingDataCollectionRecord>\n"
78 + " </dataRecords>\n"
79 + "</ns:ParsingDataCollectionPackage>";
80
81 /**
82 * @tpTestDetails Check XML parsing
83 * @tpSince RESTEasy 3.0.16
84 */
85 @Test
86 public void testWire() throws Exception {
87 {
88 Response response = client.target(generateURL("/storeXML")).request().post(Entity.entity(XML_CONTENT, "application/xml"));
89 Assert.assertEquals(HttpResponseCodes.SC_CREATED, response.getStatus());
90 response.close();
91 }
92
93 {
94 Response response = client.target(generateURL("/storeXML/abstract")).request().post(Entity.entity(XML_CONTENT, "application/xml"));
95 Assert.assertEquals(HttpResponseCodes.SC_CREATED, response.getStatus());
96 response.close();
97 }
98 }
99 }
+0
-67
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/QualityFactorTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5
6 import org.jboss.logging.Logger;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.providers.jaxb.resource.QualityFactorResource;
10 import org.jboss.resteasy.test.providers.jaxb.resource.QualityFactorThing;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.core.Response;
22
23 /**
24 * @tpSubChapter Jaxb provider
25 * @tpChapter Integration tests
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class QualityFactorTest {
31
32 static ResteasyClient client;
33 private static Logger logger = Logger.getLogger(QualityFactorTest.class.getName());
34
35
36 @Deployment
37 public static Archive<?> deploy() {
38 WebArchive war = TestUtil.prepareArchive(QualityFactorTest.class.getSimpleName());
39 war.addClass(JaxbCollectionTest.class);
40 return TestUtil.finishContainerPrepare(war, null, QualityFactorResource.class, QualityFactorThing.class);
41 }
42
43 @Before
44 public void init() {
45 client = new ResteasyClientBuilder().build();
46 }
47
48 @After
49 public void after() throws Exception {
50 client.close();
51 }
52
53 private String generateURL(String path) {
54 return PortProviderUtil.generateURL(path, QualityFactorTest.class.getSimpleName());
55 }
56
57 @Test
58 public void testHeader() throws Exception {
59 Response response = client.target(generateURL("/test")).request()
60 .accept("application/xml; q=0.5", "application/json; q=0.8").get();
61 String result = response.readEntity(String.class);
62 logger.info(result);
63 Assert.assertTrue("The format of the response doesn't reflect the quality factor", result.startsWith("{"));
64
65 }
66 }
+0
-96
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/SeeAlsoAnnotationTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.providers.jaxb.resource.SeeAlsoAnnotationRealFoo;
10 import org.jboss.resteasy.test.providers.jaxb.resource.SeeAlsoAnnotationResource;
11 import org.jboss.resteasy.test.providers.jaxb.resource.SeeAlsoAnnotationBaseFoo;
12 import org.jboss.resteasy.test.providers.jaxb.resource.SeeAlsoAnnotationFooIntf;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.After;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Entity;
23 import javax.xml.bind.JAXBContext;
24 import java.io.StringWriter;
25
26 /**
27 * @tpSubChapter Jaxb provider
28 * @tpChapter Integration tests
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class SeeAlsoAnnotationTest {
34
35 private final Logger logger = Logger.getLogger(SeeAlsoAnnotationTest.class.getName());
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(SeeAlsoAnnotationTest.class.getSimpleName());
41 return TestUtil.finishContainerPrepare(war, null, SeeAlsoAnnotationResource.class, SeeAlsoAnnotationRealFoo.class,
42 SeeAlsoAnnotationBaseFoo.class, SeeAlsoAnnotationFooIntf.class);
43 }
44
45 @Before
46 public void init() {
47 client = new ResteasyClientBuilder().build();
48 }
49
50 @After
51 public void after() throws Exception {
52 client.close();
53 client = null;
54 }
55
56 private String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, SeeAlsoAnnotationTest.class.getSimpleName());
58 }
59
60 /**
61 * @tpTestDetails Tests jaxb @SeeAlsoAnnotation
62 * @tpSince RESTEasy 3.0.16
63 */
64 @Test
65 public void testIntf() throws Exception {
66 String url = generateURL("/see/intf");
67 runTest(url);
68 }
69
70 /**
71 * @tpTestDetails Tests jaxb @SeeAlsoAnnotation
72 * @tpSince RESTEasy 3.0.16
73 */
74 @Test
75 public void testTest() throws Exception {
76 String url = generateURL("/see/base");
77 runTest(url);
78 }
79
80 private void runTest(String url) throws Exception {
81 JAXBContext ctx = JAXBContext.newInstance(SeeAlsoAnnotationRealFoo.class);
82 StringWriter writer = new StringWriter();
83 SeeAlsoAnnotationRealFoo foo = new SeeAlsoAnnotationRealFoo();
84 foo.setName("bill");
85
86 ctx.createMarshaller().marshal(foo, writer);
87
88 String s = writer.getBuffer().toString();
89 logger.info(s);
90
91 ResteasyWebTarget target = client.target(generateURL(url));
92 target.request().header("Content-Type", "application/xml").put(Entity.xml(s));
93 }
94
95 }
+0
-140
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/StatsTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import java.util.ArrayList;
3 import java.util.List;
4
5 import org.jboss.arquillian.container.test.api.Deployment;
6 import org.jboss.arquillian.container.test.api.RunAsClient;
7 import org.jboss.arquillian.junit.Arquillian;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.plugins.stats.RegistryStatsResource;
11 import org.jboss.resteasy.plugins.stats.RegistryData;
12 import org.jboss.resteasy.plugins.stats.RegistryEntry;
13 import org.jboss.resteasy.plugins.stats.PostResourceMethod;
14 import org.jboss.resteasy.plugins.stats.PutResourceMethod;
15 import org.jboss.resteasy.plugins.stats.HeadResourceMethod;
16 import org.jboss.resteasy.plugins.stats.DeleteResourceMethod;
17 import org.jboss.resteasy.plugins.stats.ResourceMethodEntry;
18 import org.jboss.resteasy.plugins.stats.GetResourceMethod;
19 import org.jboss.resteasy.test.providers.jaxb.resource.StatsProxy;
20 import org.jboss.resteasy.test.providers.jaxb.resource.StatsResource;
21 import org.jboss.resteasy.utils.PortProviderUtil;
22 import org.jboss.resteasy.utils.TestUtil;
23 import org.jboss.shrinkwrap.api.Archive;
24 import org.jboss.shrinkwrap.api.spec.WebArchive;
25 import org.junit.After;
26 import org.junit.Assert;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30
31 /**
32 * @tpSubChapter Jaxb provider
33 * @tpChapter Integration tests
34 * @tpSince RESTEasy 3.0.16
35 */
36 @RunWith(Arquillian.class)
37 @RunAsClient
38 public class StatsTest {
39
40 static ResteasyClient client;
41
42 @Deployment
43 public static Archive<?> deploy() {
44 WebArchive war = TestUtil.prepareArchive(StatsTest.class.getSimpleName());
45 war.addClass(StatsTest.class);
46 return TestUtil.finishContainerPrepare(war, null, StatsResource.class, RegistryStatsResource.class);
47 }
48
49 @Before
50 public void init() {
51 client = new ResteasyClientBuilder().build();
52 }
53
54 @After
55 public void after() throws Exception {
56 client.close();
57 }
58
59 private String generateURL(String path) {
60 return PortProviderUtil.generateURL(path, StatsTest.class.getSimpleName());
61 }
62
63 /**
64 * @tpTestDetails Tests resteasy jaxb utility RegistryStatsResource, it is getting information about resources available
65 * to the application
66 * @tpSince RESTEasy 3.0.16
67 */
68 @Test
69 public void testRegistryStats() throws Exception {
70 StatsProxy stats = client.target(generateURL("/")).proxy(StatsProxy.class);
71
72 RegistryData data = stats.get();
73 Assert.assertEquals("The number of resources doesn't match", 4, data.getEntries().size());
74 boolean found = false;
75 for (RegistryEntry entry : data.getEntries()) {
76 if (entry.getUriTemplate().equals("/entry/{foo:.*}")) {
77 Assert.assertEquals("Some method for resource \"" + entry.getUriTemplate() + "\" is missing ", 2,
78 entry.getMethods().size());
79 List<Class> prepareRequiredTypes = prepareRequiredTypes(PostResourceMethod.class, PutResourceMethod.class);
80 Assert.assertTrue("Unexpected method type", testMethodTypes(entry.getMethods().get(0), prepareRequiredTypes));
81 Assert.assertTrue("Unexpected method type", testMethodTypes(entry.getMethods().get(1), prepareRequiredTypes));
82 found = true;
83 break;
84 }
85 }
86 Assert.assertTrue("Resource not found", found);
87 found = false;
88 for (RegistryEntry entry : data.getEntries()) {
89 if (entry.getUriTemplate().equals("/resource")) {
90 Assert.assertEquals("Some method for resource \"" + entry.getUriTemplate() + "\" is missing ", 2,
91 entry.getMethods().size());
92 List<Class> prepareRequiredTypes = prepareRequiredTypes(HeadResourceMethod.class, DeleteResourceMethod.class);
93 Assert.assertTrue("Unexpected method type", testMethodTypes(entry.getMethods().get(0), prepareRequiredTypes));
94 Assert.assertTrue("Unexpected method type", testMethodTypes(entry.getMethods().get(1), prepareRequiredTypes));
95 found = true;
96 break;
97 }
98 }
99 Assert.assertTrue("Resource not found", found);
100 found = false;
101 for (RegistryEntry entry : data.getEntries()) {
102 if (entry.getUriTemplate().equals("/locator")) {
103 Assert.assertNotNull(entry.getLocator());
104 found = true;
105 break;
106 }
107 }
108 Assert.assertTrue("Resource not found", found);
109 found = false;
110 for (RegistryEntry entry : data.getEntries()) {
111 if (entry.getUriTemplate().equals("/resteasy/registry")) {
112 Assert.assertEquals("Some method for resource \"" + entry.getUriTemplate() + "\" is missing ", 1,
113 entry.getMethods().size());
114 Assert.assertTrue("Unexpected method type", entry.getMethods().get(0) instanceof GetResourceMethod);
115 found = true;
116 break;
117 }
118 }
119 Assert.assertTrue("Resource not found", found);
120
121 }
122
123 private boolean testMethodTypes(ResourceMethodEntry entry, List<Class> types) {
124 if (types.contains(entry.getClass())) {
125 types.remove(entry.getClass());
126 return true;
127 } else {
128 return false;
129 }
130 }
131
132 private List<Class> prepareRequiredTypes(Class... types) {
133 ArrayList<Class> list = new ArrayList<Class>();
134 for (Class type : types) {
135 list.add(type);
136 }
137 return list;
138 }
139 }
+0
-135
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/StreamResetTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
7 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
8 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.test.providers.jaxb.resource.StreamResetPlace;
11 import org.jboss.resteasy.test.providers.jaxb.resource.StreamResetResource;
12 import org.jboss.resteasy.test.providers.jaxb.resource.StreamResetPerson;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20 import org.jboss.resteasy.utils.TestUtil;
21 import org.jboss.resteasy.utils.PortProviderUtil;
22
23 import javax.ws.rs.client.Client;
24 import javax.ws.rs.client.ClientBuilder;
25 import javax.ws.rs.client.WebTarget;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @tpSubChapter Jaxb provider
30 * @tpChapter Integration tests
31 * @tpSince RESTEasy 3.0.16
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class StreamResetTest {
36
37 private final Logger logger = Logger.getLogger(StreamResetTest.class);
38
39 static ResteasyClient client;
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(StreamResetTest.class.getSimpleName());
44 war.addClass(StreamResetTest.class);
45 return TestUtil.finishContainerPrepare(war, null, StreamResetPlace.class, StreamResetPerson.class,
46 StreamResetResource.class);
47 }
48
49 @Before
50 public void init() {
51 client = new ResteasyClientBuilder().build();
52 }
53
54 @After
55 public void after() throws Exception {
56 client.close();
57 client = null;
58 }
59
60 private String generateURL(String path) {
61 return PortProviderUtil.generateURL(path, StreamResetTest.class.getSimpleName());
62 }
63
64 /**
65 * @tpTestDetails Regression test for JBEAP-2138. BufferEntity method is called.
66 * @tpSince RESTEasy 3.0.16
67 */
68 @Test
69 public void testJBEAP2138() throws Exception {
70 Client client = ClientBuilder.newClient();
71 WebTarget target = client.target(generateURL("/test"));
72 Response response = target.request().get();
73
74 response.bufferEntity();
75
76 try {
77 response.readEntity(StreamResetPlace.class);
78 } catch (Exception e) {
79 }
80
81 response.readEntity(StreamResetPerson.class);
82 }
83
84 /**
85 * @tpTestDetails Regression test for JBEAP-2138. BufferEntity method is not called.
86 * @tpSince RESTEasy 3.0.16
87 */
88 @Test
89 public void testJBEAP2138WithoutBufferedEntity() throws Exception {
90 try {
91 Client client = ClientBuilder.newClient();
92 WebTarget target = client.target(generateURL("/test"));
93 Response response = target.request().get();
94
95 try {
96 response.readEntity(StreamResetPlace.class);
97 } catch (Exception e) {
98 }
99
100 response.readEntity(StreamResetPerson.class);
101
102 Assert.fail();
103 } catch (IllegalStateException e) {
104 logger.info("Expected IllegalStateException was thrown");
105 }
106 }
107
108 /**
109 * @tpTestDetails Tests streamReset method of deprecated ClientResponse class. In case exception is thrown during processing
110 * response from the server, the stream of the response must be reset before reading it again.
111 * @tpPassCrit After exception is thrown the response is parsed correctly with getEntity()
112 * @tpInfo RESTEASY-456
113 * @tpSince RESTEasy 3.0.16
114 */
115 @Test
116 public void testClientRequestResetStream() throws Exception {
117 ClientRequest request = new ClientRequest(generateURL("/test"));
118 ClientResponse<StreamResetPlace> response = request.get(StreamResetPlace.class);
119 boolean exceptionThrown = false;
120 try {
121 StreamResetPlace place = response.getEntity();
122
123 } catch (Exception e) {
124 exceptionThrown = true;
125 }
126 Assert.assertTrue("The expected exception didn't happen", exceptionThrown);
127
128 response.resetStream();
129 StreamResetPerson person = response.getEntity(StreamResetPerson.class);
130 Assert.assertNotNull("The stream was not correctly reset", person);
131 Assert.assertEquals("The response from the server is not the one expected", "bill", person.getName());
132 }
133
134 }
+0
-68
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/StringCharsetTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.providers.jaxb.resource.StringCharsetResource;
10 import org.jboss.resteasy.test.providers.jaxb.resource.StringCharsetRespond;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 /**
22 * @tpSubChapter Jaxb provider
23 * @tpChapter Integration tests
24 * @tpSince RESTEasy 3.0.16
25 */
26 @RunWith(Arquillian.class)
27 @RunAsClient
28 public class StringCharsetTest {
29
30 private final Logger logger = Logger.getLogger(ExceptionMapperJaxbTest.class.getName());
31 static ResteasyClient client;
32
33 @Deployment
34 public static Archive<?> deploy() {
35 WebArchive war = TestUtil.prepareArchive(StringCharsetTest.class.getSimpleName());
36 war.addClass(StreamResetTest.class);
37 return TestUtil.finishContainerPrepare(war, null, StringCharsetResource.class, StringCharsetRespond.class);
38 }
39
40 @Before
41 public void init() {
42 client = new ResteasyClientBuilder().build();
43 }
44
45 @After
46 public void after() throws Exception {
47 client.close();
48 client = null;
49 }
50
51 private String generateURL(String path) {
52 return PortProviderUtil.generateURL(path, StringCharsetTest.class.getSimpleName());
53 }
54
55 /**
56 * @tpTestDetails Tests jaxb with combination of request specified charset
57 * @tpSince RESTEasy 3.0.16
58 */
59 @Test
60 public void testIt() throws Exception {
61 ResteasyWebTarget target = client.target(generateURL("/charset/test.xml"));
62 String response = target.request().header("Accept", "application/xml;charset=iso-8859-2").get(String.class);
63 logger.info(response);
64 Assert.assertTrue("Response doesn't contain expected characters",
65 response.contains("Test " + (char) 353 + (char) 273 + (char) 382 + (char) 269));
66 }
67 }
+0
-66
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/XmlEnumParamTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.providers.jaxb.resource.XmlEnumParamLocation;
9 import org.jboss.resteasy.test.providers.jaxb.resource.XmlEnumParamResource;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.Assert;
13 import org.junit.Before;
14 import org.junit.Test;
15 import org.junit.After;
16 import org.junit.runner.RunWith;
17 import org.jboss.resteasy.utils.TestUtil;
18 import org.jboss.resteasy.utils.PortProviderUtil;
19
20 /**
21 * @tpSubChapter Jaxb provider
22 * @tpChapter Integration tests
23 * @tpSince RESTEasy 3.0.16
24 */
25 @RunWith(Arquillian.class)
26 @RunAsClient
27 public class XmlEnumParamTest {
28
29 static ResteasyClient client;
30
31 @Deployment
32 public static Archive<?> deploy() {
33 WebArchive war = TestUtil.prepareArchive(XmlEnumParamTest.class.getSimpleName());
34 war.addClass(XmlEnumParamTest.class);
35 return TestUtil.finishContainerPrepare(war, null, XmlEnumParamResource.class, XmlEnumParamLocation.class);
36 }
37
38 @Before
39 public void init() {
40 client = new ResteasyClientBuilder().build();
41 }
42
43 @After
44 public void after() throws Exception {
45 client.close();
46 }
47
48 private String generateURL(String path) {
49 return PortProviderUtil.generateURL(path, XmlEnumParamTest.class.getSimpleName());
50 }
51
52 /**
53 * @tpTestDetails Tests xml enum param in the resource
54 * @tpPassCrit The expected enum type is returned
55 * @tpInfo RESTEASY-428
56 * @tpSince RESTEasy 3.0.16
57 */
58 @Test
59 public void testXmlEnumParam() throws Exception {
60 ResteasyWebTarget target = client.target(generateURL("/enum"));
61 String response = target.queryParam("loc", "north").request().get(String.class);
62 Assert.assertEquals("The response doesn't contain expected enum type", "NORTH", response.toUpperCase());
63 }
64
65 }
+0
-91
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/XmlHeaderTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
9 import org.jboss.resteasy.test.providers.jaxb.resource.XmlHeaderResource;
10 import org.jboss.resteasy.test.providers.jaxb.resource.XmlHeaderDecorator;
11 import org.jboss.resteasy.test.providers.jaxb.resource.XmlHeaderDecorator2;
12 import org.jboss.resteasy.test.providers.jaxb.resource.XmlHeaderJunk2Intf;
13 import org.jboss.resteasy.test.providers.jaxb.resource.XmlHeaderJunkIntf;
14 import org.jboss.resteasy.test.providers.jaxb.resource.XmlHeaderThing;
15 import org.jboss.resteasy.utils.PortProviderUtil;
16 import org.jboss.resteasy.utils.TestUtil;
17 import org.jboss.shrinkwrap.api.Archive;
18 import org.jboss.shrinkwrap.api.asset.StringAsset;
19 import org.jboss.shrinkwrap.api.spec.WebArchive;
20 import org.junit.After;
21 import org.junit.Assert;
22 import org.junit.Before;
23 import org.junit.Test;
24 import org.junit.runner.RunWith;
25
26 /**
27 * @tpSubChapter Jaxb provider
28 * @tpChapter Integration tests
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class XmlHeaderTest {
34
35 private final Logger logger = Logger.getLogger(XmlHeaderTest.class.getName());
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(XmlHeaderTest.class.getSimpleName());
41 return TestUtil.finishContainerPrepare(war, null, XmlHeaderResource.class, XmlHeaderDecorator.class,
42 XmlHeaderDecorator2.class, XmlHeaderJunk2Intf.class, XmlHeaderJunkIntf.class, XmlHeaderThing.class);
43 }
44
45 @Before
46 public void init() {
47 client = new ResteasyClientBuilder().build();
48 }
49
50 @After
51 public void after() throws Exception {
52 client.close();
53 client = null;
54 }
55
56 private String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, XmlHeaderTest.class.getSimpleName());
58 }
59
60 /**
61 * @tpTestDetails This tests decorators in general with the @XmlHeader annotation
62 * @tpPassCrit The response contains expected xml-stylesheet header
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void testHeader() throws Exception {
67 ResteasyWebTarget target = client.target(generateURL("/test/header"));
68 String response = target.request().get(String.class);
69 logger.info(response);
70 Assert.assertTrue("The response doesn't contain the expected xml-stylesheet header",
71 response.contains("<?xml-stylesheet"));
72
73 }
74
75 /**
76 * @tpTestDetails This tests decorators in general with the @Stylesheet annotation
77 * @tpPassCrit The response contains expected xml-stylesheet header
78 * @tpSince RESTEasy 3.0.16
79 */
80 @Test
81 public void testStylesheet() throws Exception {
82 ResteasyWebTarget target = client.target(generateURL("/test/stylesheet"));
83 String response = target.request().get(String.class);
84 logger.info(response);
85 Assert.assertTrue("The response doesn't contain the expected xml-stylesheet header",
86 response.contains("<?xml-stylesheet"));
87
88 }
89
90 }
+0
-214
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/XmlJAXBContextFinderTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.client.Client;
6 import javax.ws.rs.client.ClientBuilder;
7 import javax.ws.rs.client.WebTarget;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Response;
10 import javax.ws.rs.ext.ContextResolver;
11 import javax.ws.rs.ext.Provider;
12 import javax.xml.bind.JAXBContext;
13 import javax.xml.bind.JAXBException;
14 import javax.xml.bind.annotation.XmlAccessType;
15 import javax.xml.bind.annotation.XmlAccessorType;
16 import javax.xml.bind.annotation.XmlAnyElement;
17 import javax.xml.bind.annotation.XmlRootElement;
18
19 import org.jboss.arquillian.container.test.api.Deployment;
20 import org.jboss.arquillian.container.test.api.RunAsClient;
21 import org.jboss.arquillian.junit.Arquillian;
22 import org.jboss.resteasy.utils.PortProviderUtil;
23 import org.jboss.resteasy.utils.TestUtil;
24 import org.jboss.shrinkwrap.api.Archive;
25 import org.jboss.shrinkwrap.api.spec.WebArchive;
26 import org.junit.Assert;
27 import org.junit.Test;
28 import org.junit.runner.RunWith;
29
30 /**
31 * @tpSubChapter Jaxb provider
32 * @tpChapter Integration tests
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class XmlJAXBContextFinderTest {
38
39 @Deployment
40 public static Archive<?> deploy() {
41 WebArchive war = TestUtil.prepareArchive(XmlJAXBContextFinderTest.class.getSimpleName());
42 return TestUtil.finishContainerPrepare(war, null, BeanWrapper.class,
43 FirstBean.class, SecondBean.class,
44 FirstTestResource.class, SecondTestResource.class,
45 MyJAXBContextResolver.class);
46 }
47
48 @XmlRootElement
49 @XmlAccessorType(XmlAccessType.FIELD)
50 public static final class BeanWrapper {
51
52 @XmlAnyElement(lax = true)
53 private Object bean;
54
55 public Object getBean() {
56 return this.bean;
57 }
58
59 public void setBean(Object bean) {
60 this.bean = bean;
61 }
62
63 }
64
65 @XmlRootElement
66 @XmlAccessorType(XmlAccessType.FIELD)
67 public static final class FirstBean {
68
69 private String data;
70
71 public String getData() {
72 return this.data;
73 }
74
75 public void setData(String data) {
76 this.data = data;
77 }
78
79 }
80
81 @XmlRootElement
82 @XmlAccessorType(XmlAccessType.FIELD)
83 public static final class SecondBean {
84
85 private String data;
86
87 public String getData() {
88 return this.data;
89 }
90
91 public void setData(String data) {
92 this.data = data;
93 }
94
95 }
96
97 @Path("/firstTestResource")
98 @Produces(MediaType.APPLICATION_XML)
99 public static final class FirstTestResource {
100
101 @GET
102 public Response get() {
103 FirstBean firstBean = new FirstBean();
104 firstBean.setData("firstTestResource");
105 BeanWrapper beanWrapper = new BeanWrapper();
106 beanWrapper.setBean(firstBean);
107 return Response.ok(beanWrapper).build();
108 }
109
110 }
111
112 @Path("/secondTestResource")
113 @Produces(MediaType.APPLICATION_XML)
114 public static final class SecondTestResource {
115
116 @GET
117 public Response get() {
118 SecondBean secondBean = new SecondBean();
119 secondBean.setData("secondTestResource");
120 BeanWrapper beanWrapper = new BeanWrapper();
121 beanWrapper.setBean(secondBean);
122 return Response.ok(beanWrapper).build();
123 }
124
125 }
126
127 @Provider
128 @Produces(MediaType.APPLICATION_XML)
129 public static class MyJAXBContextResolver implements ContextResolver<JAXBContext> {
130 private JAXBContext jaxbContext;
131
132 @Override
133 public JAXBContext getContext(Class<?> type) {
134 if (this.jaxbContext == null) {
135 try {
136 this.jaxbContext = JAXBContext.newInstance(BeanWrapper.class,
137 FirstBean.class, SecondBean.class);
138 } catch (JAXBException e) {
139 }
140 }
141 return this.jaxbContext;
142 }
143 }
144
145 private String generateURL(String path) {
146 return PortProviderUtil.generateURL(path, XmlJAXBContextFinderTest.class.getSimpleName());
147 }
148
149 /**
150 * @tpTestDetails In the following test both firstWebTarget and secondWebTarget will share the same XmlJAXBContextFinder
151 * inherited from their shared parent configuration. We define and register a ContextResolver<JAXBContext> for each
152 * webTarget so that firstWebTarget and secondWebTarget have its own (respectively firstJaxbContextResolver
153 * and secondJaxbContextResolver).
154 * @tpSince RESTEasy 3.0.16
155 */
156 @Test
157 public void test() {
158 Client client = ClientBuilder.newClient();
159 try {
160 // First webTarget
161 WebTarget firstWebTarget = client.target(generateURL("/firstTestResource"));
162 ContextResolver<JAXBContext> firstJaxbContextResolver = new ContextResolver<JAXBContext>() {
163
164 private JAXBContext jaxbContext;
165
166 @Override
167 public JAXBContext getContext(Class<?> type) {
168 if (this.jaxbContext == null) {
169 try {
170 this.jaxbContext = JAXBContext.newInstance(BeanWrapper.class,
171 FirstBean.class);
172 } catch (JAXBException e) {
173 }
174 }
175 return this.jaxbContext;
176 }
177
178 };
179 Response firstResponse = firstWebTarget.register(firstJaxbContextResolver)
180 .request(MediaType.APPLICATION_XML_TYPE).get();
181 BeanWrapper firstBeanWrapper = firstResponse.readEntity(BeanWrapper.class);
182 Assert.assertTrue("First bean is not assignable from the parent bean", FirstBean.class.isAssignableFrom(firstBeanWrapper.getBean().getClass()));
183
184 // Second webTarget
185 WebTarget secondWebTarget = client.target(generateURL("/secondTestResource"));
186 // Will never be called
187 ContextResolver<JAXBContext> secondJaxbContextResolver = new ContextResolver<JAXBContext>() {
188
189 private JAXBContext jaxbContext;
190
191 @Override
192 public JAXBContext getContext(Class<?> type) {
193 if (this.jaxbContext == null) {
194 try {
195 this.jaxbContext = JAXBContext.newInstance(BeanWrapper.class,
196 SecondBean.class);
197 } catch (JAXBException e) {
198 }
199 }
200 return this.jaxbContext;
201 }
202
203 };
204 Response secondResponse = secondWebTarget.register(secondJaxbContextResolver)
205 .request(MediaType.APPLICATION_XML_TYPE).get();
206 BeanWrapper secondBeanWrapper = secondResponse.readEntity(BeanWrapper.class);
207 Assert.assertTrue("Second bean is not assignable from the parent bean", SecondBean.class.isAssignableFrom(secondBeanWrapper.getBean().getClass()));
208 } finally {
209 client.close();
210 }
211 }
212
213 }
+0
-276
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/XmlJavaTypeAdapterTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import java.util.ArrayList;
3 import java.util.HashMap;
4 import java.util.List;
5 import java.util.Map;
6
7 import javax.ws.rs.client.Entity;
8 import javax.ws.rs.core.GenericEntity;
9 import javax.ws.rs.core.GenericType;
10 import javax.ws.rs.core.MediaType;
11
12 import org.jboss.arquillian.container.test.api.Deployment;
13 import org.jboss.arquillian.container.test.api.RunAsClient;
14 import org.jboss.arquillian.junit.Arquillian;
15 import org.jboss.logging.Logger;
16 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
17 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
18 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
19 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJavaTypeAdapterResource;
20 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJavaTypeAdapterAlien;
21 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJavaTypeAdapterAlienAdapter;
22 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJavaTypeAdapterHuman;
23 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJavaTypeAdapterFoo;
24 import org.jboss.resteasy.utils.PortProviderUtil;
25 import org.jboss.resteasy.utils.TestUtil;
26 import org.jboss.shrinkwrap.api.Archive;
27 import org.jboss.shrinkwrap.api.spec.WebArchive;
28 import org.junit.Before;
29 import org.junit.After;
30 import org.junit.Test;
31 import org.junit.Assert;
32 import org.junit.runner.RunWith;
33
34 /**
35 * @tpSubChapter Jaxb provider
36 * @tpChapter Integration tests
37 * @tpSince RESTEasy 3.0.16
38 */
39 @RunWith(Arquillian.class)
40 public class XmlJavaTypeAdapterTest {
41
42 private final Logger logger = Logger.getLogger(XmlJavaTypeAdapterTest.class.getName());
43 static ResteasyClient client;
44
45 @Deployment
46 public static Archive<?> deploy() {
47 WebArchive war = TestUtil.prepareArchive(XmlJavaTypeAdapterTest.class.getSimpleName());
48 war.addClass(XmlJavaTypeAdapterTest.class);
49 return TestUtil.finishContainerPrepare(war, null, XmlJavaTypeAdapterAlien.class, XmlJavaTypeAdapterAlienAdapter.class,
50 XmlJavaTypeAdapterFoo.class, XmlJavaTypeAdapterHuman.class, XmlJavaTypeAdapterResource.class, PortProviderUtil.class);
51 }
52
53 @Before
54 public void init() {
55 client = new ResteasyClientBuilder().build();
56 }
57
58 @After
59 public void after() throws Exception {
60 client.close();
61 client = null;
62 }
63
64 private String generateURL(String path) {
65 return PortProviderUtil.generateURL(path, XmlJavaTypeAdapterTest.class.getSimpleName());
66 }
67
68 public static class Tralfamadorean extends XmlJavaTypeAdapterAlien {
69 }
70
71 /**
72 * @tpTestDetails Tests jaxb resource is returning correct string with @XmlJavaTypeAdapter in place
73 * @tpInfo RESTEASY-1088
74 * @tpSince RESTEasy 3.0.16
75 */
76 @Test
77 @RunAsClient
78 public void testPostHuman() {
79 ResteasyWebTarget target = client.target(generateURL("/human"));
80 XmlJavaTypeAdapterHuman human = new XmlJavaTypeAdapterHuman();
81 human.setName("bill");
82 String response = target.request().post(Entity.entity(human, MediaType.APPLICATION_XML_TYPE), String.class);
83 Assert.assertEquals("The received response was not the expected one", "bill", response);
84 }
85
86 /**
87 * @tpTestDetails Tests jaxb with class annotated by @XmlJavaTypeAdapter, resource returning Foo object
88 * @tpInfo RESTEASY-1088
89 * @tpSince RESTEasy 3.0.16
90 */
91 @Test
92 @RunAsClient
93 public void testPostFooToFoo() {
94 ResteasyWebTarget target = client.target(generateURL("/foo/foo"));
95 XmlJavaTypeAdapterFoo foo = new XmlJavaTypeAdapterFoo();
96 foo.setName("bill");
97 XmlJavaTypeAdapterFoo response = target.request().post(Entity.entity(foo, MediaType.APPLICATION_XML_TYPE), XmlJavaTypeAdapterFoo.class);
98 Assert.assertEquals("The received response was not the expected one", foo, response);
99 }
100
101 /**
102 * @tpTestDetails Tests jaxb with class annotated by @XmlJavaTypeAdapter, resource returning String
103 * @tpInfo RESTEASY-1088
104 * @tpSince RESTEasy 3.0.16
105 */
106 @Test
107 @RunAsClient
108 public void testPostFooToString() {
109 ResteasyWebTarget target = client.target(generateURL("/foo/foo"));
110 XmlJavaTypeAdapterFoo foo = new XmlJavaTypeAdapterFoo();
111 foo.setName("bill");
112 String response = target.request().post(Entity.entity(foo, MediaType.APPLICATION_XML_TYPE), String.class);
113 logger.info("response: \"" + response + "\"");
114 Assert.assertTrue("The received response was not the expected one",
115 response.contains("<xmlJavaTypeAdapterFoo><alien><name>llib</name></alien></xmlJavaTypeAdapterFoo>"));
116 }
117
118 /**
119 * @tpTestDetails Tests jaxb with class annotated by @XmlJavaTypeAdapter, resource returning list of Human objects
120 * @tpInfo RESTEASY-1088
121 * @tpSince RESTEasy 3.0.16
122 */
123 @Test
124 @RunAsClient
125 public void testPostHumanList() {
126 ResteasyWebTarget target = client.target(generateURL("/list/human"));
127 List<XmlJavaTypeAdapterHuman> list = new ArrayList<XmlJavaTypeAdapterHuman>();
128 XmlJavaTypeAdapterHuman human = new XmlJavaTypeAdapterHuman();
129 human.setName("bill");
130 list.add(human);
131 human = new XmlJavaTypeAdapterHuman();
132 human.setName("bob");
133 list.add(human);
134 GenericEntity<List<XmlJavaTypeAdapterHuman>> entity = new GenericEntity<List<XmlJavaTypeAdapterHuman>>(list) {
135 };
136 String response = target.request().post(Entity.entity(entity, MediaType.APPLICATION_XML_TYPE), String.class);
137 Assert.assertEquals("The received response was not the expected one", "|bill|bob", response);
138 }
139
140 /**
141 * @tpTestDetails Tests jaxb with class annotated by @XmlJavaTypeAdapter, resource returning list of Alien objects,
142 * where application expects the use of Human class with jaxb annotation, XmlJavaTypeAdapter is used to convert Alien
143 * to Human and back
144 * @tpInfo RESTEASY-1088
145 * @tpSince RESTEasy 3.0.16
146 */
147 @Test
148 public void testPostAlienList() {
149 ResteasyWebTarget target = client.target(generateURL("/list/alien"));
150 List<XmlJavaTypeAdapterAlien> list = new ArrayList<XmlJavaTypeAdapterAlien>();
151 XmlJavaTypeAdapterAlien alien1 = new XmlJavaTypeAdapterAlien();
152 alien1.setName("bill");
153 list.add(alien1);
154 XmlJavaTypeAdapterAlien alien2 = new XmlJavaTypeAdapterAlien();
155 alien2.setName("bob");
156 list.add(alien2);
157 GenericEntity<List<XmlJavaTypeAdapterAlien>> entity = new GenericEntity<List<XmlJavaTypeAdapterAlien>>(list) {
158 };
159 GenericType<List<XmlJavaTypeAdapterAlien>> alienListType = new GenericType<List<XmlJavaTypeAdapterAlien>>() {
160 };
161 List<XmlJavaTypeAdapterAlien> response = target.request().post(Entity.entity(entity, MediaType.APPLICATION_XML_TYPE), alienListType);
162 logger.info("response: \"" + response + "\"");
163 Assert.assertEquals("The received response was not the expected one", 2, response.size());
164 Assert.assertTrue("The received response was not the expected one", response.contains(alien1));
165 Assert.assertTrue("The received response was not the expected one", response.contains(alien2));
166 Assert.assertEquals("The marshalling of the Alien didn't happen the correct way",
167 4, XmlJavaTypeAdapterAlienAdapter.marshalCounter);
168 Assert.assertEquals("The unmarshalling of the Human didn't happen the correct way",
169 4, XmlJavaTypeAdapterAlienAdapter.unmarshalCounter);
170 XmlJavaTypeAdapterAlienAdapter.unmarshalCounter = 0;
171 XmlJavaTypeAdapterAlienAdapter.marshalCounter = 0;
172 }
173
174 /**
175 * @tpTestDetails Tests jaxb with class annotated by @XmlJavaTypeAdapter, resource returning array of Alien objects,
176 * where application expects the use of Human class with jaxb annotation, XmlJavaTypeAdapter is used to convert Alien
177 * to Human and back
178 * @tpInfo RESTEASY-1088
179 * @tpSince RESTEasy 3.0.16
180 */
181 @Test
182 public void testPostAlienArray() {
183 ResteasyWebTarget target = client.target(generateURL("/array/alien"));
184 XmlJavaTypeAdapterAlien[] array = new XmlJavaTypeAdapterAlien[2];
185 XmlJavaTypeAdapterAlien alien1 = new XmlJavaTypeAdapterAlien();
186 alien1.setName("bill");
187 array[0] = alien1;
188 XmlJavaTypeAdapterAlien alien2 = new XmlJavaTypeAdapterAlien();
189 alien2.setName("bob");
190 array[1] = alien2;
191 GenericEntity<XmlJavaTypeAdapterAlien[]> entity = new GenericEntity<XmlJavaTypeAdapterAlien[]>(array) {
192 };
193 GenericType<XmlJavaTypeAdapterAlien[]> alienArrayType = new GenericType<XmlJavaTypeAdapterAlien[]>() {
194 };
195 XmlJavaTypeAdapterAlien[] response = target.request().post(Entity.entity(entity, MediaType.APPLICATION_XML_TYPE), alienArrayType);
196 logger.info("response: \"" + response + "\"");
197 Assert.assertEquals("The received response was not the expected one", 2, response.length);
198 Assert.assertTrue("The received response was not the expected one",
199 (alien1.equals(response[0]) && alien2.equals(response[1])) || (alien1.equals(response[1]) && alien2.equals(response[0])));
200 Assert.assertEquals("The marshalling of the Alien didn't happen the correct way",
201 4, XmlJavaTypeAdapterAlienAdapter.marshalCounter);
202 Assert.assertEquals("The unmarshalling of the Human didn't happen the correct way",
203 4, XmlJavaTypeAdapterAlienAdapter.unmarshalCounter);
204 XmlJavaTypeAdapterAlienAdapter.unmarshalCounter = 0;
205 XmlJavaTypeAdapterAlienAdapter.marshalCounter = 0;
206 }
207
208 /**
209 * @tpTestDetails Tests jaxb with class annotated by @XmlJavaTypeAdapter, resource returning map of Alien objects,
210 * where application expects the use of Human class with jaxb annotation, XmlJavaTypeAdapter is used to convert Alien
211 * to Human and back
212 * @tpInfo RESTEASY-1088
213 * @tpSince RESTEasy 3.0.16
214 */
215 @Test
216 public void testPostAlienMap() {
217 ResteasyWebTarget target = client.target(generateURL("/map/alien"));
218 Map<String, XmlJavaTypeAdapterAlien> map = new HashMap<String, XmlJavaTypeAdapterAlien>();
219 XmlJavaTypeAdapterAlien alien1 = new XmlJavaTypeAdapterAlien();
220 alien1.setName("bill");
221 map.put("abc", alien1);
222 XmlJavaTypeAdapterAlien alien2 = new XmlJavaTypeAdapterAlien();
223 alien2.setName("bob");
224 map.put("xyz", alien2);
225 GenericEntity<Map<String, XmlJavaTypeAdapterAlien>> entity = new GenericEntity<Map<String, XmlJavaTypeAdapterAlien>>(map) {
226 };
227 GenericType<Map<String, XmlJavaTypeAdapterAlien>> alienMapType = new GenericType<Map<String, XmlJavaTypeAdapterAlien>>() {
228 };
229 Map<String, XmlJavaTypeAdapterAlien> response = target.request().post(Entity.entity(entity, MediaType.APPLICATION_XML_TYPE), alienMapType);
230 logger.info("response: \"" + response + "\"");
231 Assert.assertEquals("The received response was not the expected one", 2, response.size());
232 Assert.assertTrue("The received response was not the expected one", alien1.equals(response.get("abc")));
233 Assert.assertTrue("The received response was not the expected one", alien2.equals(response.get("xyz")));
234 Assert.assertEquals("The marshalling of the Alien didn't happen the correct way",
235 4, XmlJavaTypeAdapterAlienAdapter.marshalCounter);
236 Assert.assertEquals("The unmarshalling of the Human didn't happen the correct way",
237 4, XmlJavaTypeAdapterAlienAdapter.unmarshalCounter);
238 XmlJavaTypeAdapterAlienAdapter.unmarshalCounter = 0;
239 XmlJavaTypeAdapterAlienAdapter.marshalCounter = 0;
240 }
241
242 /**
243 * @tpTestDetails Tests jaxb with class annotated by @XmlJavaTypeAdapter, resource returning list of Alien objects,
244 * where application expects the use of Human class with jaxb annotation, XmlJavaTypeAdapter is used to convert Alien
245 * to Human and back. The Entity send to the server extends Alien class.
246 * @tpInfo RESTEASY-1088
247 * @tpSince RESTEasy 3.0.16
248 */
249 @Test
250 public void testPostTralfamadoreanList() {
251 ResteasyWebTarget target = client.target(generateURL("/list/alien"));
252 List<XmlJavaTypeAdapterAlien> list = new ArrayList<XmlJavaTypeAdapterAlien>();
253 Tralfamadorean tralfamadorean1 = new Tralfamadorean();
254 tralfamadorean1.setName("bill");
255 list.add(tralfamadorean1);
256 Tralfamadorean tralfamadorean2 = new Tralfamadorean();
257 tralfamadorean2.setName("bob");
258 list.add(tralfamadorean2);
259 GenericEntity<List<XmlJavaTypeAdapterAlien>> entity = new GenericEntity<List<XmlJavaTypeAdapterAlien>>(list) {
260 };
261 GenericType<List<XmlJavaTypeAdapterAlien>> alienListType = new GenericType<List<XmlJavaTypeAdapterAlien>>() {
262 };
263 List<XmlJavaTypeAdapterAlien> response = target.request().post(Entity.entity(entity, MediaType.APPLICATION_XML_TYPE), alienListType);
264 logger.info("response: \"" + response + "\"");
265 Assert.assertEquals("The received response was not the expected one", 2, response.size());
266 Assert.assertTrue("The received response was not the expected one", response.contains(tralfamadorean1));
267 Assert.assertTrue("The received response was not the expected one", response.contains(tralfamadorean2));
268 Assert.assertEquals("The marshalling of the Alien didn't happen the correct way",
269 4, XmlJavaTypeAdapterAlienAdapter.marshalCounter);
270 Assert.assertEquals("The unmarshalling of the Human didn't happen the correct way",
271 4, XmlJavaTypeAdapterAlienAdapter.unmarshalCounter);
272 XmlJavaTypeAdapterAlienAdapter.unmarshalCounter = 0;
273 XmlJavaTypeAdapterAlienAdapter.marshalCounter = 0;
274 }
275 }
+0
-149
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/XmlJaxbProvidersTest.java less more
0 package org.jboss.resteasy.test.providers.jaxb;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.providers.jaxb.resource.Order;
9 import org.jboss.resteasy.test.providers.jaxb.resource.Ordertype;
10 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJaxbProvidersOrderClient;
11 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJaxbProvidersOrderResource;
12 import org.jboss.resteasy.test.providers.jaxb.resource.ShipTo;
13 import org.jboss.resteasy.test.providers.jaxb.resource.Shiptotype;
14 import org.jboss.resteasy.test.providers.jaxb.resource.Item;
15 import org.jboss.resteasy.test.providers.jaxb.resource.Itemtype;
16 import org.jboss.resteasy.test.providers.jaxb.resource.JAXBCache;
17 import org.jboss.resteasy.test.providers.jaxb.resource.XmlJaxbProvidersHelper;
18 import org.jboss.resteasy.test.providers.jaxb.resource.XmlStreamFactory;
19 import org.jboss.resteasy.util.HttpResponseCodes;
20 import org.jboss.resteasy.utils.PortProviderUtil;
21 import org.jboss.resteasy.utils.TestUtil;
22 import org.jboss.shrinkwrap.api.Archive;
23 import org.jboss.shrinkwrap.api.exporter.ZipExporter;
24 import org.jboss.shrinkwrap.api.spec.WebArchive;
25 import org.junit.After;
26 import org.junit.Assert;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30
31 import javax.ws.rs.core.Response;
32 import javax.xml.bind.JAXBContext;
33 import javax.xml.bind.Unmarshaller;
34 import java.io.File;
35 import java.io.InputStream;
36
37 /**
38 * @tpSubChapter Jaxb provider
39 * @tpChapter Integration tests
40 * @tpSince RESTEasy 3.0.16
41 */
42 @RunWith(Arquillian.class)
43 @RunAsClient
44 public class XmlJaxbProvidersTest {
45
46 private XmlJaxbProvidersOrderClient proxy;
47 static ResteasyClient client;
48
49 private static final String ERR_NULL_ENTITY = "The entity returned from the server was null";
50 private static final String ERR_CONTENT = "Unexpected content of the Order";
51
52 @Deployment
53 public static Archive<?> deploy() {
54 WebArchive war = TestUtil.prepareArchive(XmlJaxbProvidersTest.class.getSimpleName());
55 war.addClass(XmlJaxbProvidersTest.class);
56 war.addAsResource(XmlJaxbProvidersTest.class.getPackage(), "orders/order_123.xml");
57 war.as(ZipExporter.class).exportTo(new File("target", XmlJaxbProvidersTest.class.getSimpleName() + ".war"), true);
58 return TestUtil.finishContainerPrepare(war, null, XmlJaxbProvidersOrderResource.class, Order.class, Ordertype.class,
59 ShipTo.class, Shiptotype.class, Item.class, Itemtype.class, JAXBCache.class, XmlJaxbProvidersHelper.class, XmlStreamFactory.class);
60 }
61
62 @Before
63 public void init() {
64 client = new ResteasyClientBuilder().build();
65 proxy = ProxyBuilder.builder(XmlJaxbProvidersOrderClient.class, client.target(generateURL("/"))).build();
66 }
67
68 @After
69 public void after() throws Exception {
70 client.close();
71 }
72
73 private String generateURL(String path) {
74 return PortProviderUtil.generateURL(path, XmlJaxbProvidersTest.class.getSimpleName());
75 }
76
77 /**
78 * @tpTestDetails Test jaxb unmarshaller to correctly unmarshall InputStream
79 * @tpSince RESTEasy 3.0.16
80 */
81 @Test
82 public void testUnmarshalOrder() throws Exception {
83 InputStream in = XmlJaxbProvidersTest.class.getResourceAsStream("orders/order_123.xml");
84 Order order = XmlJaxbProvidersHelper.unmarshall(Order.class, in).getValue();
85
86 Assert.assertNotNull(ERR_NULL_ENTITY, order);
87 Assert.assertEquals(ERR_CONTENT, "Ryan J. McDonough", order.getPerson());
88 }
89
90 /**
91 * @tpTestDetails An xml file is loaded on the server and jaxb converts the xml entity Order from xml file into an
92 * object
93 * @tpSince RESTEasy 3.0.16
94 */
95 @Test
96 public void testGetOrder() {
97 Order order = proxy.getOrderById("order_123");
98 Assert.assertEquals(ERR_CONTENT, "Ryan J. McDonough", order.getPerson());
99 }
100
101 /**
102 * @tpTestDetails Clients sends request with order if and set xml headerr. An xml file is loaded on the server
103 * and jaxb converts the xml entity Order from xml file into an object.
104 * @tpSince RESTEasy 3.0.16
105 */
106 @Test
107 public void testGetOrderAndUnmarshal() throws Exception {
108 Response response = client.target(generateURL("/jaxb/orders") + "/order_123").request()
109 .header(XmlJaxbProvidersHelper.FORMAT_XML_HEADER, "true").get();
110 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
111 JAXBContext jaxb = JAXBContext.newInstance(Order.class);
112 Unmarshaller u = jaxb.createUnmarshaller();
113 Order order = (Order) u.unmarshal(response.readEntity(InputStream.class));
114 Assert.assertNotNull(ERR_NULL_ENTITY, order);
115 Assert.assertEquals(ERR_CONTENT, "Ryan J. McDonough", order.getPerson());
116 response.close();
117 }
118
119 /**
120 * @tpTestDetails Same as testGetOrderWithParams() except that it uses the client framework to implicitly unmarshal
121 * the returned order and it tests its value, instead of just printing it out.
122 * @tpSince RESTEasy 3.0.16
123 */
124 @Test
125 public void testGetOrderWithParamsToOrder() throws Exception {
126 Response response = client.target(generateURL("/jaxb/orders") + "/order_123").request()
127 .header(XmlJaxbProvidersHelper.FORMAT_XML_HEADER, "true").get();
128 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
129 Order order = response.readEntity(Order.class);
130 Assert.assertEquals(ERR_CONTENT, "Ryan J. McDonough", order.getPerson());
131 }
132
133 /**
134 * @tpTestDetails Updates the specified order and returns updated object
135 * @tpSince RESTEasy 3.0.16
136 */
137 @Test
138 public void testUpdateOrder() {
139 InputStream in = XmlJaxbProvidersTest.class.getResourceAsStream("orders/order_123.xml");
140 Order order = XmlJaxbProvidersHelper.unmarshall(Order.class, in).getValue();
141 int initialItemCount = order.getItems().size();
142 order = proxy.updateOrder(order, "order_123");
143 Assert.assertEquals(ERR_CONTENT, "Ryan J. McDonough", order.getPerson());
144 Assert.assertNotSame("The number of items in the Order didn't change after update",
145 initialItemCount, order.getItems().size());
146 Assert.assertEquals("The number of items in the Order doesn't match", 3, order.getItems().size());
147 }
148 }
+0
-47
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/link/Customer.java less more
0 package org.jboss.resteasy.test.providers.jaxb.link;
1
2 import javax.ws.rs.core.Link;
3 import javax.xml.bind.annotation.XmlAccessType;
4 import javax.xml.bind.annotation.XmlAccessorType;
5 import javax.xml.bind.annotation.XmlElement;
6 import javax.xml.bind.annotation.XmlRootElement;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 /**
11 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12 * @version $Revision: 1 $
13 */
14 @XmlRootElement(name = "customer")
15 @XmlAccessorType(XmlAccessType.PROPERTY)
16 public class Customer
17 {
18 private String name;
19 private List<Link> links = new ArrayList<Link>();
20
21 public Customer()
22 {
23 }
24
25 public Customer(String name)
26 {
27 this.name = name;
28 }
29
30 @XmlElement
31 public String getName()
32 {
33 return name;
34 }
35
36 public void setName(String name)
37 {
38 this.name = name;
39 }
40
41 @XmlElement(name = "link")
42 public List<Link> getLinks()
43 {
44 return links;
45 }
46 }
+0
-8
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/link/package-info.java less more
0 @XmlJavaTypeAdapters(
1 {
2 @XmlJavaTypeAdapter(type = Link.class, value = Link.JaxbAdapter.class)
3 }) package org.jboss.resteasy.test.providers.jaxb.link;
4
5 import javax.ws.rs.core.Link;
6 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
7 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
+0
-35
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/AbstractJaxbClassCompanyCustomer.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlRootElement;
5
6 @XmlRootElement
7 @XmlAccessorType(XmlAccessType.FIELD)
8 public class AbstractJaxbClassCompanyCustomer extends AbstractJaxbClassCustomer {
9 private static final long serialVersionUID = 3224665468219250145L;
10
11 private short rabatt;
12
13 public AbstractJaxbClassCompanyCustomer() {
14 super();
15 }
16
17 public short getRabatt() {
18 return rabatt;
19 }
20
21 public void setRabatt(short rabatt) {
22 this.rabatt = rabatt;
23 }
24
25 @Override
26 public String getArt() {
27 return "COMPANYCUSTOMER";
28 }
29
30 @Override
31 public String toString() {
32 return "{" + super.toString() + ", rabatt=" + rabatt + '}';
33 }
34 }
+0
-277
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/AbstractJaxbClassCustomer.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlElement;
6 import javax.xml.bind.annotation.XmlElementWrapper;
7 import javax.xml.bind.annotation.XmlRootElement;
8 import javax.xml.bind.annotation.XmlSeeAlso;
9 import javax.xml.bind.annotation.XmlTransient;
10 import java.text.DateFormat;
11 import java.text.ParseException;
12 import java.util.Date;
13 import java.util.GregorianCalendar;
14 import java.util.List;
15 import java.util.Locale;
16
17 import static java.util.Calendar.YEAR;
18
19 @XmlRootElement
20 @XmlSeeAlso({
21 AbstractJaxbClassCompanyCustomer.class,
22 AbstractJaxbClassPrivatCustomer.class
23 })
24 @XmlAccessorType(XmlAccessType.FIELD)
25 public abstract class AbstractJaxbClassCustomer implements java.io.Serializable {
26 private static final long serialVersionUID = 8488010636885492122L;
27
28 public static final int NACHNAME_LENGTH_MIN = 2;
29 public static final int NACHNAME_LENGTH_MAX = 32;
30 public static final int VORNAME_LENGTH_MAX = 32;
31 public static final int CUSTOMERNNR_LENGTH_MAX = 32;
32 public static final int DETAILS_LENGTH_MAX = 128 * 1024;
33 public static final int PASSWORD_LENGTH_MAX = 256;
34
35 public static final String PRIVATCUSTOMER = "P";
36 public static final String COMPANYCUSTOMER = "F";
37
38 static final String FIND_CUSTOMERS = "findcustomers";
39 static final String FIND_CUSTOMERS_BY_NACHNAME = "findCustomersByNachname";
40 static final String FIND_CUSTOMERS_BY_NACHNAME_FETCH_BESTELLUNGEN = "findCustomersByNachnameFetchBestellungen";
41 static final String FIND_CUSTOMER_BY_ID_FETCH_BESTELLUNGEN = "findCustomersByIdFetchBestellungen";
42 static final String FIND_CUSTOMERS_BY_PLZ = "findCustomersByPlz";
43
44 static final String PARAM_CUSTOMER_ID = "customerId";
45 static final String PARAM_CUSTOMER_NACHNAME = "nachname";
46 static final String PARAM_CUSTOMER_ADRESSE_PLZ = "plz";
47
48 // Alternativen: TABLE, SEQUENCE, IDENTITY, AUTO, NONE (=default)
49 @XmlAttribute(name = "id", required = true)
50 protected Long id = -1L;
51
52 @XmlTransient
53 protected int version = 0;
54
55 @XmlElement(required = true)
56 protected String nachname = "";
57
58 protected String vorname = "";
59
60 @XmlAttribute(required = true)
61 protected String customersnr = "NnVn-001";
62
63 protected Date seit = null;
64
65 @XmlTransient
66 protected int anzJahre;
67
68 @XmlElement(name = "betreuer")
69 protected String betreuerKey;
70
71 @XmlElementWrapper(name = "bestellungen")
72 @XmlElement(name = "bestellung")
73 protected List<String> bestellungenKeys;
74
75 protected String details;
76
77 @XmlTransient
78 protected String password = "";
79
80 @XmlTransient
81 protected Date erzeugt = null;
82
83 @XmlTransient
84 protected Date aktualisiert = null;
85
86 public AbstractJaxbClassCustomer() {
87 super();
88 }
89
90 public Long getId() {
91 return id;
92 }
93
94 public void setId(Long id) {
95 this.id = id;
96 }
97
98 public int getVersion() {
99 return version;
100 }
101
102 public void setVersion(int version) {
103 this.version = version;
104 }
105
106 public String getNachname() {
107 return nachname;
108 }
109
110 public void setNachname(String nachname) {
111 this.nachname = nachname;
112 }
113
114 public String getVorname() {
115 return vorname;
116 }
117
118 public void setVorname(String vorname) {
119 this.vorname = vorname;
120 }
121
122 public String getCustomersnr() {
123 return customersnr;
124 }
125
126 public void setCustomersnr(String customersnr) {
127 this.customersnr = customersnr;
128 }
129
130 public Date getSeit() {
131 return seit;
132 }
133
134 public void setSeit(Date seit) {
135 this.seit = seit;
136 }
137
138 public int getAnzJahre() {
139 final GregorianCalendar now = new GregorianCalendar();
140 final GregorianCalendar seitCal = new GregorianCalendar();
141 Date temp = seit;
142 if (temp == null) {
143 temp = new Date();
144 }
145 seitCal.setTime(temp);
146
147 anzJahre = now.get(YEAR) - seitCal.get(YEAR);
148
149 return anzJahre;
150 }
151
152 public String getSeitAsString(int style, Locale locale) {
153 Date temp = seit;
154 if (temp == null) {
155 temp = new Date();
156 }
157 final DateFormat f = DateFormat.getDateInstance(style, locale);
158 return f.format(temp);
159 }
160
161 public void setSeit(String seit, int style, Locale locale) {
162 final DateFormat f = DateFormat.getDateInstance(style, locale);
163 try {
164 this.seit = f.parse(seit);
165 } catch (ParseException e) {
166 }
167 }
168
169 public String getBetreuerKey() {
170 return betreuerKey;
171 }
172
173 public void setBetreuerKey(String betreuerKey) {
174 this.betreuerKey = betreuerKey;
175 }
176
177 public List<String> getBestellungenKeys() {
178 return bestellungenKeys;
179 }
180
181 public void setBestellungenKeys(List<String> bestellungenKeys) {
182 this.bestellungenKeys = bestellungenKeys;
183 }
184
185 public abstract String getArt();
186
187 public String getDetails() {
188 return details;
189 }
190
191 public void setDetails(String details) {
192 this.details = details;
193 }
194
195 public String getPassword() {
196 return password;
197 }
198
199 public void setPassword(String passwort) {
200 this.password = passwort;
201 }
202
203 public Date getAktualisiert() {
204 return aktualisiert;
205 }
206
207 public void setAktualisiert(Date aktualisiert) {
208 this.aktualisiert = aktualisiert;
209 }
210
211 public Date getErzeugt() {
212 return erzeugt;
213 }
214
215 public void setErzeugt(Date erzeugt) {
216 this.erzeugt = erzeugt;
217 }
218
219 @Override
220 public String toString() {
221 return "id=" + id + ", version=" + version +
222 ", nachname=" + nachname + ", vorname=" + vorname +
223 ", nr=" + customersnr +
224 ", seit=" + getSeitAsString(DateFormat.MEDIUM, Locale.GERMANY) +
225 ", anzJahre=" + getAnzJahre() +
226 ", password=" + password +
227 ", erzeugt=" + erzeugt +
228 ", aktualisiert=" + aktualisiert;
229 }
230
231 @Override
232 public int hashCode() {
233 final int PRIME = 31;
234 int result = 1;
235 result = PRIME * result + ((nachname == null) ? 0 : nachname.hashCode());
236 result = PRIME * result + ((seit == null) ? 0 : seit.hashCode());
237 result = PRIME * result + ((vorname == null) ? 0 : vorname.hashCode());
238 return result;
239 }
240
241 @Override
242 public boolean equals(Object obj) {
243 if (this == obj) {
244 return true;
245 }
246 if (obj == null) {
247 return false;
248 }
249 if (getClass() != obj.getClass()) {
250 return false;
251 }
252 final AbstractJaxbClassCustomer other = (AbstractJaxbClassCustomer) obj;
253 if (nachname == null) {
254 if (other.nachname != null) {
255 return false;
256 }
257 } else if (!nachname.equals(other.nachname)) {
258 return false;
259 }
260 if (seit == null) {
261 if (other.seit != null) {
262 return false;
263 }
264 } else if (!seit.equals(other.seit)) {
265 return false;
266 }
267 if (vorname == null) {
268 if (other.vorname != null) {
269 return false;
270 }
271 } else if (!vorname.equals(other.vorname)) {
272 return false;
273 }
274 return true;
275 }
276 }
+0
-41
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/AbstractJaxbClassPerson.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlElement;
6 import javax.xml.bind.annotation.XmlRootElement;
7
8 @XmlRootElement
9 @XmlAccessorType(XmlAccessType.FIELD)
10 public class AbstractJaxbClassPerson {
11 @XmlAttribute(name = "id", required = true)
12 protected String id;
13
14 @XmlElement
15 protected String name;
16
17 public AbstractJaxbClassPerson(final String id, final String name) {
18 this.id = id;
19 this.name = name;
20 }
21
22 public AbstractJaxbClassPerson() {
23 }
24
25 public String getId() {
26 return id;
27 }
28
29 public void setId(String id) {
30 this.id = id;
31 }
32
33 public String getName() {
34 return name;
35 }
36
37 public void setName(String name) {
38 this.name = name;
39 }
40 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/AbstractJaxbClassPrivatCustomer.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlRootElement;
5
6 @XmlRootElement
7 @XmlAccessorType(XmlAccessType.FIELD)
8 public final class AbstractJaxbClassPrivatCustomer extends AbstractJaxbClassCustomer {
9 private static final long serialVersionUID = 133152931415808605L;
10
11 @Override
12 public String getArt() {
13 return "PRIVATCUSTOMER";
14 }
15
16 @Override
17 public String toString() {
18 return "{" + super.toString() + ", familienstand=nada'}'";
19 }
20 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/AbstractJaxbClassResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6
7 @Path("/")
8 public class AbstractJaxbClassResource {
9
10 private static Logger logger = Logger.getLogger(AbstractJaxbClassResource.class.getName());
11
12 @POST
13 public void post(AbstractJaxbClassPerson person) {
14 logger.info(person.getName() + " " + person.getId());
15 }
16
17 @POST
18 @Path("customer")
19 public void postKunde(AbstractJaxbClassCustomer customer) {
20 logger.info(customer.getNachname());
21 }
22
23 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/BadContenTypeTestResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.Response;
7
8 @Path("/test")
9 public class BadContenTypeTestResource {
10
11 @GET
12 public Response get() {
13 BadContentTypeTestBean bean = new BadContentTypeTestBean();
14 bean.setName("myname");
15 return Response.ok(bean).build();
16 }
17
18 @GET
19 @Produces("text/html")
20 @Path("foo")
21 public Response getMissingMBW() {
22 BadContentTypeTestBean bean = new BadContentTypeTestBean();
23 bean.setName("myname");
24 return Response.ok(bean).build();
25 }
26
27 @POST
28 public void post(BadContentTypeTestBean bean) {
29
30 }
31
32 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/BadContentTypeTestBean.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class BadContentTypeTestBean {
6 private String name;
7
8 public String getName() {
9 return name;
10 }
11
12 public void setName(String name) {
13 this.name = name;
14 }
15
16 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CharSetCustomer.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "customer")
8 @XmlAccessorType(XmlAccessType.PROPERTY)
9 public class CharSetCustomer {
10 private String name;
11
12 @XmlElement
13 public String getName() {
14 return name;
15 }
16
17 public void setName(String name) {
18 this.name = name;
19 }
20 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CharSetFavoriteMovieXmlRootElement.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class CharSetFavoriteMovieXmlRootElement {
6 private String _title;
7 public String getTitle() {
8 return _title;
9 }
10 public void setTitle(String title) {
11 _title = title;
12 }
13 }
+0
-54
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CharSetMovieResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.GET;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 import java.nio.charset.Charset;
11
12 import static org.jboss.resteasy.test.providers.jaxb.CharSetRE1066Test.APPLICATION_XML_UTF16;
13
14 @Path("/")
15 public class CharSetMovieResource {
16
17 private final Logger log = Logger.getLogger(CharSetMovieResource.class.getName());
18
19 @GET
20 @Path("junk")
21 public String junk() {
22 return "junk";
23 }
24
25 @POST
26 @Path("xml/produces")
27 @Consumes("application/xml")
28 @Produces(APPLICATION_XML_UTF16)
29 public CharSetFavoriteMovieXmlRootElement xmlProduces(CharSetFavoriteMovieXmlRootElement movie) {
30 log.info("server default charset: " + Charset.defaultCharset());
31 log.info("title: " + movie.getTitle());
32 return movie;
33 }
34
35 @POST
36 @Path("xml/accepts")
37 @Consumes("application/xml")
38 public CharSetFavoriteMovieXmlRootElement xmlAccepts(CharSetFavoriteMovieXmlRootElement movie) {
39 log.info("server default charset: " + Charset.defaultCharset());
40 log.info("title: " + movie.getTitle());
41 return movie;
42 }
43
44 @POST
45 @Path("xml/default")
46 @Consumes("application/xml")
47 @Produces("application/xml")
48 public CharSetFavoriteMovieXmlRootElement xmlDefault(CharSetFavoriteMovieXmlRootElement movie) {
49 log.info("server default charset: " + Charset.defaultCharset());
50 log.info("title: " + movie.getTitle());
51 return movie;
52 }
53 }
+0
-54
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CharSetRE1066Resource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.GET;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 import static org.jboss.resteasy.test.providers.jaxb.CharSetRE1066Test.APPLICATION_XML_UTF16;
11
12 @Path("/")
13 public class CharSetRE1066Resource
14 {
15
16 private final Logger log = Logger.getLogger(CharSetRE1066Resource.class.getName());
17
18 @GET
19 @Path("junk")
20 public String junk()
21 {
22 return "junk";
23 }
24
25 @POST
26 @Path("xml/produces")
27 @Consumes("application/xml")
28 @Produces(APPLICATION_XML_UTF16)
29 public CharSetFavoriteMovieXmlRootElement xmlProduces(CharSetFavoriteMovieXmlRootElement movie)
30 {
31 log.info("title: " + movie.getTitle());
32 return movie;
33 }
34
35 @POST
36 @Path("xml/accepts")
37 @Consumes("application/xml")
38 public CharSetFavoriteMovieXmlRootElement xmlAccepts(CharSetFavoriteMovieXmlRootElement movie)
39 {
40 log.info("title: " + movie.getTitle());
41 return movie;
42 }
43
44 @POST
45 @Path("xml/default")
46 @Consumes("application/xml")
47 @Produces("application/xml")
48 public CharSetFavoriteMovieXmlRootElement xmlDefault(CharSetFavoriteMovieXmlRootElement movie)
49 {
50 log.info("title: " + movie.getTitle());
51 return movie;
52 }
53 }
+0
-45
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CharSetResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.logging.Logger;
3 import org.junit.Assert;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.core.Response;
9 import java.io.UnsupportedEncodingException;
10
11 @Path("/test")
12 public class CharSetResource {
13
14 private static Logger logger = Logger.getLogger(CharSetResource.class.getName());
15
16 @POST
17 @Consumes("application/xml")
18 public Response post(CharSetCustomer cust) {
19 logger.info(cust.getName());
20 String name = "bill\u00E9";
21 boolean equal = false;
22 try {
23 String test = new String(name.getBytes("UTF-8"), "UTF-8");
24 if (test.compareTo(cust.getName()) == 0) {
25 equal = true;
26 }
27 } catch (UnsupportedEncodingException e) {
28 Assert.fail("Not supported encoding.");
29 }
30 return equal ? Response.ok().build() : Response.serverError().build();
31 }
32
33 @POST
34 @Path("string")
35 public Response postString(String cust) {
36 logger.info(cust);
37 boolean equal = false;
38 String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><customer><name>billé</name></customer>";
39 if (expected.compareTo(cust) == 0) {
40 equal = true;
41 }
42 return equal ? Response.ok().build() : Response.serverError().build();
43 }
44 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CharacterSetData.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement(name = "test-data")
5 public class CharacterSetData {
6 private String text = "Text \u0100.";
7
8 public String getText() {
9 return text;
10 }
11
12 public void setText(String value) {
13 text = value;
14 }
15 }
+0
-34
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CharacterSetResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Response;
6 import javax.ws.rs.core.Context;
7 import javax.ws.rs.core.Request;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Variant;
10 import java.util.List;
11
12 @Path("/")
13 public class CharacterSetResource {
14
15 private final String[] characterSets = {"US-ASCII", "UTF-8", "ISO-8859-1"};
16
17 @GET
18 @Path("variant-selection")
19 @Produces("application/xml")
20 public Response getVariantSelection(@Context Request request) {
21 int i = characterSets.length;
22 MediaType[] mediaTypes = new MediaType[i];
23 while (--i >= 0) {
24 mediaTypes[i] = MediaType.valueOf("application/xml;charset=" + characterSets[i]);
25 }
26 List<Variant> variants = Variant.mediaTypes(mediaTypes).build();
27 Variant variant = request.selectVariant(variants);
28 if (variant == null) {
29 return Response.notAcceptable(variants).build();
30 }
31 return Response.ok(new CharacterSetData(), variant).build();
32 }
33 }
+0
-78
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/Child.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.Unmarshaller;
3 import javax.xml.bind.annotation.XmlAccessType;
4 import javax.xml.bind.annotation.XmlAccessorType;
5 import javax.xml.bind.annotation.XmlRootElement;
6 import javax.xml.bind.annotation.XmlTransient;
7 import javax.xml.bind.annotation.XmlType;
8
9 /**
10 * A Child.
11 *
12 * @author <a href="ryan@damnhandy.com">Ryan J. McDonough</a>
13 * @version $Revision:$
14 */
15 @XmlRootElement
16 @XmlAccessorType(XmlAccessType.FIELD)
17 @XmlType(name = "childType")
18 public class Child {
19 private String name;
20
21 @XmlTransient
22 private Parent parent;
23
24 public Child() {
25
26 }
27
28 public Child(final String name) {
29 this.name = name;
30 }
31
32 /**
33 * Get the name.
34 *
35 * @return the name.
36 */
37 public String getName() {
38 return name;
39 }
40
41 /**
42 * Set the name.
43 *
44 * @param name The name to set.
45 */
46 public void setName(String name) {
47 this.name = name;
48 }
49
50 /**
51 * Get the parent.
52 *
53 * @return the parent.
54 */
55 public Parent getParent() {
56 return parent;
57 }
58
59 /**
60 * Set the parent.
61 *
62 * @param parent The parent to set.
63 */
64 public void setParent(Parent parent) {
65 this.parent = parent;
66 }
67
68 /**
69 * FIXME Comment this
70 *
71 * @param unmarshaller
72 * @param parent
73 */
74 public void afterUnmarshal(Unmarshaller unmarshaller, Object object) {
75 this.parent = (Parent) object;
76 }
77 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CollectionCustomer.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "customer")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class CollectionCustomer {
10 @XmlElement
11 private String name;
12
13 public CollectionCustomer() {
14 }
15
16 public CollectionCustomer(final String name) {
17 this.name = name;
18 }
19
20 public String getName() {
21 return name;
22 }
23 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CollectionNamespacedCustomer.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "customer", namespace = "http://customer.com")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class CollectionNamespacedCustomer {
10 @XmlElement
11 private String name;
12
13 public CollectionNamespacedCustomer() {
14 }
15
16 public CollectionNamespacedCustomer(final String name) {
17 this.name = name;
18 }
19
20 public String getName() {
21 return name;
22 }
23 }
+0
-81
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CollectionNamespacedResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.Wrapped;
3 import org.junit.Assert;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.PUT;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.core.GenericEntity;
11 import javax.ws.rs.core.Response;
12 import java.util.ArrayList;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Set;
16
17 @Path("/namespaced")
18 public class CollectionNamespacedResource {
19 @GET
20 @Path("array")
21 @Produces("application/xml")
22 @Wrapped
23 public CollectionNamespacedCustomer[] getCustomers() {
24 CollectionNamespacedCustomer[] custs = {new CollectionNamespacedCustomer("bill"), new CollectionNamespacedCustomer("monica")};
25 return custs;
26 }
27
28 @PUT
29 @Path("array")
30 @Consumes("application/xml")
31 public void putCustomers(@Wrapped CollectionNamespacedCustomer[] customers) {
32 Assert.assertEquals("bill", customers[0].getName());
33 Assert.assertEquals("monica", customers[1].getName());
34 }
35
36 @GET
37 @Path("set")
38 @Produces("application/xml")
39 @Wrapped
40 public Set<CollectionNamespacedCustomer> getCustomerSet() {
41 HashSet<CollectionNamespacedCustomer> set = new HashSet<CollectionNamespacedCustomer>();
42 set.add(new CollectionNamespacedCustomer("bill"));
43 set.add(new CollectionNamespacedCustomer("monica"));
44
45 return set;
46 }
47
48 @PUT
49 @Path("list")
50 @Consumes("application/xml")
51 public void putCustomers(@Wrapped List<CollectionNamespacedCustomer> customers) {
52 Assert.assertEquals("bill", customers.get(0).getName());
53 Assert.assertEquals("monica", customers.get(1).getName());
54 }
55
56 @GET
57 @Path("list")
58 @Produces("application/xml")
59 @Wrapped
60 public List<CollectionNamespacedCustomer> getCustomerList() {
61 ArrayList<CollectionNamespacedCustomer> set = new ArrayList<CollectionNamespacedCustomer>();
62 set.add(new CollectionNamespacedCustomer("bill"));
63 set.add(new CollectionNamespacedCustomer("monica"));
64
65 return set;
66 }
67
68 @GET
69 @Path("list/response")
70 @Produces("application/xml")
71 @Wrapped
72 public Response getCustomerListResponse() {
73 ArrayList<CollectionNamespacedCustomer> set = new ArrayList<CollectionNamespacedCustomer>();
74 set.add(new CollectionNamespacedCustomer("bill"));
75 set.add(new CollectionNamespacedCustomer("monica"));
76 GenericEntity<List<CollectionNamespacedCustomer>> genericEntity = new GenericEntity<List<CollectionNamespacedCustomer>>(set) {
77 };
78 return Response.ok(genericEntity).build();
79 }
80 }
+0
-82
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CollectionResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.Wrapped;
3 import org.junit.Assert;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.PUT;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.core.GenericEntity;
11 import javax.ws.rs.core.Response;
12 import java.util.ArrayList;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Set;
16
17 @Path("/")
18 public class CollectionResource {
19 private static final String WRONG_REQUEST_ERROR_MSG = "Request contains wrong data";
20 @GET
21 @Path("array")
22 @Produces("application/xml")
23 @Wrapped
24 public CollectionCustomer[] getCustomers() {
25 CollectionCustomer[] custs = {new CollectionCustomer("bill"), new CollectionCustomer("monica")};
26 return custs;
27 }
28
29 @PUT
30 @Path("array")
31 @Consumes("application/xml")
32 public void putCustomers(@Wrapped CollectionCustomer[] customers) {
33 Assert.assertEquals(WRONG_REQUEST_ERROR_MSG, "bill", customers[0].getName());
34 Assert.assertEquals(WRONG_REQUEST_ERROR_MSG, "monica", customers[1].getName());
35 }
36
37 @GET
38 @Path("set")
39 @Produces("application/xml")
40 @Wrapped
41 public Set<CollectionCustomer> getCustomerSet() {
42 HashSet<CollectionCustomer> set = new HashSet<CollectionCustomer>();
43 set.add(new CollectionCustomer("bill"));
44 set.add(new CollectionCustomer("monica"));
45
46 return set;
47 }
48
49 @PUT
50 @Path("list")
51 @Consumes("application/xml")
52 public void putCustomers(@Wrapped List<CollectionCustomer> customers) {
53 Assert.assertEquals(WRONG_REQUEST_ERROR_MSG, "bill", customers.get(0).getName());
54 Assert.assertEquals(WRONG_REQUEST_ERROR_MSG, "monica", customers.get(1).getName());
55 }
56
57 @GET
58 @Path("list")
59 @Produces("application/xml")
60 @Wrapped
61 public List<CollectionCustomer> getCustomerList() {
62 ArrayList<CollectionCustomer> set = new ArrayList<CollectionCustomer>();
63 set.add(new CollectionCustomer("bill"));
64 set.add(new CollectionCustomer("monica"));
65
66 return set;
67 }
68
69 @GET
70 @Path("list/response")
71 @Produces("application/xml")
72 @Wrapped
73 public Response getCustomerListResponse() {
74 ArrayList<CollectionCustomer> set = new ArrayList<CollectionCustomer>();
75 set.add(new CollectionCustomer("bill"));
76 set.add(new CollectionCustomer("monica"));
77 GenericEntity<List<CollectionCustomer>> genericEntity = new GenericEntity<List<CollectionCustomer>>(set) {
78 };
79 return Response.ok(genericEntity).build();
80 }
81 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CustomOverrideFoo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class CustomOverrideFoo {
6 private String name;
7
8 public String getName() {
9 return name;
10 }
11
12 public void setName(String name) {
13 this.name = name;
14 }
15 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CustomOverrideResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Response;
6
7 @Path("/test")
8 @Produces("application/xml")
9 public class CustomOverrideResource {
10 @GET
11 public Response getFooXml() {
12 CustomOverrideFoo foo = new CustomOverrideFoo();
13 foo.setName("bill");
14 return Response.ok(foo).build();
15 }
16
17 @GET
18 @Produces("text/x-vcard")
19 public Response getFooVcard() {
20 CustomOverrideFoo foo = new CustomOverrideFoo();
21 foo.setName("bill");
22 return Response.ok(foo).build();
23 }
24 }
+0
-32
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/CustomOverrideWriter.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Produces;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import javax.ws.rs.ext.Provider;
8 import java.io.IOException;
9 import java.io.OutputStream;
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.Type;
12
13 @Provider
14 @Produces("text/x-vcard")
15 public class CustomOverrideWriter implements MessageBodyWriter<CustomOverrideFoo> {
16 @Override
17 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
18 return true;
19 }
20
21 @Override
22 public long getSize(CustomOverrideFoo foo, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
23 return -1;
24 }
25
26 @Override
27 public void writeTo(CustomOverrideFoo foo, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
28 String msg = "---" + foo.getName() + "---";
29 entityStream.write(msg.getBytes());
30 }
31 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/EmptyContentTypeFoo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class EmptyContentTypeFoo {
6 private String name;
7
8 public String getName() {
9 return name;
10 }
11
12 public void setName(String name) {
13 this.name = name;
14 }
15
16 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/EmptyContentTypeResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.HeaderParam;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Response;
10
11 @Path("/test")
12 public class EmptyContentTypeResource {
13 @POST
14 public Response postNada(@HeaderParam("Content-Type") String contentType) {
15 Assert.assertEquals(null, contentType);
16 return Response.ok("NULL", "text/plain").build();
17 }
18
19 @POST
20 @Consumes(MediaType.APPLICATION_XML)
21 public Response post(EmptyContentTypeFoo foo) {
22 return Response.ok(foo.getName(), "text/plain").build();
23 }
24 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/ExceptionMapperJaxbMapper.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.plugins.providers.jaxb.JAXBUnmarshalException;
3
4 import javax.ws.rs.core.Response;
5 import javax.ws.rs.ext.ExceptionMapper;
6 import javax.ws.rs.ext.Provider;
7
8 @Provider
9 public class ExceptionMapperJaxbMapper implements ExceptionMapper<JAXBUnmarshalException> {
10 @Override
11 public Response toResponse(JAXBUnmarshalException exception) {
12 return Response.status(400).type("text/plain").entity(exception.getMessage()).build();
13 }
14 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/ExceptionMapperJaxbResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5
6 @Path("/test")
7 public class ExceptionMapperJaxbResource {
8 @POST
9 @Consumes("application/xml")
10 public void post(AbstractJaxbClassPerson person) {
11 }
12 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericResourceAbstractResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.Response;
6
7 public class GenericResourceAbstractResource<T> {
8
9 @POST
10 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
11 public Response createEntity(T entity) {
12 return Response.ok("Success!").build();
13 }
14
15 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericResourceModel.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class GenericResourceModel {
6 private String _s;
7
8 public String getS() {
9 return _s;
10 }
11
12 public void setS(String s) {
13 _s = s;
14 }
15 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericResourceOtherAbstractResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2
3 public class GenericResourceOtherAbstractResource<T> extends GenericResourceAbstractResource<T> {
4 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericResourceResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ejb.Stateless;
3 import javax.ws.rs.Path;
4
5 @Stateless
6 @Path("/test")
7 public class GenericResourceResource extends GenericResourceOtherAbstractResource<GenericResourceModel> {
8
9 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericResourceResource2.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ejb.Stateless;
3 import javax.ws.rs.Path;
4
5 @Path("test2")
6 @Stateless
7 public class GenericResourceResource2 extends GenericResourceAbstractResource<GenericResourceModel> {
8
9 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceAbstractBackendCollectionResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public abstract class GenericSuperInterfaceAbstractBackendCollectionResource<R extends GenericSuperInterfaceBaseResource, Q /* extends GenericSuperInterfaceIVdcQueryable */>
3 extends GenericSuperInterfaceAbstractBackendResource<R, Q> {
4 }
+0
-6
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceAbstractBackendResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceAbstractBackendResource<R extends GenericSuperInterfaceBaseResource, Q /* extends GenericSuperInterfaceIVdcQueryable */>
3 extends GenericSuperInterfaceBackendResource {
4
5 }
+0
-6
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceAbstractBackendSubResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceAbstractBackendSubResource<R extends GenericSuperInterfaceBaseResource, Q /* extends GenericSuperInterfaceIVdcQueryable */> extends
3 GenericSuperInterfaceAbstractBackendResource<R, Q> {
4
5 }
+0
-6
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceAction.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceAction
3 extends GenericSuperInterfaceBaseResources {
4
5 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceAssignedPermissionsResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.GET;
3
4 public class GenericSuperInterfaceAssignedPermissionsResource {
5 @GET
6 String hello() {
7 return "hello";
8 }
9 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceBackendDataCenterResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceBackendDataCenterResource
3 extends GenericSuperInterfaceAbstractBackendSubResource<GenericSuperInterfaceDataCenter, GenericSuperInterfaceStoragePool>
4 implements GenericSuperInterfaceDataCenterResource {
5 public GenericSuperInterfaceBackendDataCenterResource(final String id,
6 final GenericSuperInterfaceBackendDataCentersResource backendDataCentersResource) {
7
8 }
9
10 @Override
11 public GenericSuperInterfaceAssignedPermissionsResource getPermissionsResource() {
12 return null;
13 }
14
15 @Override
16 public GenericSuperInterfaceDataCenter get() {
17 GenericSuperInterfaceDataCenter dc = new GenericSuperInterfaceDataCenter();
18 dc.setName("Bill");
19 return dc;
20 }
21
22 @Override
23 public GenericSuperInterfaceDataCenter update(GenericSuperInterfaceDataCenter resource) {
24 return resource;
25 }
26
27 }
+0
-32
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceBackendDataCentersResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.core.Response;
3
4 public class GenericSuperInterfaceBackendDataCentersResource extends
5 GenericSuperInterfaceAbstractBackendCollectionResource<GenericSuperInterfaceDataCenter, GenericSuperInterfaceStoragePool> implements GenericSuperInterfaceDataCentersResource {
6
7 @Override
8 public GenericSuperInterfaceDataCenters list() {
9 return null;
10 }
11
12 @Override
13 public Response add(GenericSuperInterfaceDataCenter dataCenter) {
14 return null;
15 }
16
17 @Override
18 public Response remove(String id, GenericSuperInterfaceAction action) {
19 return null;
20 }
21
22 @Override
23 public GenericSuperInterfaceDataCenterResource getDataCenterSubResource(String id) {
24 return new GenericSuperInterfaceBackendDataCenterResource(id, this);
25 }
26
27 @Override
28 public Response remove(String id) {
29 return null;
30 }
31 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceBackendResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceBackendResource extends GenericSuperInterfaceBaseBackendResource {
3
4 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceBaseBackendResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceBaseBackendResource {
3
4 }
+0
-52
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceBaseResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceBaseResource {
3
4 protected String name;
5 protected String description;
6 protected String id;
7
8 /**
9 * Gets the value of the name property.
10 *
11 * @return possible object is {@link String }
12 */
13 public String getName() {
14 return name;
15 }
16
17 /**
18 * Sets the value of the name property.
19 *
20 * @param value allowed object is {@link String }
21 */
22 public void setName(String value) {
23 this.name = value;
24 }
25
26 public boolean isSetName() {
27 return (this.name != null);
28 }
29
30 /**
31 * Gets the value of the description property.
32 *
33 * @return possible object is {@link String }
34 */
35 public String getDescription() {
36 return description;
37 }
38
39 /**
40 * Sets the value of the description property.
41 *
42 * @param value allowed object is {@link String }
43 */
44 public void setDescription(String value) {
45 this.description = value;
46 }
47
48 public boolean isSetDescription() {
49 return (this.description != null);
50 }
51 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceBaseResources.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceBaseResources {
3
4 }
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceBusinessEntity.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import java.io.Serializable;
3
4 public interface GenericSuperInterfaceBusinessEntity<T extends Serializable> extends Serializable {
5
6 /**
7 * Returns the unique ID of the business entity.
8 *
9 * @return The unique ID of the business entity.
10 */
11 T getId();
12
13 /**
14 * Sets the unique ID of the business entity
15 *
16 * @param id The unique ID of the business entity.
17 */
18 void setId(T id);
19 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceDataCenter.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class GenericSuperInterfaceDataCenter extends GenericSuperInterfaceBaseResource {
6 private String name;
7
8 public String getName() {
9 return name;
10 }
11
12 public void setName(String name) {
13 this.name = name;
14 }
15 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceDataCenterResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.Produces;
4 import javax.ws.rs.core.MediaType;
5
6 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
7 public interface GenericSuperInterfaceDataCenterResource extends GenericSuperInterfaceUpdatableResource<GenericSuperInterfaceDataCenter> {
8
9 @Path("permissions")
10 GenericSuperInterfaceAssignedPermissionsResource getPermissionsResource();
11
12 }
+0
-6
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceDataCenters.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceDataCenters
3 extends GenericSuperInterfaceBaseResources {
4
5 }
+0
-46
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceDataCentersResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.DELETE;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.PathParam;
10 import javax.ws.rs.Produces;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.Response;
13
14 @Path("/datacenters")
15 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
16 public interface GenericSuperInterfaceDataCentersResource {
17
18 @GET
19 @Formatted
20 GenericSuperInterfaceDataCenters list();
21
22 @POST
23 @Formatted
24 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
25 Response add(GenericSuperInterfaceDataCenter dataCenter);
26
27 @DELETE
28 @Path("{id}")
29 Response remove(@PathParam("id") String id);
30
31 @DELETE
32 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
33 @Path("{id}")
34 Response remove(@PathParam("id") String id, GenericSuperInterfaceAction action);
35
36 /**
37 * Sub-resource locator method, returns individual GenericSuperInterfaceDataCenterResource on which the
38 * remainder of the URI is dispatched.
39 *
40 * @param id the GenericSuperInterfaceDataCenter ID
41 * @return matching subresource if found
42 */
43 @Path("{id}")
44 GenericSuperInterfaceDataCenterResource getDataCenterSubResource(@PathParam("id") String id);
45 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceGuid.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import java.io.Serializable;
3
4 public class GenericSuperInterfaceGuid implements Serializable {
5
6 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceINotifyPropertyChanged.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public interface GenericSuperInterfaceINotifyPropertyChanged {
3
4 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceIVdcQueryable.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceIVdcQueryable {
3
4 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceStoragePool.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class GenericSuperInterfaceStoragePool extends GenericSuperInterfaceIVdcQueryable implements GenericSuperInterfaceINotifyPropertyChanged, GenericSuperInterfaceBusinessEntity<GenericSuperInterfaceGuid> {
3
4 @Override
5 public GenericSuperInterfaceGuid getId() {
6 return null;
7 }
8
9 @Override
10 public void setId(GenericSuperInterfaceGuid id) {
11 }
12 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceTop.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("/")
5 public class GenericSuperInterfaceTop {
6 @Path("datacenters")
7 public GenericSuperInterfaceBackendDataCentersResource getDatacenters() {
8 return new GenericSuperInterfaceBackendDataCentersResource();
9 }
10
11 // here we get GenericSuperInterfaceBackendDataCentersResource collection sub-resource GenericSuperInterfaceBackendDataCenterResource
12 // e.g "/datacenters/xxx"
13
14 // and invoke one of the methods inherited from GenericSuperInterfaceUpdatableResource on it
15 // e.g get()/update()
16 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/GenericSuperInterfaceUpdatableResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.PUT;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.MediaType;
7
8 @Produces({MediaType.APPLICATION_XML})
9 public interface GenericSuperInterfaceUpdatableResource<R extends GenericSuperInterfaceBaseResource> {
10
11 @GET
12 R get();
13
14 @PUT
15 @Consumes({MediaType.APPLICATION_XML})
16 R update(R resource);
17 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/InheritanceAnimal.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAttribute;
3 import javax.xml.bind.annotation.XmlSeeAlso;
4
5 @XmlSeeAlso({InheritanceDog.class, InheritanceCat.class})
6 public abstract class InheritanceAnimal {
7 @XmlAttribute
8 public String name;
9
10 public InheritanceAnimal() {
11 }
12
13 public InheritanceAnimal(final String name) {
14 this.name = name;
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/InheritanceCat.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlRootElement;
5
6 @XmlRootElement
7 @XmlAccessorType(XmlAccessType.PROPERTY)
8 public class InheritanceCat extends InheritanceAnimal {
9
10 public InheritanceCat() {
11 }
12
13 public InheritanceCat(final String name) {
14 super(name);
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/InheritanceDog.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlRootElement;
5
6 @XmlRootElement
7 @XmlAccessorType(XmlAccessType.PROPERTY)
8 public class InheritanceDog extends InheritanceAnimal {
9
10 public InheritanceDog() {
11 }
12
13 public InheritanceDog(final String name) {
14 super(name);
15 }
16 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/InheritanceResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/zoo")
7 public class InheritanceResource {
8
9 @GET
10 @Produces("application/xml")
11 public InheritanceZoo getZoo() {
12 InheritanceZoo aZoo = new InheritanceZoo();
13 aZoo.add(new InheritanceDog("Foo"));
14 aZoo.add(new InheritanceCat("Bar"));
15 return aZoo;
16 }
17 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/InheritanceZoo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlElementRef;
3 import javax.xml.bind.annotation.XmlRootElement;
4 import java.util.ArrayList;
5 import java.util.List;
6
7 @XmlRootElement
8 public class InheritanceZoo {
9
10 private List<InheritanceAnimal> animals;
11
12 public InheritanceZoo() {
13 animals = new ArrayList<InheritanceAnimal>();
14 }
15
16 @XmlElementRef
17 public List<InheritanceAnimal> getAnimals() {
18 return animals;
19 }
20
21 public void add(InheritanceAnimal animal) {
22 animals.add(animal);
23 }
24 }
+0
-133
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/Item.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.Unmarshaller;
3 import javax.xml.bind.annotation.XmlAccessType;
4 import javax.xml.bind.annotation.XmlAccessorType;
5 import javax.xml.bind.annotation.XmlElement;
6 import javax.xml.bind.annotation.XmlRootElement;
7 import javax.xml.bind.annotation.XmlTransient;
8 import javax.xml.bind.annotation.XmlType;
9
10 @XmlRootElement
11 @XmlAccessorType(XmlAccessType.FIELD)
12 @XmlType(name = "itemtype", propOrder = {
13 "title",
14 "note",
15 "quantity",
16 "price"
17 })
18 public class Item {
19 @XmlElement(required = true)
20 private String title;
21
22 private String note;
23
24 @XmlElement(required = true)
25 private Integer quantity;
26
27 @XmlElement(required = true)
28 private Double price;
29
30 @XmlTransient
31 private Order order;
32
33 /**
34 * Get the order.
35 *
36 * @return the order.
37 */
38 public Order getOrder() {
39 return order;
40 }
41
42 /**
43 * Set the order.
44 *
45 * @param order The order to set.
46 */
47 public void setOrder(Order order) {
48 this.order = order;
49 }
50
51 /**
52 * Get the title.
53 *
54 * @return the title.
55 */
56 public String getTitle() {
57 return title;
58 }
59
60 /**
61 * Set the title.
62 *
63 * @param title The title to set.
64 */
65 public void setTitle(String title) {
66 this.title = title;
67 }
68
69 /**
70 * Get the note.
71 *
72 * @return the note.
73 */
74 public String getNote() {
75 return note;
76 }
77
78 /**
79 * Set the note.
80 *
81 * @param note The note to set.
82 */
83 public void setNote(String note) {
84 this.note = note;
85 }
86
87 /**
88 * Get the quantity.
89 *
90 * @return the quantity.
91 */
92 public Integer getQuantity() {
93 return quantity;
94 }
95
96 /**
97 * Set the quantity.
98 *
99 * @param quantity The quantity to set.
100 */
101 public void setQuantity(Integer quantity) {
102 this.quantity = quantity;
103 }
104
105 /**
106 * Get the price.
107 *
108 * @return the price.
109 */
110 public Double getPrice() {
111 return price;
112 }
113
114 /**
115 * Set the price.
116 *
117 * @param price The price to set.
118 */
119 public void setPrice(Double price) {
120 this.price = price;
121 }
122
123 /**
124 * JAXB Callback method used to reassociate the item with the owning Order.
125 *
126 * @param unmarshaller the JAXB {@link Unmarshaller}.
127 * @param parent the owning {@link Contact} instance.
128 */
129 public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
130 this.setOrder((Order) order);
131 }
132 }
+0
-128
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/Itemtype.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import java.math.BigDecimal;
3 import java.math.BigInteger;
4 import javax.xml.bind.annotation.XmlAccessType;
5 import javax.xml.bind.annotation.XmlAccessorType;
6 import javax.xml.bind.annotation.XmlElement;
7 import javax.xml.bind.annotation.XmlType;
8
9
10 /**
11 * <p>Java class for itemtype complex type.
12 * <p>
13 * <p>The following schema fragment specifies the expected content contained within this class.
14 * <p>
15 * <pre>
16 * &lt;complexType name="itemtype">
17 * &lt;complexContent>
18 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
19 * &lt;sequence>
20 * &lt;element name="title" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}stringtype"/>
21 * &lt;element name="note" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}stringtype" minOccurs="0"/>
22 * &lt;element name="quantity" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}inttype"/>
23 * &lt;element name="price" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}dectype"/>
24 * &lt;/sequence>
25 * &lt;/restriction>
26 * &lt;/complexContent>
27 * &lt;/complexType>
28 * </pre>
29 */
30 @XmlAccessorType(XmlAccessType.FIELD)
31 @XmlType(name = "itemtype", propOrder = {
32 "title",
33 "note",
34 "quantity",
35 "price"
36 })
37 public class Itemtype {
38
39 @XmlElement(required = true)
40 protected String title;
41 protected String note;
42 @XmlElement(required = true)
43 protected BigInteger quantity;
44 @XmlElement(required = true)
45 protected BigDecimal price;
46
47 /**
48 * Gets the value of the title property.
49 *
50 * @return possible object is
51 * {@link String }
52 */
53 public String getTitle() {
54 return title;
55 }
56
57 /**
58 * Sets the value of the title property.
59 *
60 * @param value allowed object is
61 * {@link String }
62 */
63 public void setTitle(String value) {
64 this.title = value;
65 }
66
67 /**
68 * Gets the value of the note property.
69 *
70 * @return possible object is
71 * {@link String }
72 */
73 public String getNote() {
74 return note;
75 }
76
77 /**
78 * Sets the value of the note property.
79 *
80 * @param value allowed object is
81 * {@link String }
82 */
83 public void setNote(String value) {
84 this.note = value;
85 }
86
87 /**
88 * Gets the value of the quantity property.
89 *
90 * @return possible object is
91 * {@link BigInteger }
92 */
93 public BigInteger getQuantity() {
94 return quantity;
95 }
96
97 /**
98 * Sets the value of the quantity property.
99 *
100 * @param value allowed object is
101 * {@link BigInteger }
102 */
103 public void setQuantity(BigInteger value) {
104 this.quantity = value;
105 }
106
107 /**
108 * Gets the value of the price property.
109 *
110 * @return possible object is
111 * {@link BigDecimal }
112 */
113 public BigDecimal getPrice() {
114 return price;
115 }
116
117 /**
118 * Sets the value of the price property.
119 *
120 * @param value allowed object is
121 * {@link BigDecimal }
122 */
123 public void setPrice(BigDecimal value) {
124 this.price = value;
125 }
126
127 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JAXBCache.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.core.ExceptionAdapter;
3 import org.jboss.logging.Logger;
4
5 import javax.xml.bind.JAXBContext;
6 import javax.xml.bind.JAXBException;
7 import java.util.concurrent.ConcurrentHashMap;
8
9 public final class JAXBCache {
10
11 private static final Logger logger = Logger.getLogger(JAXBCache.class);
12
13 private static JAXBCache instance = new JAXBCache();
14
15 private ConcurrentHashMap<Object, JAXBContext> contextCache = new ConcurrentHashMap<Object, JAXBContext>();
16
17 private JAXBCache() {
18
19 }
20
21 public static JAXBCache instance() {
22 return instance;
23 }
24
25 public JAXBContext getJAXBContext(Class<?>... classes) {
26 JAXBContext context = contextCache.get(classes);
27 if (context == null) {
28 try {
29 context = JAXBContext.newInstance(classes);
30 } catch (JAXBException e) {
31 throw new ExceptionAdapter(e);
32 }
33 contextCache.putIfAbsent(classes, context);
34 }
35 logger.debugv("Locating JAXBContext for package: {0}", (Object[]) classes);
36 return context;
37 }
38
39 /*public JAXBContext getJAXBContext(String... packageNames) {
40 String contextPath = buildContextPath(packageNames);
41 logger.debug("Locating JAXBContext for packages: {0}", contextPath);
42 // FIXME This was the original call causing an infinitive recursive loop.
43 // However I don't know how to fix it, but this method is not used currently
44 // so instead of fixing it modified it to return a null and not going into
45 // recursive loop for now.
46
47 // return getJAXBContext(contextPath, null);
48 return null;
49 }*/
50
51 private String buildContextPath(String[] packageNames) {
52 StringBuilder b = new StringBuilder();
53 for (int i = 0; i < packageNames.length; i++) {
54 b.append(packageNames[i]);
55 if (i != (packageNames.length - 1)) {
56 b.append(":");
57 }
58 }
59 return b.toString();
60 }
61
62 }
+0
-73
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbCacheChild.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2
3 import javax.xml.bind.Unmarshaller;
4 import javax.xml.bind.annotation.XmlAccessType;
5 import javax.xml.bind.annotation.XmlAccessorType;
6 import javax.xml.bind.annotation.XmlRootElement;
7 import javax.xml.bind.annotation.XmlTransient;
8 import javax.xml.bind.annotation.XmlType;
9
10 @XmlRootElement
11 @XmlAccessorType(XmlAccessType.FIELD)
12 @XmlType(name = "childType")
13 public class JaxbCacheChild {
14 private String name;
15
16 @XmlTransient
17 private JaxbCacheParent parent;
18
19 public JaxbCacheChild() {
20
21 }
22
23 public JaxbCacheChild(final String name) {
24 this.name = name;
25 }
26
27 /**
28 * Get the name.
29 *
30 * @return the name.
31 */
32 public String getName() {
33 return name;
34 }
35
36 /**
37 * Set the name.
38 *
39 * @param name The name to set.
40 */
41 public void setName(String name) {
42 this.name = name;
43 }
44
45 /**
46 * Get the parent.
47 *
48 * @return the parent.
49 */
50 public JaxbCacheParent getParent() {
51 return parent;
52 }
53
54 /**
55 * Set the parent.
56 *
57 * @param parent The parent to set.
58 */
59 public void setParent(JaxbCacheParent parent) {
60 this.parent = parent;
61 }
62
63 /**
64 * Set parent after unmarshalling
65 *
66 * @param unmarshaller
67 * @param JaxbCacheParent
68 */
69 public void afterUnmarshal(Unmarshaller unmarshaller, Object object) {
70 this.parent = (JaxbCacheParent) object;
71 }
72 }
+0
-79
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbCacheParent.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2
3 import javax.xml.bind.annotation.XmlAccessType;
4 import javax.xml.bind.annotation.XmlAccessorType;
5 import javax.xml.bind.annotation.XmlElement;
6 import javax.xml.bind.annotation.XmlElementWrapper;
7 import javax.xml.bind.annotation.XmlRootElement;
8 import javax.xml.bind.annotation.XmlType;
9 import java.util.ArrayList;
10 import java.util.List;
11
12 @XmlRootElement
13 @XmlAccessorType(XmlAccessType.FIELD)
14 @XmlType(name = "parentType")
15 public class JaxbCacheParent {
16 private String name;
17
18 @XmlElementWrapper(name = "children")
19 @XmlElement(name = "child")
20 private List<JaxbCacheChild> children = new ArrayList<JaxbCacheChild>();
21
22 public JaxbCacheParent() {
23
24 }
25
26 public JaxbCacheParent(final String name) {
27 this.name = name;
28 }
29
30 /**
31 * Get the name.
32 *
33 * @return the name.
34 */
35 public String getName() {
36 return name;
37 }
38
39 /**
40 * Set the name.
41 *
42 * @param name The name to set.
43 */
44 public void setName(String name) {
45 this.name = name;
46 }
47
48 /**
49 * Get the children.
50 *
51 * @return the children.
52 */
53 public List<JaxbCacheChild> getChildren() {
54 return children;
55 }
56
57 /**
58 * Set the children.
59 *
60 * @param children The children to set.
61 */
62 public void setChildren(List<JaxbCacheChild> children) {
63 this.children = children;
64 }
65
66 public void addChild(JaxbCacheChild child) {
67 child.setParent(this);
68 this.children.add(child);
69 }
70
71 public static JaxbCacheParent createTestParent(String name) {
72 JaxbCacheParent parent = new JaxbCacheParent(name);
73 parent.addChild(new JaxbCacheChild("JaxbCacheChild 1"));
74 parent.addChild(new JaxbCacheChild("JaxbCacheChild 2"));
75 parent.addChild(new JaxbCacheChild("JaxbCacheChild 3"));
76 return parent;
77 }
78 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbCollectionFoo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "foo")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class JaxbCollectionFoo {
10 @XmlAttribute
11 private String test;
12
13 public JaxbCollectionFoo() {
14 }
15
16 public JaxbCollectionFoo(final String test) {
17 this.test = test;
18 }
19
20 public String getTest() {
21 return test;
22 }
23
24 public void setTest(String test) {
25 this.test = test;
26 }
27 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbCollectionNamespacedFoo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "foo", namespace = "http://foo.com")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class JaxbCollectionNamespacedFoo {
10 @XmlAttribute
11 private String test;
12
13 public JaxbCollectionNamespacedFoo() {
14 }
15
16 public JaxbCollectionNamespacedFoo(final String test) {
17 this.test = test;
18 }
19
20 public String getTest() {
21 return test;
22 }
23
24 public void setTest(String test) {
25 this.test = test;
26 }
27 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbCollectionNamespacedResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.Wrapped;
3 import org.junit.Assert;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import java.util.List;
10
11 @Path("/namespaced")
12 public class JaxbCollectionNamespacedResource {
13 @Path("/array")
14 @Produces("application/xml")
15 @Consumes("application/xml")
16 @POST
17 public JaxbCollectionNamespacedFoo[] naked(JaxbCollectionNamespacedFoo[] foo) {
18 Assert.assertEquals("The unmarshalled array doesn't contain 1 item, which is expected", 1, foo.length);
19 Assert.assertEquals("The unmarshalled array doesn't contain correct element value", foo[0].getTest(), "hello");
20 return foo;
21 }
22
23 @Path("/list")
24 @POST
25 @Produces("application/xml")
26 @Consumes("application/xml")
27 @Wrapped(element = "list", namespace = "", prefix = "")
28 public List<JaxbCollectionNamespacedFoo> wrapped(@Wrapped(element = "list", namespace = "", prefix = "") List<JaxbCollectionNamespacedFoo> list) {
29 Assert.assertEquals("The unmarshalled list doesn't contain 1 item, which is expected", 1, list.size());
30 Assert.assertEquals("The unmarshalled list doesn't contain correct element value", list.get(0).getTest(), "hello");
31 return list;
32 }
33
34
35 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbCollectionResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.Wrapped;
3 import org.junit.Assert;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import java.util.List;
10
11 @Path("/")
12 public class JaxbCollectionResource {
13 @Path("/array")
14 @Produces("application/xml")
15 @Consumes("application/xml")
16 @POST
17 public JaxbCollectionFoo[] naked(JaxbCollectionFoo[] foo) {
18 Assert.assertEquals("The unmarshalled array doesn't contain 1 item, which is expected", 1, foo.length);
19 Assert.assertEquals("The unmarshalled array doesn't contain correct element value", foo[0].getTest(), "hello");
20 return foo;
21 }
22
23 @Path("/list")
24 @POST
25 @Produces("application/xml")
26 @Consumes("application/xml")
27 @Wrapped(element = "list", namespace = "", prefix = "")
28 public List<JaxbCollectionFoo> wrapped(@Wrapped(element = "list", namespace = "", prefix = "") List<JaxbCollectionFoo> list) {
29 Assert.assertEquals("The unmarshalled list doesn't contain 1 item, which is expected", 1, list.size());
30 Assert.assertEquals("The unmarshalled list doesn't contain correct element value", list.get(0).getTest(), "hello");
31 return list;
32 }
33
34
35 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbElementClient.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8 import javax.xml.bind.JAXBElement;
9
10 @Consumes("application/xml")
11 @Produces("application/xml")
12 public interface JaxbElementClient {
13
14 @GET
15 @Path("/{name}")
16 JAXBElement<Parent> getParent(@PathParam("name") String name);
17
18 @POST
19 JAXBElement<Parent> postParent(JAXBElement<Parent> parent);
20
21 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbElementEntityMessageReader.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import javax.ws.rs.ext.MessageBodyReader;
6 import java.io.BufferedReader;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.InputStreamReader;
10 import java.lang.annotation.Annotation;
11 import java.lang.reflect.Type;
12
13 public class JaxbElementEntityMessageReader implements
14 MessageBodyReader<JaxbElementReadableWritableEntity> {
15
16 @Override
17 public boolean isReadable(Class<?> type, Type genericType,
18 Annotation[] annotations, MediaType mediaType) {
19 return JaxbElementReadableWritableEntity.class.isAssignableFrom(type);
20 }
21
22 @Override
23 public JaxbElementReadableWritableEntity readFrom(Class<JaxbElementReadableWritableEntity> arg0,
24 Type arg1, Annotation[] annotations, MediaType mediaType,
25 MultivaluedMap<String, String> arg4, InputStream entityStream)
26 throws IOException, WebApplicationException {
27 String entity = readInputStream(entityStream);
28 return JaxbElementReadableWritableEntity.fromString(entity);
29 }
30
31 String readInputStream(InputStream is) throws IOException {
32 InputStreamReader isr = new InputStreamReader(is);
33 BufferedReader br = new BufferedReader(isr);
34 return br.readLine();
35 }
36
37 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbElementEntityMessageWriter.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.WebApplicationException;
3 import javax.ws.rs.core.MediaType;
4 import javax.ws.rs.core.MultivaluedMap;
5 import javax.ws.rs.ext.MessageBodyWriter;
6 import java.io.IOException;
7 import java.io.OutputStream;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Type;
10
11 public class JaxbElementEntityMessageWriter implements
12 MessageBodyWriter<JaxbElementReadableWritableEntity> {
13
14 @Override
15 public long getSize(JaxbElementReadableWritableEntity t, Class<?> type,
16 Type genericType, Annotation[] annotations, MediaType mediaType) {
17 return t.toXmlString().length();
18 }
19
20 @Override
21 public boolean isWriteable(Class<?> type, Type genericType,
22 Annotation[] annotations, MediaType mediaType) {
23 return JaxbElementReadableWritableEntity.class.isAssignableFrom(type);
24 }
25
26 @Override
27 public void writeTo(JaxbElementReadableWritableEntity t, Class<?> type,
28 Type genericType, Annotation[] annotations, MediaType mediaType,
29 MultivaluedMap<String, Object> httpHeaders,
30 OutputStream entityStream) throws IOException,
31 WebApplicationException {
32 entityStream.write(t.toXmlString().getBytes());
33 }
34
35 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbElementReadableWritableEntity.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 public class JaxbElementReadableWritableEntity {
3 private String entity;
4 public static final String NAME = "READABLEWRITEABLE";
5 private static final String PREFIX = "<" + NAME + ">";
6 private static final String SUFFIX = "</" + NAME + ">";
7
8 public JaxbElementReadableWritableEntity(final String entity) {
9 this.entity = entity;
10 }
11
12 public String toXmlString() {
13 StringBuilder sb = new StringBuilder();
14 sb.append(PREFIX).append(entity).append(SUFFIX);
15 return sb.toString();
16 }
17
18 @Override
19 public String toString() {
20 return entity;
21 }
22
23 public static JaxbElementReadableWritableEntity fromString(String stream) {
24 String entity = stream.replaceAll(PREFIX, "").replaceAll(SUFFIX, "");
25 return new JaxbElementReadableWritableEntity(entity);
26 }
27 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbElementResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;;
4
5 @Path("resource")
6 public class JaxbElementResource {
7
8 @POST
9 @Path("standardwriter")
10 public String bytearraywriter(String value) {
11 return value;
12 }
13 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbJsonElementClient.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8 import javax.xml.bind.JAXBElement;
9
10 @Consumes("application/json")
11 @Produces("application/json")
12 public interface JaxbJsonElementClient {
13
14 @GET
15 @Path("/{name}")
16 JAXBElement<Parent> getParent(@PathParam("name") String name);
17
18 @POST
19 JAXBElement<Parent> postParent(JAXBElement<Parent> parent);
20
21 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbJsonXmlRootElementClient.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8
9 @Consumes("application/json")
10 @Produces("application/json")
11 public interface JaxbJsonXmlRootElementClient {
12
13 @GET
14 @Path("/{name}")
15 Parent getParent(@PathParam("name") String name);
16
17 @GET
18 @Path("/{name}")
19 String getParentString(@PathParam("name") String name);
20
21 @POST
22 Parent postParent(Parent parent);
23
24 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbJunkXmlOrderClient.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8
9 @Consumes({"application/junk+xml"})
10 @Produces({"application/junk+xml"})
11 public interface JaxbJunkXmlOrderClient {
12
13 @GET
14 @Path("/{name}")
15 Parent getParent(@PathParam("name")
16 String name);
17
18 @POST
19 Parent postParent(Parent parent);
20
21 }
+0
-50
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbMarshallingSoakAsyncService.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.test.providers.jaxb.JaxbMarshallingSoakTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import java.io.ByteArrayInputStream;
11
12 @Path("/mpac")
13 public class JaxbMarshallingSoakAsyncService {
14 @GET()
15 @Produces("text/plain")
16 public String sayHello() {
17 return "Hello World!";
18 }
19
20
21 public void addSchedule(JaxbMarshallingSoakItem item) {
22 try {
23 Assert.assertNotNull(item);
24 item.toString();
25 JaxbMarshallingSoakTest.counter.incrementAndGet();
26 } finally {
27 JaxbMarshallingSoakTest.latch.countDown();
28 }
29 }
30
31 @POST()
32 @Path("/add")
33 @Consumes("application/xml")
34 public void addSchedule(byte[] bytes) throws Exception {
35 ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
36 JaxbMarshallingSoakItem item = (JaxbMarshallingSoakItem) JaxbMarshallingSoakTest.ctx.createUnmarshaller().unmarshal(bais);
37 try {
38 addSchedule(item);
39 } catch (Exception ex) {
40 String str = new String(bytes);
41 String msg = "Failed ";
42 if (!str.equals(JaxbMarshallingSoakTest.itemString)) {
43 msg += " with " + str;
44 }
45 throw new Exception(msg);
46 }
47 }
48
49 }
+0
-134
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbMarshallingSoakItem.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3 import java.util.Map;
4
5 @XmlRootElement(name = "item")
6 public class JaxbMarshallingSoakItem {
7 String description;
8 int price;
9 String requestID;
10 String dummy1;
11 String dummy2;
12 String dummy3;
13 String dummy4;
14 String dummy5;
15 String dummy6;
16 String dummy7;
17 String dummy8;
18 Map<String, String> harness;
19
20 public Map<String, String> getHarness() {
21 return this.harness;
22 }
23
24 public void setHarness(Map<String, String> harness) {
25 this.harness = harness;
26 }
27
28 public String getDummy1() {
29 return dummy1;
30 }
31
32 public void setDummy1(String dummy1) {
33 this.dummy1 = dummy1;
34 }
35
36 public String getDummy2() {
37 return dummy2;
38 }
39
40 public void setDummy2(String dummy2) {
41 this.dummy2 = dummy2;
42 }
43
44 public String getDummy3() {
45 return dummy3;
46 }
47
48 public void setDummy3(String dummy3) {
49 this.dummy3 = dummy3;
50 }
51
52 public String getDummy4() {
53 return dummy4;
54 }
55
56 public void setDummy4(String dummy4) {
57 this.dummy4 = dummy4;
58 }
59
60 public String getDummy5() {
61 return dummy5;
62 }
63
64 public void setDummy5(String dummy5) {
65 this.dummy5 = dummy5;
66 }
67
68 public String getDummy6() {
69 return dummy6;
70 }
71
72 public void setDummy6(String dummy6) {
73 this.dummy6 = dummy6;
74 }
75
76 public String getDummy7() {
77 return dummy7;
78 }
79
80 public void setDummy7(String dummy7) {
81 this.dummy7 = dummy7;
82 }
83
84 public String getDummy8() {
85 return dummy8;
86 }
87
88 public void setDummy8(String dummy8) {
89 this.dummy8 = dummy8;
90 }
91
92 public String getDescription() {
93 return description;
94 }
95
96 public void setDescription(String description) {
97 this.description = description;
98 }
99
100 public String getRequestID() {
101 return this.requestID;
102 }
103
104 public void setRequestID(String requestID) {
105 this.requestID = requestID;
106 }
107
108 public int getPrice() {
109 return this.price;
110 }
111
112 public void setPrice(int price) {
113 this.price = price;
114 }
115
116 public String toString() {
117 StringBuffer buffer = new StringBuffer();
118 buffer.append("Price " + this.price);
119 buffer.append(" Description " + this.description);
120 buffer.append(" RequestID " + this.requestID);
121 buffer.append(" Dummy1 " + this.dummy1);
122 buffer.append(" Dummy2 " + this.dummy2);
123 buffer.append(" Dummy3 " + this.dummy3);
124 buffer.append(" Dummy4 " + this.dummy4);
125 buffer.append(" Dummy5 " + this.dummy5);
126 buffer.append(" Dummy6 " + this.dummy6);
127 buffer.append(" Dummy7 " + this.dummy7);
128 buffer.append(" Dummy8 " + this.dummy8);
129 buffer.append(" HASHNAP " + this.harness.toString());
130
131 return buffer.toString();
132 }
133 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbXmlRootElementClient.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8
9 @Consumes("application/xml")
10 @Produces("application/xml")
11 public interface JaxbXmlRootElementClient {
12
13 @GET
14 @Path("/{name}")
15 Parent getParent(@PathParam("name") String name);
16
17 @POST
18 Parent postParent(Parent parent);
19
20 }
+0
-41
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/JaxbXmlRootElementProviderResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.GET;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.PathParam;
9 import javax.ws.rs.Produces;
10
11 @Path("/jaxb")
12 @Consumes(
13 {"application/xml", "application/fastinfoset", "application/json"})
14 @Produces(
15 {"application/xml", "application/fastinfoset", "application/json"})
16 public class JaxbXmlRootElementProviderResource {
17
18 @GET
19 @Path("/{name}")
20 public Parent getParent(@PathParam("name") String name) {
21 Parent parent = Parent.createTestParent(name);
22 return parent;
23 }
24
25 @GET
26 @Path("/{name}")
27 @Produces("application/junk+xml")
28 public Parent getParentJunk(@PathParam("name") String name) {
29 Parent parent = Parent.createTestParent(name);
30 return parent;
31 }
32
33 @POST
34 public Parent postParent(Parent parent) {
35 Assert.assertTrue(parent.getChildren().size() > 0);
36 Assert.assertTrue(parent.getChildren().get(0).getParent().equals(parent));
37 parent.addChild(new Child("Child 4"));
38 return parent;
39 }
40 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/KeepCharsetFavoriteMovieXmlRootElement.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class KeepCharsetFavoriteMovieXmlRootElement {
6 private String _title;
7
8 public String getTitle() {
9 return _title;
10 }
11
12 public void setTitle(String title) {
13 _title = title;
14 }
15 }
+0
-44
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/KeepCharsetMovieResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.Path;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.Produces;
8 import java.nio.charset.Charset;
9
10 @Path("/")
11 public class KeepCharsetMovieResource {
12
13 private static Logger logger = Logger.getLogger(KeepCharsetMovieResource.class);
14
15 @POST
16 @Path("/xml/produces")
17 @Consumes("application/xml")
18 @Produces("application/xml;charset=UTF-16")
19 public KeepCharsetFavoriteMovieXmlRootElement xmlProduces(KeepCharsetFavoriteMovieXmlRootElement movie) {
20 logger.info("server default charset: " + Charset.defaultCharset());
21 logger.info("title: " + movie.getTitle());
22 return movie;
23 }
24
25 @POST
26 @Path("/xml/accepts")
27 @Consumes("application/xml")
28 public KeepCharsetFavoriteMovieXmlRootElement xmlAccepts(KeepCharsetFavoriteMovieXmlRootElement movie) {
29 logger.info("server default charset: " + Charset.defaultCharset());
30 logger.info("title: " + movie.getTitle());
31 return movie;
32 }
33
34 @POST
35 @Path("/xml/default")
36 @Consumes("application/xml")
37 @Produces("application/xml")
38 public KeepCharsetFavoriteMovieXmlRootElement xmlDefault(KeepCharsetFavoriteMovieXmlRootElement movie) {
39 logger.info("server default charset: " + Charset.defaultCharset());
40 logger.info("title: " + movie.getTitle());
41 return movie;
42 }
43 }
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/LinkJaxbCustomer.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.core.Link;
3 import javax.xml.bind.annotation.XmlAccessType;
4 import javax.xml.bind.annotation.XmlAccessorType;
5 import javax.xml.bind.annotation.XmlElement;
6 import javax.xml.bind.annotation.XmlRootElement;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 @XmlRootElement(name = "customer")
11 @XmlAccessorType(XmlAccessType.PROPERTY)
12 public class LinkJaxbCustomer {
13 private String name;
14 private List<Link> links = new ArrayList<Link>();
15
16 public LinkJaxbCustomer() {
17 }
18
19 public LinkJaxbCustomer( final String name) {
20 this.name = name;
21 }
22
23 @XmlElement
24 public String getName() {
25 return name;
26 }
27
28 public void setName(String name) {
29 this.name = name;
30 }
31
32 @XmlElement(name = "link")
33 public List<Link> getLinks() {
34 return links;
35 }
36 }
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/LinkJaxbResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Link;
6
7 @Path("/")
8 public class LinkJaxbResource {
9 @GET
10 @Produces("application/xml")
11 public LinkJaxbCustomer getCustomer() {
12 LinkJaxbCustomer cust = new LinkJaxbCustomer("bill");
13 Link link = Link.fromUri("a/b/c").build();
14 cust.getLinks().add(link);
15 link = Link.fromUri("c/d").rel("delete").build();
16 cust.getLinks().add(link);
17 return cust;
18 }
19 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/MapFoo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAttribute;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement(namespace = "http://foo.com")
6 public class MapFoo {
7 @XmlAttribute
8 private String name;
9
10 public MapFoo() {
11 }
12
13 public MapFoo(final String name) {
14 this.name = name;
15 }
16
17 public String getName() {
18 return name;
19 }
20 }
+0
-93
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/MapJaxb.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.JAXBElement;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAccessType;
5 import javax.xml.bind.annotation.XmlAnyElement;
6 import javax.xml.bind.annotation.XmlAnyAttribute;
7 import javax.xml.bind.annotation.XmlTransient;
8 import javax.xml.namespace.QName;
9 import java.util.ArrayList;
10 import java.util.HashMap;
11 import java.util.List;
12 import java.util.Map;
13
14 @XmlAccessorType(XmlAccessType.FIELD)
15 public class MapJaxb {
16 @XmlAnyElement
17 List<JAXBElement<Entry>> value = new ArrayList<JAXBElement<Entry>>();
18
19 @XmlTransient
20 private String entryName;
21 @XmlTransient
22 private String keyAttributeName;
23 @XmlTransient
24 private String namespace;
25
26 public MapJaxb() {
27 }
28
29 public MapJaxb(final String entryName, final String keyAttributeName, final String namespace) {
30 this.entryName = entryName;
31 this.namespace = namespace;
32 this.keyAttributeName = keyAttributeName;
33 }
34
35 @XmlAccessorType(XmlAccessType.FIELD)
36 public static class Entry {
37 @XmlAnyElement
38 Object value;
39
40 @XmlAnyAttribute
41 Map<QName, Object> attribute = new HashMap<QName, Object>();
42
43 @XmlTransient
44 private String key;
45
46 @XmlTransient
47 private String keyAttributeName;
48
49 public Entry() {
50 }
51
52 public Entry(final String keyAttributeName, final String key, final Object value) {
53 this.value = value;
54 this.keyAttributeName = keyAttributeName;
55 setKey(key);
56 }
57
58 public Object getValue() {
59 return value;
60 }
61
62 public void setValue(Object value) {
63 this.value = value;
64 }
65
66 public String getKey() {
67 if (key != null) {
68 return key;
69 }
70 key = (String) attribute.values().iterator().next();
71 return key;
72 }
73
74 public void setKey(String keyValue) {
75 this.key = keyValue;
76 attribute.clear();
77
78 QName name = new QName(keyAttributeName);
79 attribute.put(name, keyValue);
80 }
81 }
82
83 public void addEntry(String key, Object val) {
84 Entry entry = new Entry(keyAttributeName, key, val);
85 JAXBElement<Entry> element = new JAXBElement<Entry>(new QName(namespace, entryName), Entry.class, entry);
86 value.add(element);
87 }
88
89 public List<JAXBElement<Entry>> getValue() {
90 return value;
91 }
92 }
+0
-57
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/MapResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.WrappedMap;
3 import org.junit.Assert;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import java.util.HashMap;
10 import java.util.Map;
11
12 @Path("/map")
13 public class MapResource {
14 @POST
15 @Produces("application/xml")
16 @Consumes("application/xml")
17 public Map<String, MapFoo> post(Map<String, MapFoo> map) {
18 Assert.assertEquals("The map from the request has unexpected content", 2, map.size());
19 Assert.assertNotNull("The map from the request has unexpected content", map.get("bill"));
20 Assert.assertNotNull("The map from the request has unexpected content", map.get("monica"));
21 Assert.assertEquals("The map from the request has unexpected content", map.get("bill").getName(), "bill");
22 Assert.assertEquals("The map from the request has unexpected content", map.get("monica").getName(), "monica");
23 return map;
24 }
25
26 @POST
27 @Produces("application/xml")
28 @Consumes("application/xml")
29 @Path("/wrapped")
30 @WrappedMap(namespace = "")
31 public Map<String, MapFoo> postWrapped(@WrappedMap(namespace = "") Map<String, MapFoo> map) {
32 Assert.assertEquals("The map from the request has unexpected content", 2, map.size());
33 Assert.assertNotNull("The map from the request has unexpected content", map.get("bill"));
34 Assert.assertNotNull("The map from the request has unexpected content", map.get("monica"));
35 Assert.assertEquals("The map from the request has unexpected content", map.get("bill").getName(), "bill");
36 Assert.assertEquals("The map from the request has unexpected content", map.get("monica").getName(), "monica");
37 return map;
38 }
39
40 @POST
41 @Produces("application/xml")
42 @Consumes("application/xml")
43 @Path("/integerFoo")
44 public Map<Integer, MapFoo> postIntegerFoo(Map<String, MapFoo> map) {
45 Assert.assertEquals("The map from the request has unexpected content", 2, map.size());
46 Assert.assertNotNull("The map from the request has unexpected content", map.get("1"));
47 Assert.assertNotNull("The map from the request has unexpected content", map.get("2"));
48 Assert.assertEquals("The map from the request has unexpected content", map.get("1").getName(), "bill");
49 Assert.assertEquals("The map from the request has unexpected content", map.get("2").getName(), "monica");
50 Map<Integer, MapFoo> result = new HashMap<Integer, MapFoo>();
51 for (Map.Entry<String, MapFoo> e : map.entrySet()) {
52 result.put(Integer.valueOf(e.getKey()), e.getValue());
53 }
54 return result;
55 }
56 }
+0
-132
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/Order.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlElement;
6 import javax.xml.bind.annotation.XmlRootElement;
7 import javax.xml.bind.annotation.XmlType;
8 import java.util.ArrayList;
9 import java.util.List;
10
11 @XmlRootElement
12 @XmlAccessorType(XmlAccessType.FIELD)
13 @XmlType(name = "ordertype", propOrder =
14 {"person", "shipto", "items"})
15 public class Order {
16
17 private String person;
18
19 private ShipTo shipto;
20
21 @XmlElement(name = "item", required = true)
22 private List<Item> items = new ArrayList<Item>();
23
24 @XmlAttribute(required = true)
25 private String orderid;
26
27 /**
28 * Get the person.
29 *
30 * @return the person.
31 */
32 public String getPerson() {
33 return person;
34 }
35
36 /**
37 * Set the person.
38 *
39 * @param person The person to set.
40 */
41 public void setPerson(String person) {
42 this.person = person;
43 }
44
45 /**
46 * Get the shipto.
47 *
48 * @return the shipto.
49 */
50 public ShipTo getShipto() {
51 return shipto;
52 }
53
54 /**
55 * Set the shipto.
56 *
57 * @param shipto The shipto to set.
58 */
59 public void setShipto(ShipTo shipto) {
60 this.shipto = shipto;
61 }
62
63 /**
64 * Add item to items
65 *
66 * @param item
67 */
68 public void addItem(Item item) {
69 item.setOrder(this);
70 items.add(item);
71 }
72
73 /**
74 * Get the item.
75 *
76 * @return the item.
77 */
78 public List<Item> getItems() {
79 return items;
80 }
81
82 public Item getItem(int index) {
83 return items.get(index);
84 }
85
86 /**
87 * Remove item from items
88 *
89 * @param item
90 */
91 public void removeItem(Item item) {
92 items.remove(item);
93 }
94
95 /**
96 * Remove item on specified index
97 *
98 * @param index
99 * @return
100 */
101 public Item removeItem(int index) {
102 return items.remove(index);
103 }
104
105 /**
106 * Set the item.
107 *
108 * @param item The item to set.
109 */
110 public void setItems(List<Item> items) {
111 this.items = items;
112 }
113
114 /**
115 * Get the orderid.
116 *
117 * @return the orderid.
118 */
119 public String getOrderid() {
120 return orderid;
121 }
122
123 /**
124 * Set the orderid.
125 *
126 * @param orderid The orderid to set.
127 */
128 public void setOrderid(String orderid) {
129 this.orderid = orderid;
130 }
131 }
+0
-136
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/Ordertype.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import java.util.ArrayList;
3 import java.util.List;
4 import javax.xml.bind.annotation.XmlAccessType;
5 import javax.xml.bind.annotation.XmlAccessorType;
6 import javax.xml.bind.annotation.XmlAttribute;
7 import javax.xml.bind.annotation.XmlElement;
8 import javax.xml.bind.annotation.XmlType;
9
10
11 /**
12 * <p>Java class for ordertype complex type.
13 * <p>
14 * <p>The following schema fragment specifies the expected content contained within this class.
15 * <p>
16 * <pre>
17 * &lt;complexType name="ordertype">
18 * &lt;complexContent>
19 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
20 * &lt;sequence>
21 * &lt;element name="person" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}stringtype"/>
22 * &lt;element name="shipto" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}shiptotype"/>
23 * &lt;element name="item" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}itemtype" maxOccurs="unbounded"/>
24 * &lt;/sequence>
25 * &lt;attribute name="orderid" use="required" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}orderidtype" />
26 * &lt;/restriction>
27 * &lt;/complexContent>
28 * &lt;/complexType>
29 * </pre>
30 */
31 @XmlAccessorType(XmlAccessType.FIELD)
32 @XmlType(name = "ordertype", propOrder = {
33 "person",
34 "shipto",
35 "item"
36 })
37 public class Ordertype {
38
39 @XmlElement(required = true)
40 protected String person;
41 @XmlElement(required = true)
42 protected Shiptotype shipto;
43 @XmlElement(required = true)
44 protected List<Itemtype> item;
45 @XmlAttribute(required = true)
46 protected String orderid;
47
48 /**
49 * Gets the value of the person property.
50 *
51 * @return possible object is
52 * {@link String }
53 */
54 public String getPerson() {
55 return person;
56 }
57
58 /**
59 * Sets the value of the person property.
60 *
61 * @param value allowed object is
62 * {@link String }
63 */
64 public void setPerson(String value) {
65 this.person = value;
66 }
67
68 /**
69 * Gets the value of the shipto property.
70 *
71 * @return possible object is
72 * {@link Shiptotype }
73 */
74 public Shiptotype getShipto() {
75 return shipto;
76 }
77
78 /**
79 * Sets the value of the shipto property.
80 *
81 * @param value allowed object is
82 * {@link Shiptotype }
83 */
84 public void setShipto(Shiptotype value) {
85 this.shipto = value;
86 }
87
88 /**
89 * Gets the value of the item property.
90 * <p>
91 * <p>
92 * This accessor method returns a reference to the live list,
93 * not a snapshot. Therefore any modification you make to the
94 * returned list will be present inside the JAXB object.
95 * This is why there is not a <CODE>set</CODE> method for the item property.
96 * <p>
97 * <p>
98 * For example, to add a new item, do as follows:
99 * <pre>
100 * getItem().add(newItem);
101 * </pre>
102 * <p>
103 * <p>
104 * <p>
105 * Objects of the following type(s) are allowed in the list
106 * {@link Itemtype }
107 */
108 public List<Itemtype> getItem() {
109 if (item == null) {
110 item = new ArrayList<Itemtype>();
111 }
112 return this.item;
113 }
114
115 /**
116 * Gets the value of the orderid property.
117 *
118 * @return possible object is
119 * {@link String }
120 */
121 public String getOrderid() {
122 return orderid;
123 }
124
125 /**
126 * Sets the value of the orderid property.
127 *
128 * @param value allowed object is
129 * {@link String }
130 */
131 public void setOrderid(String value) {
132 this.orderid = value;
133 }
134
135 }
+0
-78
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/Parent.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlElementWrapper;
6 import javax.xml.bind.annotation.XmlRootElement;
7 import javax.xml.bind.annotation.XmlType;
8 import java.util.ArrayList;
9 import java.util.List;
10
11 @XmlRootElement
12 @XmlAccessorType(XmlAccessType.FIELD)
13 @XmlType(name = "parentType")
14 public class Parent {
15 private String name;
16
17 @XmlElementWrapper(name = "children")
18 @XmlElement(name = "child")
19 private List<Child> children = new ArrayList<Child>();
20
21 public Parent() {
22
23 }
24
25 public Parent(final String name) {
26 this.name = name;
27 }
28
29 /**
30 * Get the name.
31 *
32 * @return the name.
33 */
34 public String getName() {
35 return name;
36 }
37
38 /**
39 * Set the name.
40 *
41 * @param name The name to set.
42 */
43 public void setName(String name) {
44 this.name = name;
45 }
46
47 /**
48 * Get the children.
49 *
50 * @return the children.
51 */
52 public List<Child> getChildren() {
53 return children;
54 }
55
56 /**
57 * Set the children.
58 *
59 * @param children The children to set.
60 */
61 public void setChildren(List<Child> children) {
62 this.children = children;
63 }
64
65 public void addChild(Child child) {
66 child.setParent(this);
67 this.children.add(child);
68 }
69
70 public static Parent createTestParent(String name) {
71 Parent parent = new Parent(name);
72 parent.addChild(new Child("Child 1"));
73 parent.addChild(new Child("Child 2"));
74 parent.addChild(new Child("Child 3"));
75 return parent;
76 }
77 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/QualityFactorResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.HeaderParam;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8
9 @Path("/test")
10 public class QualityFactorResource {
11
12 private static Logger logger = Logger.getLogger(QualityFactorResource.class.getName());
13
14 @GET
15 @Produces({"application/json", "application/xml"})
16 public QualityFactorThing get(@HeaderParam("Accept") String accept) {
17 logger.info(accept);
18 QualityFactorThing thing = new QualityFactorThing();
19 thing.setName("Bill");
20 return thing;
21 }
22 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/QualityFactorThing.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class QualityFactorThing {
6 private String name;
7
8 public String getName() {
9 return name;
10 }
11
12 public void setName(String name) {
13 this.name = name;
14 }
15 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/SeeAlsoAnnotationBaseFoo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlSeeAlso;
3
4 @XmlSeeAlso(SeeAlsoAnnotationRealFoo.class)
5 public class SeeAlsoAnnotationBaseFoo {
6 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/SeeAlsoAnnotationFooIntf.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlSeeAlso;
3
4 @XmlSeeAlso(SeeAlsoAnnotationRealFoo.class)
5 public interface SeeAlsoAnnotationFooIntf {
6 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/SeeAlsoAnnotationRealFoo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class SeeAlsoAnnotationRealFoo extends SeeAlsoAnnotationBaseFoo implements SeeAlsoAnnotationFooIntf {
6 private String name;
7
8 public String getName() {
9 return name;
10 }
11
12 public void setName(String name) {
13 this.name = name;
14 }
15 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/SeeAlsoAnnotationResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.PUT;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.core.MediaType;
8
9 @Path("/see")
10 public class SeeAlsoAnnotationResource {
11 @Path("/intf")
12 @PUT
13 @Consumes(MediaType.APPLICATION_XML)
14 public void put(SeeAlsoAnnotationFooIntf foo) {
15 Assert.assertTrue("The input parameter for the resource has wrong type", foo instanceof SeeAlsoAnnotationRealFoo);
16 Assert.assertEquals("The foo object has unexpected content", ((SeeAlsoAnnotationRealFoo) foo).getName(), "bill");
17 }
18
19 @Path("base")
20 @PUT
21 @Consumes(MediaType.APPLICATION_XML)
22 public void put(SeeAlsoAnnotationBaseFoo foo) {
23 Assert.assertTrue("The input parameter for the resource has wrong type", foo instanceof SeeAlsoAnnotationRealFoo);
24 Assert.assertEquals("The foo object has unexpected content", ((SeeAlsoAnnotationRealFoo) foo).getName(), "bill");
25 }
26 }
+0
-134
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/ShipTo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.Unmarshaller;
3 import javax.xml.bind.annotation.XmlAccessType;
4 import javax.xml.bind.annotation.XmlAccessorType;
5 import javax.xml.bind.annotation.XmlElement;
6 import javax.xml.bind.annotation.XmlRootElement;
7 import javax.xml.bind.annotation.XmlTransient;
8 import javax.xml.bind.annotation.XmlType;
9
10 @XmlRootElement(name = "shipto")
11 @XmlAccessorType(XmlAccessType.FIELD)
12 @XmlType(name = "shiptotype", propOrder = {
13 "name",
14 "address",
15 "city",
16 "country"
17 })
18 public class ShipTo {
19 @XmlElement(required = true)
20 private String name;
21
22 @XmlElement(required = true)
23 private String address;
24
25 @XmlElement(required = true)
26 private String city;
27
28 @XmlElement(required = true)
29 private String country;
30
31 @XmlTransient
32 private Order order;
33
34 /**
35 * Get the name.
36 *
37 * @return the name.
38 */
39 public String getName() {
40 return name;
41 }
42
43 /**
44 * Set the name.
45 *
46 * @param name The name to set.
47 */
48 public void setName(String name) {
49 this.name = name;
50 }
51
52 /**
53 * Get the address.
54 *
55 * @return the address.
56 */
57 public String getAddress() {
58 return address;
59 }
60
61 /**
62 * Set the address.
63 *
64 * @param address The address to set.
65 */
66 public void setAddress(String address) {
67 this.address = address;
68 }
69
70 /**
71 * Get the city.
72 *
73 * @return the city.
74 */
75 public String getCity() {
76 return city;
77 }
78
79 /**
80 * Set the city.
81 *
82 * @param city The city to set.
83 */
84 public void setCity(String city) {
85 this.city = city;
86 }
87
88 /**
89 * Get the country.
90 *
91 * @return the country.
92 */
93 public String getCountry() {
94 return country;
95 }
96
97 /**
98 * Set the country.
99 *
100 * @param country The country to set.
101 */
102 public void setCountry(String country) {
103 this.country = country;
104 }
105
106 /**
107 * Get the order.
108 *
109 * @return the order.
110 */
111 public Order getOrder() {
112 return order;
113 }
114
115 /**
116 * Set the order.
117 *
118 * @param order The order to set.
119 */
120 public void setOrder(Order order) {
121 this.order = order;
122 }
123
124 /**
125 * JAXB Callback method used to reassociate the item with the owning Order.
126 *
127 * @param unmarshaller the JAXB {@link Unmarshaller}.
128 * @param parent the owning {@link Contact} instance.
129 */
130 public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
131 this.setOrder((Order) order);
132 }
133 }
+0
-127
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/Shiptotype.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlType;
6
7
8 /**
9 * <p>Java class for shiptotype complex type.
10 * <p>
11 * <p>The following schema fragment specifies the expected content contained within this class.
12 * <p>
13 * <pre>
14 * &lt;complexType name="shiptotype">
15 * &lt;complexContent>
16 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
17 * &lt;sequence>
18 * &lt;element name="name" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}stringtype"/>
19 * &lt;element name="address" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}stringtype"/>
20 * &lt;element name="city" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}stringtype"/>
21 * &lt;element name="country" type="{http://jboss.org/resteasy/test/providers/jaxb/generated/order}stringtype"/>
22 * &lt;/sequence>
23 * &lt;/restriction>
24 * &lt;/complexContent>
25 * &lt;/complexType>
26 * </pre>
27 */
28 @XmlAccessorType(XmlAccessType.FIELD)
29 @XmlType(name = "shiptotype", propOrder = {
30 "name",
31 "address",
32 "city",
33 "country"
34 })
35 public class Shiptotype {
36
37 @XmlElement(required = true)
38 protected String name;
39 @XmlElement(required = true)
40 protected String address;
41 @XmlElement(required = true)
42 protected String city;
43 @XmlElement(required = true)
44 protected String country;
45
46 /**
47 * Gets the value of the name property.
48 *
49 * @return possible object is
50 * {@link String }
51 */
52 public String getName() {
53 return name;
54 }
55
56 /**
57 * Sets the value of the name property.
58 *
59 * @param value allowed object is
60 * {@link String }
61 */
62 public void setName(String value) {
63 this.name = value;
64 }
65
66 /**
67 * Gets the value of the address property.
68 *
69 * @return possible object is
70 * {@link String }
71 */
72 public String getAddress() {
73 return address;
74 }
75
76 /**
77 * Sets the value of the address property.
78 *
79 * @param value allowed object is
80 * {@link String }
81 */
82 public void setAddress(String value) {
83 this.address = value;
84 }
85
86 /**
87 * Gets the value of the city property.
88 *
89 * @return possible object is
90 * {@link String }
91 */
92 public String getCity() {
93 return city;
94 }
95
96 /**
97 * Sets the value of the city property.
98 *
99 * @param value allowed object is
100 * {@link String }
101 */
102 public void setCity(String value) {
103 this.city = value;
104 }
105
106 /**
107 * Gets the value of the country property.
108 *
109 * @return possible object is
110 * {@link String }
111 */
112 public String getCountry() {
113 return country;
114 }
115
116 /**
117 * Sets the value of the country property.
118 *
119 * @param value allowed object is
120 * {@link String }
121 */
122 public void setCountry(String value) {
123 this.country = value;
124 }
125
126 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/StatsProxy.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.plugins.stats.RegistryData;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7
8 @Path("/resteasy/registry")
9 public interface StatsProxy {
10 @GET
11 @Produces("application/xml")
12 RegistryData get();
13 }
+0
-43
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/StatsResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.PUT;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.DELETE;
6 import javax.ws.rs.HEAD;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.Consumes;
9
10 @Path("/")
11 public class StatsResource {
12 @Path("locator")
13 public Object getLocator() {
14 return null;
15 }
16
17 @Path("entry/{foo:.*}")
18 @PUT
19 @Produces("text/xml")
20 @Consumes("application/json")
21 public void put() {
22
23 }
24
25 @Path("entry/{foo:.*}")
26 @POST
27 @Produces("text/xml")
28 @Consumes("application/json")
29 public void post() {
30
31 }
32
33 @DELETE
34 @Path("resource")
35 public void delete() {
36 }
37
38 @HEAD
39 @Path("resource")
40 public void head() {
41 }
42 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/StreamResetPerson.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "person")
8 @XmlAccessorType(XmlAccessType.PROPERTY)
9 public class StreamResetPerson {
10 private String name;
11
12 @XmlAttribute
13 public String getName() {
14 return name;
15 }
16
17 public void setName(String name) {
18 this.name = name;
19 }
20 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/StreamResetPlace.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "place")
8 @XmlAccessorType(XmlAccessType.PROPERTY)
9 public class StreamResetPlace {
10 private String name;
11
12 @XmlAttribute
13 public String getName() {
14 return name;
15 }
16
17 public void setName(String name) {
18 this.name = name;
19 }
20 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/StreamResetResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/test")
7 public class StreamResetResource {
8 @GET
9 @Produces("application/xml")
10 public String get() {
11 return "<person name=\"bill\"/>";
12 }
13 }
+0
-48
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/StringCharsetResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.StreamingOutput;
7 import java.io.IOException;
8 import java.io.OutputStream;
9 import java.io.PrintStream;
10
11 @Path("/charset")
12 public class StringCharsetResource {
13 @GET
14 @Path("test.xml")
15 @Produces("application/xml")
16 public StringCharsetRespond getTestXML() {
17 String test = "Test " + (char) 353 + (char) 273 + (char) 382 + (char) 269;
18 return new StringCharsetRespond(test);
19 }
20
21 @GET
22 @Path("test.json")
23 @Produces("application/json;charset=UTF-8")
24 public StringCharsetRespond getTestJSON() {
25 return new StringCharsetRespond("Test " + (char) 353 + (char) 273 + (char) 382 + (char) 269);
26 }
27
28 @GET
29 @Path("test.html")
30 @Produces("text/html;charset=UTF-8")
31 public String getTestHTML() {
32 return "<html><body>Test " + (char) 353 + (char) 273 + (char) 382 + (char) 269 + "</body></html>";
33 }
34
35 @GET
36 @Path("test_stream.html")
37 @Produces("text/html;charset=UTF-8")
38 public StreamingOutput getTestStream() {
39 return new StreamingOutput() {
40 public void write(OutputStream outputStream) throws IOException, WebApplicationException {
41 PrintStream writer = new PrintStream(outputStream, true, "UTF-8");
42 writer.println("<html><body>Test " + (char) 353 + (char) 273 + (char) 382 + (char) 269 + "</body></html>");
43 }
44 };
45 }
46
47 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/StringCharsetRespond.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlElement;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement(name = "respond_test")
6 public class StringCharsetRespond {
7 protected String word;
8
9 public StringCharsetRespond() {
10
11 }
12
13 public StringCharsetRespond(final String _word) {
14 this.word = _word;
15 }
16
17 @XmlElement(name = "word")
18 public String getWord() {
19 return word;
20 }
21
22 public void setWord(String word) {
23 this.word = word;
24 }
25 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlEnumParamLocation.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlEnum;
3 import javax.xml.bind.annotation.XmlEnumValue;
4
5 @XmlEnum
6 public enum XmlEnumParamLocation {
7
8 @XmlEnumValue("north")
9 NORTH("north"),
10 @XmlEnumValue("south")
11 SOUTH("south"),
12 @XmlEnumValue("east")
13 EAST("east"),
14 @XmlEnumValue("west")
15 WEST("west");
16 private final String value;
17
18 XmlEnumParamLocation(final String v) {
19 value = v;
20 }
21
22 public String value() {
23 return value;
24 }
25
26 public static XmlEnumParamLocation fromValue(String v) {
27 for (XmlEnumParamLocation c : XmlEnumParamLocation.values()) {
28 if (c.value.equals(v)) {
29 return c;
30 }
31 }
32 throw new IllegalArgumentException(v.toString());
33 }
34
35 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlEnumParamResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.QueryParam;
6
7 @Path("enum")
8 public class XmlEnumParamResource {
9 @GET
10 @Produces("text/plain")
11 public String get(@QueryParam("loc") XmlEnumParamLocation loc) {
12 return loc.toString();
13 }
14 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlHeaderDecorator.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.DecorateTypes;
3 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
4
5 import javax.ws.rs.core.MediaType;
6 import javax.xml.bind.Marshaller;
7 import java.lang.annotation.Annotation;
8
9 @DecorateTypes("application/json")
10 public class XmlHeaderDecorator implements DecoratorProcessor<Marshaller, XmlHeaderJunkIntf> {
11 public Marshaller decorate(Marshaller target, XmlHeaderJunkIntf annotation, Class type, Annotation[] annotations, MediaType mediaType) {
12 throw new RuntimeException("FAILURE!!!!");
13 }
14 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlHeaderDecorator2.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.DecorateTypes;
3 import org.jboss.resteasy.spi.interception.DecoratorProcessor;
4 import org.junit.Assert;
5
6 import javax.ws.rs.core.MediaType;
7 import java.lang.annotation.Annotation;
8
9 @DecorateTypes("application/xml")
10 public class XmlHeaderDecorator2 implements DecoratorProcessor<Assert, XmlHeaderJunk2Intf> {
11 public Assert decorate(Assert target, XmlHeaderJunk2Intf annotation, Class type, Annotation[] annotations, MediaType mediaType) {
12 throw new RuntimeException("FAILURE!!!!");
13 }
14 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlHeaderJunk2Intf.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.Decorator;
3 import org.junit.Assert;
4
5 /**
6 * Test correct media type, but incorrect type
7 */
8 @Decorator(processor = XmlHeaderDecorator.class, target = Assert.class)
9 public @interface XmlHeaderJunk2Intf {
10 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlHeaderJunkIntf.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.Decorator;
3
4 import javax.xml.bind.Marshaller;
5
6 /**
7 * Test correct type (Marshaller), but incorrect media type
8 */
9 @Decorator(processor = XmlHeaderDecorator.class, target = Marshaller.class)
10 public @interface XmlHeaderJunkIntf {
11 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlHeaderResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.Stylesheet;
3 import org.jboss.resteasy.annotations.providers.jaxb.XmlHeader;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8
9 @Path("/test")
10 public class XmlHeaderResource {
11
12 @GET
13 @Path("/header")
14 @Produces("application/xml")
15 @XmlHeader("<?xml-stylesheet type='text/xsl' href='${baseuri}foo.xsl' ?>")
16 public XmlHeaderThing get() {
17 XmlHeaderThing thing = new XmlHeaderThing();
18 thing.setName("bill");
19 return thing;
20 }
21
22 @GET
23 @Path("/stylesheet")
24 @Produces("application/xml")
25 @Stylesheet(type = "text/css", href = "${basepath}foo.xsl")
26 @XmlHeaderJunkIntf
27 public XmlHeaderThing getStyle() {
28 XmlHeaderThing thing = new XmlHeaderThing();
29 thing.setName("bill");
30 return thing;
31 }
32 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlHeaderThing.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 @XmlHeaderJunkIntf
6 @XmlHeaderJunk2Intf
7 public class XmlHeaderThing {
8 private String name;
9
10 public String getName() {
11 return name;
12 }
13
14 public void setName(String name) {
15 this.name = name;
16 }
17 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlJavaTypeAdapterAlien.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
3
4 @XmlJavaTypeAdapter(XmlJavaTypeAdapterAlienAdapter.class)
5 public class XmlJavaTypeAdapterAlien {
6 private String name;
7
8 public String getName() {
9 return name;
10 }
11
12 public void setName(String name) {
13 this.name = name;
14 }
15
16 @Override
17 public boolean equals(Object o) {
18 if (!(o instanceof XmlJavaTypeAdapterAlien)) {
19 return false;
20 }
21 return name.equals(XmlJavaTypeAdapterAlien.class.cast(o).name);
22 }
23
24 @Override
25 public int hashCode() {
26 return name.hashCode();
27 }
28 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlJavaTypeAdapterAlienAdapter.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.xml.bind.annotation.adapters.XmlAdapter;
5
6 public class XmlJavaTypeAdapterAlienAdapter extends XmlAdapter<XmlJavaTypeAdapterHuman, XmlJavaTypeAdapterAlien> {
7 public static int marshalCounter;
8 public static int unmarshalCounter;
9 private static Logger logger = Logger.getLogger(XmlJavaTypeAdapterResource.class.getName());
10
11 public static void reset() {
12 marshalCounter = 0;
13 unmarshalCounter = 0;
14 logger.info("reset()");
15 }
16
17 @Override
18 public XmlJavaTypeAdapterHuman marshal(XmlJavaTypeAdapterAlien alien) throws Exception {
19 logger.info("Entering AlienAdapter.marshal()");
20 marshalCounter++;
21 XmlJavaTypeAdapterHuman human = new XmlJavaTypeAdapterHuman();
22 human.setName(reverse(alien.getName()));
23 return human;
24 }
25
26 @Override
27 public XmlJavaTypeAdapterAlien unmarshal(XmlJavaTypeAdapterHuman human) throws Exception {
28 logger.info("Entering AlienAdapter.unmarshal()");
29 unmarshalCounter++;
30 XmlJavaTypeAdapterAlien alien = new XmlJavaTypeAdapterAlien();
31 alien.setName(reverse(human.getName()));
32 return alien;
33 }
34
35 protected static String reverse(String s) {
36 return new StringBuilder(s).reverse().toString();
37 }
38 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlJavaTypeAdapterFoo.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
7
8 @XmlRootElement
9 @XmlAccessorType(XmlAccessType.FIELD)
10 public class XmlJavaTypeAdapterFoo {
11 @XmlJavaTypeAdapter(XmlJavaTypeAdapterAlienAdapter.class)
12 @XmlElement
13 XmlJavaTypeAdapterAlien alien;
14
15 public void setName(String name) {
16 alien = new XmlJavaTypeAdapterAlien();
17 alien.setName(name);
18 }
19
20 public String toString() {
21 return "Foo[Alien[" + alien.getName() + "]]: " + super.toString();
22 }
23
24 @Override
25 public boolean equals(Object o) {
26 if (!(o instanceof XmlJavaTypeAdapterFoo)) {
27 return false;
28 }
29 XmlJavaTypeAdapterFoo foo = XmlJavaTypeAdapterFoo.class.cast(o);
30 return alien.getName().equals(foo.alien.getName());
31 }
32
33 @Override
34 public int hashCode() {
35 return alien.hashCode();
36 }
37
38 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlJavaTypeAdapterHuman.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "human")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class XmlJavaTypeAdapterHuman {
10 @XmlElement
11 private String name;
12
13 public String getName() {
14 return name;
15 }
16
17 public void setName(String name) {
18 this.name = name;
19 }
20 }
+0
-82
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlJavaTypeAdapterResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Map;
11
12 @Path("")
13 public class XmlJavaTypeAdapterResource {
14
15 private static Logger logger = Logger.getLogger(XmlJavaTypeAdapterResource.class.getName());
16
17 @POST
18 @Path("foo/foo")
19 @Consumes("application/xml")
20 @Produces("application/xml")
21 public XmlJavaTypeAdapterFoo foo(XmlJavaTypeAdapterFoo foo) {
22 logger.info("foo: \"" + foo + "\"");
23 return foo;
24 }
25
26 @POST
27 @Path("human")
28 @Produces("text/plain")
29 public String human(XmlJavaTypeAdapterHuman human) {
30 logger.info("human: \"" + human.getName() + "\"");
31 return human.getName();
32 }
33
34 @POST
35 @Path("alien")
36 @Produces("text/plain")
37 public String alien(XmlJavaTypeAdapterAlien alien) {
38 logger.info("human: \"" + alien.getName() + "\"");
39 return alien.getName();
40 }
41
42 @POST
43 @Path("list/alien")
44 @Consumes("application/xml")
45 @Produces("application/xml")
46 public List<XmlJavaTypeAdapterAlien> listAlien(List<XmlJavaTypeAdapterAlien> list) {
47 logger.info("entering listAlien()");
48 return list;
49 }
50
51 @POST
52 @Path("array/alien")
53 @Consumes("application/xml")
54 @Produces("application/xml")
55 public XmlJavaTypeAdapterAlien[] arrayAlien(XmlJavaTypeAdapterAlien[] array) {
56 logger.info("entering arrayAlien()");
57 return array;
58 }
59
60 @POST
61 @Path("map/alien")
62 @Consumes("application/xml")
63 @Produces("application/xml")
64 public Map<String, XmlJavaTypeAdapterAlien> mapAlien(Map<String, XmlJavaTypeAdapterAlien> map) {
65 logger.info("entering mapAlien()");
66 return map;
67 }
68
69 @POST
70 @Path("list/human")
71 @Consumes("application/xml")
72 @Produces("text/plain")
73 public String listHuman(List<XmlJavaTypeAdapterHuman> list) {
74 String result = "";
75 for (Iterator<XmlJavaTypeAdapterHuman> it = list.iterator(); it.hasNext(); ) {
76 String name = it.next().getName();
77 result += "|" + name;
78 }
79 return result;
80 }
81 }
+0
-57
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlJaxbProvidersHelper.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2
3 import org.jboss.resteasy.core.ExceptionAdapter;
4
5 import javax.ws.rs.core.MediaType;
6 import javax.xml.bind.JAXBContext;
7 import javax.xml.bind.JAXBElement;
8 import javax.xml.bind.JAXBException;
9 import javax.xml.bind.Unmarshaller;
10 import javax.xml.stream.XMLStreamReader;
11 import java.io.InputStream;
12
13 public final class XmlJaxbProvidersHelper {
14
15 /**
16 * An HTTP Header than can be passed in order to have the XML response formatted.
17 */
18 public static final String FORMAT_XML_HEADER = "X-Xml-Formatted";
19
20 private XmlJaxbProvidersHelper() {
21 }
22
23 public static <T> JAXBElement<T> unmarshall(Class<T> type, InputStream entityStream) {
24 XMLStreamReader reader = XmlStreamFactory.getXMLStreamReader(entityStream);
25 return unmarshall(type, entityStream, reader);
26 }
27
28 public static <T> JAXBElement<T> unmarshall(Class<T> type,
29 InputStream entityStream,
30 XMLStreamReader reader) {
31 JAXBContext jaxb = JAXBCache.instance().getJAXBContext(type);
32 return unmarshall(jaxb, type, entityStream, reader);
33 }
34
35 public static <T> JAXBElement<T> unmarshall(JAXBContext jaxb,
36 Class<T> type,
37 InputStream entityStream,
38 XMLStreamReader reader) {
39 try {
40 Unmarshaller unmarshaller = jaxb.createUnmarshaller();
41 JAXBElement<T> e = unmarshaller.unmarshal(reader, type);
42 return e;
43 } catch (JAXBException e) {
44 throw new ExceptionAdapter(e);
45 }
46 }
47
48 public static String getCharset(final MediaType mediaType) {
49 if (mediaType != null) {
50 return mediaType.getParameters().get("charset");
51 }
52 return null;
53 }
54
55
56 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlJaxbProvidersOrderClient.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.Response;
10
11 @Path("/jaxb/orders")
12 @Consumes({"application/xml"})
13 @Produces({"application/xml"})
14 public interface XmlJaxbProvidersOrderClient {
15
16 @GET
17 @Path("/{orderId}")
18 Order getOrderById(@PathParam("orderId") String orderId);
19
20 @POST
21 Response createOrder(Ordertype order);
22
23 @PUT
24 @Path("/{orderId}")
25 Order updateOrder(Order order, @PathParam("orderId") String orderId);
26
27 }
+0
-53
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlJaxbProvidersOrderResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.GET;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.PUT;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.PathParam;
10 import javax.ws.rs.Produces;
11 import javax.ws.rs.core.Response;
12 import java.io.InputStream;
13
14 @Path("/jaxb/orders")
15 @Consumes({"application/xml", "application/fastinfoset", "application/json"})
16 @Produces({"application/xml", "application/fastinfoset", "application/json"})
17 public class XmlJaxbProvidersOrderResource {
18
19 @GET
20 @Path("/{orderId}")
21 public Order getOrderById(@PathParam("orderId") String orderId) {
22 Order order = getOrderFromFileSystem(orderId);
23 return order;
24 }
25
26 @POST
27 public Response createOrder(Order order) {
28 return null;
29 }
30
31 @PUT
32 @Path("/{orderId}")
33 public Order updateOrder(Order order, @PathParam("orderId") String orderId) {
34 Item updatedItem = order.getItem(0);
35 updatedItem.setQuantity(updatedItem.getQuantity() + 1);
36 Item item = new Item();
37 item.setNote("New Item");
38 item.setPrice(21.99d);
39 item.setQuantity(1);
40 item.setTitle("New Thing");
41 order.addItem(item);
42 return order;
43 }
44
45 private Order getOrderFromFileSystem(String orderId) {
46 StringBuilder order = new StringBuilder("orders/");
47 order.append(orderId).append(".xml");
48 InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("org/jboss/resteasy/test/providers/jaxb/" + order.toString());
49 Assert.assertNotEquals(null, in);
50 return XmlJaxbProvidersHelper.unmarshall(Order.class, in).getValue();
51 }
52 }
+0
-43
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/XmlStreamFactory.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource;
1
2 import org.jboss.resteasy.core.ExceptionAdapter;
3
4 import javax.xml.stream.XMLInputFactory;
5 import javax.xml.stream.XMLOutputFactory;
6 import javax.xml.stream.XMLStreamException;
7 import javax.xml.stream.XMLStreamReader;
8 import javax.xml.stream.XMLStreamWriter;
9 import java.io.BufferedInputStream;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12
13 /**
14 * A XmlStreamFactory.
15 *
16 * @author <a href="ryan@damnhandy.com">Ryan J. McDonough</a>
17 * @version $Revision:$
18 */
19 public final class XmlStreamFactory {
20
21 private XmlStreamFactory() {
22
23 }
24
25 public static XMLStreamWriter getXMLStreamWriter(OutputStream out) {
26 try {
27 return XMLOutputFactory.newInstance().createXMLStreamWriter(out);
28 } catch (XMLStreamException e) {
29 throw new ExceptionAdapter(e);
30 }
31 }
32
33 static XMLStreamReader getXMLStreamReader(InputStream entityStream) {
34 InputStream in = new BufferedInputStream(entityStream, 2048);
35 try {
36 XMLInputFactory factory = XMLInputFactory.newInstance();
37 return factory.createXMLStreamReader(in);
38 } catch (XMLStreamException e) {
39 throw new ExceptionAdapter(e);
40 }
41 }
42 }
+0
-108
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/parsing/ObjectFactory.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource.parsing;
1
2 import javax.xml.bind.JAXBElement;
3 import javax.xml.bind.annotation.XmlElementDecl;
4 import javax.xml.bind.annotation.XmlRegistry;
5 import javax.xml.datatype.XMLGregorianCalendar;
6 import javax.xml.namespace.QName;
7
8
9 /**
10 * This object contains factory methods for each
11 * Java content interface and Java element interface
12 * generated in the mil.navy.tsts.datacollection.parseRS package.
13 * <p>An ObjectFactory allows you to programatically
14 * construct new instances of the Java representation
15 * for XML content. The Java representation of XML
16 * content can consist of schema derived interfaces
17 * and classes representing the binding of schema
18 * type definitions, element declarations and model
19 * groups. Factory methods for each of these are
20 * provided in this class.
21 */
22 @XmlRegistry
23 public class ObjectFactory {
24
25 private static final QName _DataCollectionPackage_QNAME = new QName("http://www.example.org/ParsingDataCollectionPackage", "ParsingDataCollectionPackage");
26 private static final QName _DataCollectionRecord_QNAME = new QName("http://www.example.org/ParsingDataCollectionPackage", "ParsingDataCollectionRecord");
27 private static final QName _SourceID_QNAME = new QName("http://www.example.org/ParsingDataCollectionPackage", "sourceID");
28 private static final QName _Timestamp_QNAME = new QName("http://www.example.org/ParsingDataCollectionPackage", "timestamp");
29 private static final QName _EventID_QNAME = new QName("http://www.example.org/ParsingDataCollectionPackage", "eventID");
30 private static final QName _CollectedData_QNAME = new QName("http://www.example.org/ParsingDataCollectionPackage", "collectedData");
31
32 /**
33 * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: mil.navy.tsts.datacollection.parseRS
34 */
35 public ObjectFactory() {
36 }
37
38 /**
39 * Create an instance of {@link ParsingDataCollectionPackage }
40 */
41 public ParsingDataCollectionPackage createDataCollectionPackage() {
42 return new ParsingDataCollectionPackage();
43 }
44
45 /**
46 * Create an instance of {@link ParsingDataCollectionPackage.DataRecords }
47 */
48 public ParsingDataCollectionPackage.DataRecords createDataCollectionPackageDataRecords() {
49 return new ParsingDataCollectionPackage.DataRecords();
50 }
51
52 /**
53 * Create an instance of {@link ParsingDataCollectionRecord }
54 */
55 public ParsingDataCollectionRecord createDataCollectionRecord() {
56 return new ParsingDataCollectionRecord();
57 }
58
59 /**
60 * Create an instance of {@link JAXBElement }{@code <}{@link ParsingDataCollectionPackage }{@code >}}
61 */
62 @XmlElementDecl(namespace = "http://www.example.org/ParsingDataCollectionPackage", name = "ParsingDataCollectionPackage")
63 public JAXBElement<ParsingDataCollectionPackage> createDataCollectionPackage(ParsingDataCollectionPackage value) {
64 return new JAXBElement<ParsingDataCollectionPackage>(_DataCollectionPackage_QNAME, ParsingDataCollectionPackage.class, null, value);
65 }
66
67 /**
68 * Create an instance of {@link JAXBElement }{@code <}{@link ParsingDataCollectionRecord }{@code >}}
69 */
70 @XmlElementDecl(namespace = "http://www.example.org/ParsingDataCollectionPackage", name = "ParsingDataCollectionRecord")
71 public JAXBElement<ParsingDataCollectionRecord> createDataCollectionRecord(ParsingDataCollectionRecord value) {
72 return new JAXBElement<ParsingDataCollectionRecord>(_DataCollectionRecord_QNAME, ParsingDataCollectionRecord.class, null, value);
73 }
74
75 /**
76 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
77 */
78 @XmlElementDecl(namespace = "http://www.example.org/ParsingDataCollectionPackage", name = "sourceID")
79 public JAXBElement<String> createSourceID(String value) {
80 return new JAXBElement<String>(_SourceID_QNAME, String.class, null, value);
81 }
82
83 /**
84 * Create an instance of {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >}}
85 */
86 @XmlElementDecl(namespace = "http://www.example.org/ParsingDataCollectionPackage", name = "timestamp")
87 public JAXBElement<XMLGregorianCalendar> createTimestamp(XMLGregorianCalendar value) {
88 return new JAXBElement<XMLGregorianCalendar>(_Timestamp_QNAME, XMLGregorianCalendar.class, null, value);
89 }
90
91 /**
92 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
93 */
94 @XmlElementDecl(namespace = "http://www.example.org/ParsingDataCollectionPackage", name = "eventID")
95 public JAXBElement<String> createEventID(String value) {
96 return new JAXBElement<String>(_EventID_QNAME, String.class, null, value);
97 }
98
99 /**
100 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
101 */
102 @XmlElementDecl(namespace = "http://www.example.org/ParsingDataCollectionPackage", name = "collectedData")
103 public JAXBElement<String> createCollectedData(String value) {
104 return new JAXBElement<String>(_CollectedData_QNAME, String.class, null, value);
105 }
106
107 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/parsing/ParsingAbstractData.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource.parsing;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlSeeAlso;
5 import javax.xml.bind.annotation.XmlType;
6
7 @XmlAccessorType(XmlAccessType.FIELD)
8 @XmlType(name = "ParsingAbstractData")
9 @XmlSeeAlso(ParsingDataCollectionPackage.class)
10 public class ParsingAbstractData {
11 }
+0
-173
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/parsing/ParsingDataCollectionPackage.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource.parsing;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlType;
6 import java.util.ArrayList;
7 import java.util.List;
8
9
10 /**
11 * <p>Java class for ParsingDataCollectionPackage complex type.
12 * <p>
13 * <p>The following schema fragment specifies the expected content contained within this class.
14 * <p>
15 * <pre>
16 * &lt;complexType name="ParsingDataCollectionPackage">
17 * &lt;complexContent>
18 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
19 * &lt;sequence>
20 * &lt;element name="sourceID" type="{http://www.w3.org/2001/XMLSchema}string"/>
21 * &lt;element name="eventID" type="{http://www.w3.org/2001/XMLSchema}string"/>
22 * &lt;element name="dataRecords">
23 * &lt;complexType>
24 * &lt;complexContent>
25 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
26 * &lt;sequence>
27 * &lt;element name="ParsingDataCollectionRecord" type="{http://www.example.org/DataCollectionPackage}ParsingDataCollectionRecord" maxOccurs="unbounded"/>
28 * &lt;/sequence>
29 * &lt;/restriction>
30 * &lt;/complexContent>
31 * &lt;/complexType>
32 * &lt;/element>
33 * &lt;/sequence>
34 * &lt;/restriction>
35 * &lt;/complexContent>
36 * &lt;/complexType>
37 * </pre>
38 */
39 @XmlAccessorType(XmlAccessType.FIELD)
40 @XmlType(name = "ParsingDataCollectionPackage",
41 propOrder = {
42 "sourceID",
43 "eventID",
44 "dataRecords"
45 })
46 public class ParsingDataCollectionPackage extends ParsingAbstractData {
47
48 @XmlElement(name = "sourceID", required = true)
49 protected String sourceID;
50 @XmlElement(required = true)
51 protected String eventID;
52 @XmlElement(required = true)
53 protected ParsingDataCollectionPackage.DataRecords dataRecords;
54
55 /**
56 * Gets the value of the sourceID property.
57 *
58 * @return possible object is
59 * {@link String }
60 */
61 public String getSourceID() {
62 return sourceID;
63 }
64
65 /**
66 * Sets the value of the sourceID property.
67 *
68 * @param value allowed object is
69 * {@link String }
70 */
71 public void setSourceID(String value) {
72 this.sourceID = value;
73 }
74
75 /**
76 * Gets the value of the eventID property.
77 *
78 * @return possible object is
79 * {@link String }
80 */
81 public String getEventID() {
82 return eventID;
83 }
84
85 /**
86 * Sets the value of the eventID property.
87 *
88 * @param value allowed object is
89 * {@link String }
90 */
91 public void setEventID(String value) {
92 this.eventID = value;
93 }
94
95 /**
96 * Gets the value of the dataRecords property.
97 *
98 * @return possible object is
99 * {@link ParsingDataCollectionPackage.DataRecords }
100 */
101 public ParsingDataCollectionPackage.DataRecords getDataRecords() {
102 return dataRecords;
103 }
104
105 /**
106 * Sets the value of the dataRecords property.
107 *
108 * @param value allowed object is
109 * {@link ParsingDataCollectionPackage.DataRecords }
110 */
111 public void setDataRecords(ParsingDataCollectionPackage.DataRecords value) {
112 this.dataRecords = value;
113 }
114
115
116 /**
117 * <p>Java class for anonymous complex type.
118 * <p>
119 * <p>The following schema fragment specifies the expected content contained within this class.
120 * <p>
121 * <pre>
122 * &lt;complexType>
123 * &lt;complexContent>
124 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
125 * &lt;sequence>
126 * &lt;element name="ParsingDataCollectionRecord" type="{http://www.example.org/DataCollectionPackage}ParsingDataCollectionRecord" maxOccurs="unbounded"/>
127 * &lt;/sequence>
128 * &lt;/restriction>
129 * &lt;/complexContent>
130 * &lt;/complexType>
131 * </pre>
132 */
133 @XmlAccessorType(XmlAccessType.FIELD)
134 @XmlType(name = "", propOrder = {
135 "dataCollectionRecord"
136 })
137 public static class DataRecords {
138
139 @XmlElement(name = "ParsingDataCollectionRecord", required = true)
140 protected List<ParsingDataCollectionRecord> dataCollectionRecord;
141
142 /**
143 * Gets the value of the dataCollectionRecord property.
144 * <p>
145 * <p>
146 * This accessor method returns a reference to the live list,
147 * not a snapshot. Therefore any modification you make to the
148 * returned list will be present inside the JAXB object.
149 * This is why there is not a <CODE>set</CODE> method for the dataCollectionRecord property.
150 * <p>
151 * <p>
152 * For example, to add a new item, do as follows:
153 * <pre>
154 * getDataCollectionRecord().add(newItem);
155 * </pre>
156 * <p>
157 * <p>
158 * <p>
159 * Objects of the following type(s) are allowed in the list
160 * {@link ParsingDataCollectionRecord }
161 */
162 public List<ParsingDataCollectionRecord> getDataCollectionRecord() {
163 if (dataCollectionRecord == null) {
164 dataCollectionRecord = new ArrayList<ParsingDataCollectionRecord>();
165 }
166 return this.dataCollectionRecord;
167 }
168
169
170 }
171
172 }
+0
-81
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/parsing/ParsingDataCollectionRecord.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource.parsing;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlType;
6 import javax.xml.datatype.XMLGregorianCalendar;
7
8
9 /**
10 * <p>Java class for ParsingDataCollectionRecord complex type.
11 * <p>
12 * <p>The following schema fragment specifies the expected content contained within this class.
13 * <p>
14 * <pre>
15 * &lt;complexType name="ParsingDataCollectionRecord">
16 * &lt;complexContent>
17 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
18 * &lt;sequence>
19 * &lt;element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
20 * &lt;element name="collectedData" type="{http://www.w3.org/2001/XMLSchema}string"/>
21 * &lt;/sequence>
22 * &lt;/restriction>
23 * &lt;/complexContent>
24 * &lt;/complexType>
25 * </pre>
26 */
27 @XmlAccessorType(XmlAccessType.FIELD)
28 @XmlType(name = "ParsingDataCollectionRecord",
29 propOrder = {
30 "timestamp",
31 "collectedData"
32 })
33 public class ParsingDataCollectionRecord {
34
35 @XmlElement(required = true)
36 protected XMLGregorianCalendar timestamp;
37 @XmlElement(required = true)
38 protected String collectedData;
39
40 /**
41 * Gets the value of the timestamp property.
42 *
43 * @return possible object is
44 * {@link XMLGregorianCalendar }
45 */
46 public XMLGregorianCalendar getTimestamp() {
47 return timestamp;
48 }
49
50 /**
51 * Sets the value of the timestamp property.
52 *
53 * @param value allowed object is
54 * {@link XMLGregorianCalendar }
55 */
56 public void setTimestamp(XMLGregorianCalendar value) {
57 this.timestamp = value;
58 }
59
60 /**
61 * Gets the value of the collectedData property.
62 *
63 * @return possible object is
64 * {@link String }
65 */
66 public String getCollectedData() {
67 return collectedData;
68 }
69
70 /**
71 * Sets the value of the collectedData property.
72 *
73 * @param value allowed object is
74 * {@link String }
75 */
76 public void setCollectedData(String value) {
77 this.collectedData = value;
78 }
79
80 }
+0
-72
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jaxb/resource/parsing/ParsingStoreResource.java less more
0 package org.jboss.resteasy.test.providers.jaxb.resource.parsing;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.Response;
7 import javax.ws.rs.core.Response.ResponseBuilder;
8 import javax.ws.rs.core.Response.Status;
9 import javax.xml.datatype.XMLGregorianCalendar;
10 import java.net.URI;
11 import java.net.URISyntaxException;
12 import java.sql.Timestamp;
13 import java.util.GregorianCalendar;
14
15 @Path("/")
16 public class ParsingStoreResource {
17 // this unitName matches the one defined in persistence.xml file
18 //@PersistenceContext(unitName="DataCollectionPU")
19 //EntityManager em;
20
21 @POST
22 @Consumes("application/xml")
23 @Path("storeXML/abstract")
24 public Response storeXMLAbstract(ParsingAbstractData dataCollectionPackage) {
25 return storeXML((ParsingDataCollectionPackage) dataCollectionPackage);
26 }
27
28 @POST
29 @Consumes("application/xml")
30 @Path("storeXML")
31 public Response storeXML(ParsingDataCollectionPackage dataCollectionPackage) {
32 String sourceID = dataCollectionPackage.getSourceID();
33 String eventID = dataCollectionPackage.getEventID();
34
35 if (dataCollectionPackage.getDataRecords() == null ||
36 dataCollectionPackage.getDataRecords().getDataCollectionRecord() == null) {
37 ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR);
38 builder.type("text/html");
39 builder.entity("<h3>No records included</h3>");
40 throw new WebApplicationException(builder.build());
41 }
42
43 for (ParsingDataCollectionRecord dr : dataCollectionPackage.getDataRecords().getDataCollectionRecord()) {
44
45 // JAXB datatype for dateTime is XMLGregorianCalendar, need to convert to the java.sql.Timestamp
46 XMLGregorianCalendar cal = dr.getTimestamp();
47 GregorianCalendar gregorianCalendar = cal.toGregorianCalendar();
48 long timeAsMillis = gregorianCalendar.getTimeInMillis();
49 Timestamp timestamp = new Timestamp(timeAsMillis);
50
51 // persist data here
52 }
53
54 URI createdURI = null;
55 try {
56 // Create a relative URI
57 createdURI = new URI("records");
58 } catch (URISyntaxException e) {
59 throw new WebApplicationException(Response.serverError().build());
60 }
61 // For a successful POST send a 201 CREATED with the URI of where to find the records
62 // The relative URI will be turned into an absolute URI based on the URI used to access
63 // this method.
64 //return Response.created(createdURI).build();
65 ResponseBuilder builder = Response.created(createdURI);
66 builder.type("text/plain");
67 // SoapUI considers a 0 length response an error
68 builder.entity("storeXML");
69 return builder.build();
70 }
71 }
+0
-90
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/BaseClassFromTypeListTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.logging.Logger;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.providers.jettison.resource.BaseClassFromTypeListStoreIntf;
10 import org.jboss.resteasy.test.providers.jettison.resource.BaseClassFromTypeListCustomer;
11 import org.jboss.resteasy.test.providers.jettison.resource.BaseClassFromTypeListInAccountsIntf;
12 import org.jboss.resteasy.test.providers.jettison.resource.BaseClassFromTypeListResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.After;
19 import org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.client.WebTarget;
26 import javax.ws.rs.core.Response;
27 import java.util.List;
28
29 /**
30 * @tpSubChapter Jettison provider
31 * @tpChapter Integration tests
32 * @tpTestCaseDetails Regression test for RESTEASY-167
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class BaseClassFromTypeListTest {
38
39 public static class Parent<T> {
40 public List<T> get() {
41 return null;
42 }
43 }
44
45 public static class Child extends Parent<BaseClassFromTypeListCustomer> {
46 }
47
48 protected final Logger logger = Logger.getLogger(BaseClassFromTypeListTest.class.getName());
49
50 static ResteasyClient client;
51
52 @Deployment
53 public static Archive<?> deploy() {
54 WebArchive war = TestUtil.prepareArchive(BaseClassFromTypeListTest.class.getSimpleName());
55 war.addAsManifestResource("jboss-deployment-structure-no-jackson.xml", "jboss-deployment-structure.xml");
56 return TestUtil.finishContainerPrepare(war, null, BaseClassFromTypeListCustomer.class, BaseClassFromTypeListResource.class,
57 BaseClassFromTypeListInAccountsIntf.class, BaseClassFromTypeListStoreIntf.class);
58 }
59
60 @Before
61 public void init() {
62 client = new ResteasyClientBuilder().build();
63 }
64
65 @After
66 public void after() throws Exception {
67 client.close();
68 client = null;
69 }
70
71 private String generateURL(String path) {
72 return PortProviderUtil.generateURL(path, BaseClassFromTypeListTest.class.getSimpleName());
73 }
74
75 /**
76 * @tpTestDetails Test with resource implementing generic interface
77 * @tpSince RESTEasy 3.0.16
78 */
79 @Test
80 public void testIntfTemplate() throws Exception {
81 WebTarget target = client.target(generateURL("/intf"));
82 Response response = target.request().get();
83 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
84 String str = response.readEntity(String.class);
85 logger.info(str);
86 response = target.request().put(Entity.entity(str, "application/json"));
87 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
88 }
89 }
+0
-166
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/ContentTypeMatchingTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.providers.jettison.resource.ContentTypeMatchingError;
9 import org.jboss.resteasy.test.providers.jettison.resource.ContentTypeMatchingErrorException;
10 import org.jboss.resteasy.test.providers.jettison.resource.ContentTypeMatchingErrorExceptionMapper;
11 import org.jboss.resteasy.test.providers.jettison.resource.ContentTypeMatchingMapperResource;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.After;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22 import javax.ws.rs.client.WebTarget;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Jettison provider
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails This tests automatically picking content type based on Accept header and/or @Produces
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class ContentTypeMatchingTest {
34
35 protected final Logger logger = Logger.getLogger(ContentTypeMatchingTest.class.getName());
36
37 static ResteasyClient client;
38
39 @Deployment
40 public static Archive<?> deploy() {
41 WebArchive war = TestUtil.prepareArchive(ContentTypeMatchingTest.class.getSimpleName());
42 war.addAsManifestResource("jboss-deployment-structure-no-jackson.xml", "jboss-deployment-structure.xml");
43 return TestUtil.finishContainerPrepare(war, null, ContentTypeMatchingError.class, ContentTypeMatchingErrorException.class,
44 ContentTypeMatchingErrorExceptionMapper.class, ContentTypeMatchingMapperResource.class);
45 }
46
47 @Before
48 public void init() {
49 client = new ResteasyClientBuilder().build();
50 }
51
52 @After
53 public void after() throws Exception {
54 client.close();
55 client = null;
56 }
57
58 private String generateURL(String path) {
59 return PortProviderUtil.generateURL(path, ContentTypeMatchingTest.class.getSimpleName());
60 }
61
62 /**
63 * @tpTestDetails Test that media type is chosen from resource method
64 * @tpPassCrit The response returned with expected http response code
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testProduces() throws Exception {
69 WebTarget target = client.target(generateURL("/mapper/produces"));
70 Response response = target.request().get();
71 Assert.assertEquals("Unexpected http response code was returned", 412, response.getStatus());
72 Assert.assertEquals("Wrong response content-type returned",
73 "application/xml;charset=UTF-8", response.getStringHeaders().getFirst("Content-Type"));
74 String error = response.readEntity(String.class);
75 logger.info(error);
76 Assert.assertTrue("Incorrect exception mapper was used",
77 error.contains("<contentTypeMatchingError><name>foo</name></contentTypeMatchingError>"));
78
79 }
80
81 /**
82 * @tpTestDetails Test that media type is chosen from resource method and accepts
83 * @tpPassCrit The response returned with expected http response code
84 * @tpSince RESTEasy 3.0.16
85 */
86 @Test
87 public void testAcceptsProduces() throws Exception {
88 WebTarget target = client.target(generateURL("/mapper/accepts-produces"));
89 {
90 Response response = target.request().accept("application/json").get();
91 Assert.assertEquals(412, response.getStatus());
92 Assert.assertEquals("application/json", response.getStringHeaders().getFirst("Content-Type"));
93 String error = response.readEntity(String.class);
94 logger.info(error);
95 Assert.assertTrue("Incorrect exception mapper was used", error.contains("{\"name\":\"foo\"}"));
96 }
97
98 {
99 Response response = target.request().accept("application/xml").get();
100 Assert.assertEquals(412, response.getStatus());
101 Assert.assertEquals("application/xml;charset=UTF-8", response.getStringHeaders().getFirst("Content-Type"));
102 String error = response.readEntity(String.class);
103 logger.info(error);
104 Assert.assertTrue("Incorrect exception mapper was used",
105 error.contains("<contentTypeMatchingError><name>foo</name></contentTypeMatchingError>"));
106 }
107 }
108
109 /**
110 * @tpTestDetails Test that media type is chosen from accepts
111 * @tpPassCrit The response returned with expected http response code
112 * @tpSince RESTEasy 3.0.16
113 */
114 @Test
115 public void testAccepts() throws Exception {
116 WebTarget target = client.target(generateURL("/mapper/accepts"));
117 {
118
119 Response response = target.request().accept("application/json").get();
120 Assert.assertEquals(412, response.getStatus());
121 Assert.assertEquals("application/json", response.getStringHeaders().getFirst("Content-Type"));
122 String error = response.readEntity(String.class);
123 logger.info(error);
124 Assert.assertTrue("Incorrect exception mapper was used", error.contains("{\"name\":\"foo\"}"));
125 }
126
127 {
128 Response response = target.request().accept("application/xml").get();
129 Assert.assertEquals(412, response.getStatus());
130 Assert.assertEquals("application/xml;charset=UTF-8", response.getStringHeaders().getFirst("Content-Type"));
131 String error = response.readEntity(String.class);
132 logger.info(error);
133 Assert.assertTrue("Incorrect exception mapper was used",
134 error.contains("<contentTypeMatchingError><name>foo</name></contentTypeMatchingError>"));
135 }
136 }
137
138 /**
139 * @tpTestDetails Test that media type is chosen from accepts when returning an entity
140 * @tpPassCrit The response returned with expected http response code
141 * @tpSince RESTEasy 3.0.16
142 */
143 @Test
144 public void testAcceptsEntity() throws Exception {
145 WebTarget target = client.target(generateURL("/mapper/accepts-entity"));
146 {
147 Response response = target.request().accept("application/json").get();
148 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
149 Assert.assertEquals("application/json", response.getStringHeaders().getFirst("Content-Type"));
150 String error = response.readEntity(String.class);
151 logger.info(error);
152 Assert.assertTrue("Incorrect exception mapper was used", error.contains("{\"name\":\"foo\"}"));
153 }
154
155 {
156 Response response = target.request().accept("application/xml").get();
157 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
158 Assert.assertEquals("application/xml;charset=UTF-8", response.getStringHeaders().getFirst("Content-Type"));
159 String error = response.readEntity(String.class);
160 logger.info(error);
161 Assert.assertTrue("Incorrect exception mapper was used",
162 error.contains("<contentTypeMatchingError><name>foo</name></contentTypeMatchingError>"));
163 }
164 }
165 }
+0
-169
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/JaxbSmokeTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.annotations.providers.jaxb.json.Mapped;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
10 import org.jboss.resteasy.plugins.providers.jaxb.json.BadgerContext;
11 import org.jboss.resteasy.plugins.providers.jaxb.json.JettisonMappedContext;
12 import org.jboss.resteasy.test.providers.jettison.resource.Book;
13 import org.jboss.resteasy.test.providers.jettison.resource.BookStoreClient;
14 import org.jboss.resteasy.test.providers.jettison.resource.BookStoreResource;
15 import org.jboss.resteasy.utils.PortProviderUtil;
16 import org.jboss.resteasy.utils.TestUtil;
17 import org.jboss.shrinkwrap.api.Archive;
18 import org.jboss.shrinkwrap.api.spec.WebArchive;
19 import org.junit.After;
20 import org.junit.Assert;
21 import org.junit.Before;
22 import org.junit.Test;
23 import org.junit.runner.RunWith;
24
25 import javax.xml.bind.annotation.XmlAttribute;
26 import javax.xml.bind.annotation.XmlElement;
27 import javax.xml.bind.annotation.XmlRootElement;
28 import java.io.StringReader;
29 import java.io.StringWriter;
30 import java.util.ArrayList;
31 import java.util.List;
32
33 /**
34 * @tpSubChapter Jettison provider
35 * @tpChapter Integration tests
36 * @tpSince RESTEasy 3.0.16
37 */
38 @RunWith(Arquillian.class)
39 @RunAsClient
40 public class JaxbSmokeTest {
41
42 private final Logger log = Logger.getLogger(JaxbSmokeTest.class.getName());
43 private static ResteasyClient client;
44
45 @Deployment
46 public static Archive<?> deploy() {
47 WebArchive war = TestUtil.prepareArchive(JaxbSmokeTest.class.getSimpleName());
48 war.addClass(Book.class);
49 return TestUtil.finishContainerPrepare(war, null, BookStoreResource.class);
50 }
51
52 @Before
53 public void before() throws Exception {
54 client = new ResteasyClientBuilder().build();
55 }
56
57 @After
58 public void after() throws Exception {
59 client.close();
60 client = null;
61 }
62
63 private String generateURL(String path) {
64 return PortProviderUtil.generateURL(path, JaxbSmokeTest.class.getSimpleName());
65 }
66
67 @Test
68 public void testNoDefaultsResource() {
69
70 ResteasyWebTarget target = client.target(generateURL(""));
71 BookStoreClient bookStoreClient = target.proxy(BookStoreClient.class);
72
73 Book book = bookStoreClient.getBookByISBN("596529260");
74 Assert.assertNotNull(book);
75 Assert.assertEquals("RESTful Web Services", book.getTitle());
76
77 book = new Book("Bill Burke", "666", "EJB 3.0");
78 bookStoreClient.addBook(book);
79 book = new Book("Bill Burke", "3434", "JBoss Workbook");
80 bookStoreClient.addBookJson(book);
81
82 book = bookStoreClient.getBookByISBN("666");
83 Assert.assertEquals("Bill Burke", book.getAuthor());
84 Assert.assertEquals("EJB 3.0", book.getTitle());
85
86 book = bookStoreClient.getBookByISBNJson("3434");
87 Assert.assertEquals("Bill Burke", book.getAuthor());
88 Assert.assertEquals("JBoss Workbook", book.getTitle());
89
90 }
91
92 @XmlRootElement
93 public static class Library {
94 private String name;
95 private List<Book> books;
96
97 @XmlAttribute
98 public String getName() {
99 return name;
100 }
101
102 public void setName(String name) {
103 this.name = name;
104 }
105
106 @XmlElement(name = "registered-books")
107 public List<Book> getBooks() {
108 return books;
109 }
110
111 public void setBooks(List<Book> books) {
112 this.books = books;
113 }
114 }
115
116 @Test
117 @Mapped(attributesAsElements = {"title"})
118 public void testJSON() throws Exception {
119 {
120 Mapped mapped = JaxbSmokeTest.class.getMethod("testJSON").getAnnotation(Mapped.class);
121 JettisonMappedContext context = new JettisonMappedContext(mapped, Book.class);
122 StringWriter writer = new StringWriter();
123 context.createMarshaller().marshal(new Book("Bill Burke", "666", "EJB 3.0"), writer);
124
125 String val = writer.toString();
126 log.info("Mapped: " + val);
127
128 // test Mapped attributeAsElement
129 Assert.assertTrue(!val.contains("@title"));
130 }
131 {
132 BadgerContext context = new BadgerContext(Book.class);
133 StringWriter writer = new StringWriter();
134 context.createMarshaller().marshal(new Book("Bill Burke", "666", "EJB 3.0"), writer);
135 log.info("Badger: " + writer.toString());
136 }
137 Library library = new Library();
138 List<Book> books = new ArrayList<>();
139 books.add(new Book("Bill Burke", "555", "JBoss Workbook"));
140 books.add(new Book("Bill Burke", "666", "EJB 3.0"));
141 library.setName("BPL");
142 library.setBooks(books);
143
144 {
145 BadgerContext context = new BadgerContext(Library.class);
146 StringWriter writer = new StringWriter();
147 context.createMarshaller().marshal(library, writer);
148
149 String s = writer.toString();
150 log.info("Badger: " + s);
151 Library lib = (Library) context.createUnmarshaller().unmarshal(new StringReader(s));
152 Assert.assertEquals(lib.getName(), "BPL");
153 Assert.assertEquals(lib.getBooks().size(), 2);
154 }
155 {
156 JettisonMappedContext context = new JettisonMappedContext(Library.class);
157 StringWriter writer = new StringWriter();
158 context.createMarshaller().marshal(library, writer);
159
160 String s = writer.toString();
161 log.info("Mapped: " + s);
162 Library lib = (Library) context.createUnmarshaller().unmarshal(new StringReader(s));
163 Assert.assertEquals(lib.getName(), "BPL");
164 Assert.assertEquals(lib.getBooks().size(), 2);
165 }
166 }
167
168 }
+0
-70
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/JettisonCustomerTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.providers.jettison.resource.JettisonCustomer;
9 import org.jboss.resteasy.test.providers.jettison.resource.JettisonCustomerList;
10 import org.jboss.resteasy.test.providers.jettison.resource.JettisonCustomerManagementResource;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.core.Response;
23
24 /**
25 * @tpSubChapter Jettison provider
26 * @tpChapter Integration tests
27 * @tpTestCaseDetails Regression test for RESTEASY-175
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class JettisonCustomerTest {
33
34 private static ResteasyClient client;
35
36 @Deployment
37 public static Archive<?> deploy() {
38 WebArchive war = TestUtil.prepareArchive(JettisonCustomerTest.class.getSimpleName());
39 war.addClasses(JettisonCustomer.class, JettisonCustomerList.class);
40 return TestUtil.finishContainerPrepare(war, null, JettisonCustomerManagementResource.class);
41 }
42
43 @Before
44 public void before() {
45 client = new ResteasyClientBuilder().build();
46 }
47
48 @After
49 public void after() {
50 client.close();
51 client = null;
52 }
53
54 private String generateURL(String path) {
55 return PortProviderUtil.generateURL(path, JettisonCustomerTest.class.getSimpleName());
56 }
57
58 @Test
59 public void testCustomer() {
60 ResteasyWebTarget target = client.target(generateURL("/management/customers"));
61 Response response = target.request().get();
62
63 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
64 JettisonCustomerList customers = response.readEntity(JettisonCustomerList.class);
65 Assert.assertEquals(4, customers.size());
66
67 response.close();
68 }
69 }
+0
-68
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/JettisonMediaTypeTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.providers.jettison.resource.JettisonMediaTypeObject;
8 import org.jboss.resteasy.test.providers.jettison.resource.JettisonMediaTypeService;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.core.Response;
21
22 import static org.hamcrest.CoreMatchers.containsString;
23
24 /**
25 * @tpSubChapter Jettison provider
26 * @tpChapter Integration tests
27 * @tpTestCaseDetails Regression test for RESTEASY-244
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class JettisonMediaTypeTest {
33 static ResteasyClient client;
34
35 @Deployment
36 public static Archive<?> deploy() {
37 WebArchive war = TestUtil.prepareArchive(JettisonMediaTypeTest.class.getSimpleName());
38 war.addAsManifestResource("jboss-deployment-structure-no-jackson.xml", "jboss-deployment-structure.xml");
39 war.addClass(JettisonMediaTypeObject.class);
40 return TestUtil.finishContainerPrepare(war, null, JettisonMediaTypeService.class);
41 }
42
43 @Before
44 public void init() {
45 client = new ResteasyClientBuilder().build();
46 }
47
48 @After
49 public void after() throws Exception {
50 client.close();
51 }
52
53 private String generateURL(String path) {
54 return PortProviderUtil.generateURL(path, JettisonMediaTypeTest.class.getSimpleName());
55 }
56
57 /**
58 * @tpTestDetails Cannot provide charset MediaType with application/json
59 * @tpSince RESTEasy 3.0.16
60 */
61 @Test
62 public void testCharset() throws Exception {
63 Response response = client.target(generateURL("/test/bug")).request().get();
64 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
65 Assert.assertThat("Wrong content of response", response.readEntity(String.class), containsString("bill"));
66 }
67 }
+0
-192
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/JsonCollectionTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.logging.Logger;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.providers.jettison.resource.JsonCollectionFoo;
10 import org.jboss.resteasy.test.providers.jettison.resource.JsonCollectionMyNamespacedResource;
11 import org.jboss.resteasy.test.providers.jettison.resource.JsonCollectionMyResource;
12 import org.jboss.resteasy.test.providers.jettison.resource.JsonCollectionNamespacedFoo;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Assert;
19 import org.junit.Before;
20 import org.junit.After;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.client.WebTarget;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @tpSubChapter Jettison provider
30 * @tpChapter Integration tests
31 * @tpSince RESTEasy 3.0.16
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class JsonCollectionTest {
36
37 protected final Logger logger = Logger.getLogger(JsonCollectionTest.class.getName());
38
39 static ResteasyClient client;
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(JsonCollectionTest.class.getSimpleName());
44 war.addAsManifestResource("jboss-deployment-structure-no-jackson.xml", "jboss-deployment-structure.xml");
45 return TestUtil.finishContainerPrepare(war, null, JsonCollectionFoo.class, JsonCollectionMyNamespacedResource.class,
46 JsonCollectionNamespacedFoo.class, JsonCollectionMyResource.class);
47 }
48
49 @Before
50 public void init() {
51 client = new ResteasyClientBuilder().build();
52 }
53
54 @After
55 public void after() throws Exception {
56 client.close();
57 client = null;
58 }
59
60 private String generateURL(String path) {
61 return PortProviderUtil.generateURL(path, JsonCollectionTest.class.getSimpleName());
62 }
63
64 /**
65 * @tpTestDetails Test that an array containing json objects can be received and send
66 * @tpPassCrit The response with Success is returned
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void testArray() throws Exception {
71 WebTarget target = client.target(generateURL("/array"));
72 Response response;
73 {
74 response = target.request().get();
75 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
76 logger.info(response.readEntity(String.class));
77 }
78
79 {
80 response = target.request()
81 .post(Entity.entity("[{\"jsonCollectionFoo\":{\"@test\":\"bill{\"}},{\"jsonCollectionFoo\":{\"@test\":\"monica\\\"}\"}}]",
82 "application/json"));
83 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
84 logger.info(response.readEntity(String.class));
85 }
86
87 }
88
89 /**
90 * @tpTestDetails Test that json entity is correctly marshalled into the array, and json string is returned from the server
91 * and the same entity is send back to the server to produce a list and returned as json string.
92 * @tpPassCrit The response with Success is returned
93 * @tpSince RESTEasy 3.0.16
94 */
95 @Test
96 public void testList() throws Exception {
97
98 WebTarget targetArray = client.target(generateURL("/array"));
99 Response response = targetArray.request().get();
100 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
101 String entity = response.readEntity(String.class);
102 logger.info(entity);
103
104 WebTarget targetList = client.target(generateURL("/list"));
105 response = targetList.request().post(Entity.entity(entity, "application/json"));
106 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
107 Assert.assertEquals("The response from the server is not the expected one",
108 "[{\"jsonCollectionFoo\":{\"@test\":\"bill{\"}},{\"jsonCollectionFoo\":{\"@test\":\"monica\\\"}\"}}]",
109 response.readEntity(String.class));
110 }
111
112 /**
113 * @tpTestDetails Test that an array of namespaced json objects can be received and send
114 * @tpPassCrit The response with Success is returned
115 * @tpSince RESTEasy 3.0.16
116 */
117 @Test
118 public void testNamespacedArray() throws Exception {
119 WebTarget target = client.target(generateURL("/namespaced/array"));
120 Response response = target.request().get();
121 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
122 String entity = response.readEntity(String.class);
123 logger.info(entity);
124
125 response = target.request().post(Entity.entity(entity, "application/json"));
126 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
127 Assert.assertEquals("The response from the server is not the expected one",
128 "[{\"foo.com.foo\":{\"@test\":\"bill{\"}},{\"foo.com.foo\":{\"@test\":\"monica\\\"}\"}}]",
129 response.readEntity(String.class));
130 }
131
132 /**
133 * @tpTestDetails Test that namespaced json entity is correctly marshalled into the array, and json string is returned from the server
134 * and the same entity is send back to the server to produce a list and returned as json string.
135 * @tpPassCrit The response with Success is returned
136 * @tpSince RESTEasy 3.0.16
137 */
138 @Test
139 public void testNamespacedList() throws Exception {
140 WebTarget target = client.target(generateURL("/namespaced/array"));
141 Response response = target.request().get();
142 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
143 String entity = response.readEntity(String.class);
144 logger.info(entity);
145
146 WebTarget targetList = client.target(generateURL("/namespaced/list"));
147 response = targetList.request().post(Entity.entity(entity, "application/json"));
148 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
149 Assert.assertEquals("The response from the server is not the expected one",
150 "[{\"foo.com.foo\":{\"@test\":\"bill{\"}},{\"foo.com.foo\":{\"@test\":\"monica\\\"}\"}}]",
151 response.readEntity(String.class));
152 }
153
154 /**
155 * @tpTestDetails Test to send and receive empty json array
156 * @tpPassCrit The response with Success is returned
157 * @tpSince RESTEasy 3.0.16
158 */
159 @Test
160 public void testEmptyArray() throws Exception {
161 WebTarget target = client.target(generateURL("/empty/array"));
162 Response response = target.request().post(Entity.entity("[]", "application/json"));
163 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
164 Assert.assertEquals("The response from the server is not the expected one", "[]", response.readEntity(String.class));
165 }
166
167 /**
168 * @tpTestDetails Test to send and receive empty json list
169 * @tpPassCrit The response with Success is returned
170 * @tpSince RESTEasy 3.0.16
171 */
172 @Test
173 public void testEmptyList() throws Exception {
174 WebTarget target = client.target(generateURL("/empty/list"));
175 Response response = target.request().post(Entity.entity("[]", "application/json"));
176 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
177 Assert.assertEquals("The response from the server is not the expected one", "[]", response.readEntity(String.class));
178 }
179
180 /**
181 * @tpTestDetails Test to send non-json input
182 * @tpPassCrit The response with code Bad request is returned
183 * @tpSince RESTEasy 3.0.16
184 */
185 @Test
186 public void testBadArray() throws Exception {
187 WebTarget target = client.target(generateURL("/array"));
188 Response response = target.request().post(Entity.entity("asdfasdfasdf", "application/json"));
189 Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus());
190 }
191 }
+0
-103
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/JsonMapTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.providers.jettison.resource.JsonMapFoo;
9 import org.jboss.resteasy.test.providers.jettison.resource.JsonMapResource;
10 import org.jboss.resteasy.util.HttpResponseCodes;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.After;
16 import org.junit.Assert;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.Entity;
22 import javax.ws.rs.client.WebTarget;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Jettison provider
27 * @tpChapter Integration tests
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class JsonMapTest {
33
34 protected final Logger logger = Logger.getLogger(JsonMapTest.class.getName());
35
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(JsonMapTest.class.getSimpleName());
41 war.addClass(JsonMapTest.class);
42 war.addAsManifestResource("jboss-deployment-structure-no-jackson.xml", "jboss-deployment-structure.xml");
43 return TestUtil.finishContainerPrepare(war, null, JsonMapFoo.class, JsonMapResource.class);
44 }
45
46 @Before
47 public void init() {
48 client = new ResteasyClientBuilder().build();
49 }
50
51 @After
52 public void after() throws Exception {
53 client.close();
54 client = null;
55 }
56
57 private String generateURL(String path) {
58 return PortProviderUtil.generateURL(path, JsonMapTest.class.getSimpleName());
59 }
60
61 /**
62 * @tpTestDetails Client sends GET request for json resource. The response should be processed with jettison provider.
63 * The json map is send as entity with the POST request.
64 * @tpPassCrit The response returned successfully
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testProvider() throws Exception {
69 WebTarget target = client.target(generateURL("/map"));
70 Response response = target.request().get();
71 String stringResponse = response.readEntity(String.class);
72 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
73 logger.info(stringResponse);
74 response.close();
75
76 response = target.request().post(Entity.entity(stringResponse, "application/json"));
77 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
78 response.close();
79
80 response = target.request()
81 .post(Entity.json("{\"monica\":{\"jsonMapFoo\":{\"@name\":\"monica\"}},\"bill\":{\"jsonMapFoo\":{\"@name\":\"bill\"}}}"));
82 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
83 response.close();
84
85 }
86
87 /**
88 * @tpTestDetails Client sends POST request for json resource. The response should be processed with jettison provider.
89 * The entity in the resource is empty map.
90 * @tpPassCrit The response returned successfully
91 * @tpSince RESTEasy 3.0.16
92 */
93 @Test
94 public void testEmptyMap() throws Exception {
95 WebTarget target = client.target(generateURL("/map/empty"));
96 Response response = target.request().post(Entity.json("{}"));
97 String responseString = response.readEntity(String.class);
98 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
99 Assert.assertEquals("The map in the response should be empty and it's not", "{}", responseString);
100
101 }
102 }
+0
-85
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/NamespaceMappingTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2 import org.codehaus.jettison.json.JSONObject;
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.providers.jettison.resource.NamespaceMappingTestExtends;
9 import org.jboss.resteasy.test.providers.jettison.resource.ObjectFactory;
10 import org.jboss.resteasy.test.providers.jettison.resource.NamespaceMappingTestBase;
11 import org.jboss.resteasy.test.providers.jettison.resource.NamespaceMappingResource;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.client.WebTarget;
24 import javax.ws.rs.core.Response;
25
26 /**
27 * @tpSubChapter Jettison provider
28 * @tpChapter Integration tests
29 * @tpTestCaseDetails Namespace mapping test for jettison provider
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class NamespaceMappingTest {
35 static ResteasyClient client;
36
37 @Deployment
38 public static Archive<?> deploy() {
39 WebArchive war = TestUtil.prepareArchive(NamespaceMappingTest.class.getSimpleName());
40 war.addClasses(NamespaceMappingTestBase.class, NamespaceMappingTestExtends.class,
41 NamespaceMappingResource.class, ObjectFactory.class);
42 war.addAsManifestResource("jboss-deployment-structure-no-jackson.xml", "jboss-deployment-structure.xml");
43 return TestUtil.finishContainerPrepare(war, null, NamespaceMappingResource.class);
44 }
45
46 @Before
47 public void init() {
48 client = new ResteasyClientBuilder().build();
49 }
50
51 @After
52 public void after() throws Exception {
53 client.close();
54 }
55
56 private String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, NamespaceMappingTest.class.getSimpleName());
58 }
59
60 /**
61 * @tpTestDetails Test "application/*+json" media type
62 * @tpSince RESTEasy 3.0.16
63 */
64 @Test
65 public void testJsonReqRes() throws Exception {
66 String getData = getDataFromUrl();
67 Assert.assertNotNull(getData);
68 String postData = postDataToUrl(getData, "application/*+json");
69 Assert.assertNotNull(postData);
70 new JSONObject(postData);
71 }
72
73 private String postDataToUrl(String data, String contentType) throws Exception {
74 WebTarget target = client.target(generateURL("/test/v1"));
75 Response response = target.request().post(Entity.entity(data, contentType));
76 return response.readEntity(String.class);
77 }
78
79 private String getDataFromUrl() throws Exception {
80 WebTarget target = client.target(generateURL("/test/v1"));
81 Response response = target.request().get();
82 return response.readEntity(String.class);
83 }
84 }
+0
-93
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/ProxyInheritanceTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ProxyFactory;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.providers.jettison.resource.CRUDEntityWebservice;
9 import org.jboss.resteasy.test.providers.jettison.resource.MyService;
10 import org.jboss.resteasy.test.providers.jettison.resource.NamespaceMappingResource;
11 import org.jboss.resteasy.test.providers.jettison.resource.NamespaceMappingTestBase;
12 import org.jboss.resteasy.test.providers.jettison.resource.NamespaceMappingTestExtends;
13 import org.jboss.resteasy.test.providers.jettison.resource.ObjectFactory;
14 import org.jboss.resteasy.test.providers.jettison.resource.UserEntity;
15 import org.jboss.resteasy.test.providers.jettison.resource.UserEntityWebservice;
16 import org.jboss.resteasy.utils.PortProviderUtil;
17 import org.jboss.resteasy.utils.TestUtil;
18 import org.jboss.shrinkwrap.api.Archive;
19 import org.jboss.shrinkwrap.api.spec.WebArchive;
20 import org.junit.After;
21 import org.junit.Before;
22 import org.junit.Test;
23 import org.junit.runner.RunWith;
24
25 import static org.junit.Assert.assertEquals;
26
27 /**
28 * @tpSubChapter Jettison provider
29 * @tpChapter Integration tests
30 * @tpTestCaseDetails Regression test for RESTEASY-213
31 * @tpSince RESTEasy 3.0.16
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class ProxyInheritanceTest {
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(ProxyInheritanceTest.class.getSimpleName());
41 war.addClasses(NamespaceMappingTestBase.class, NamespaceMappingTestExtends.class,
42 NamespaceMappingResource.class, ObjectFactory.class);
43 war.addClasses(CRUDEntityWebservice.class, MyService.class,
44 UserEntity.class, UserEntityWebservice.class);
45 war.addAsManifestResource("jboss-deployment-structure-no-jackson.xml", "jboss-deployment-structure.xml");
46 return TestUtil.finishContainerPrepare(war, null, MyService.class);
47 }
48
49 @Before
50 public void init() {
51 client = new ResteasyClientBuilder().build();
52 }
53
54 @After
55 public void after() throws Exception {
56 client.close();
57 }
58
59 private String generateBaseUrl() {
60 return PortProviderUtil.generateBaseUrl(ProxyInheritanceTest.class.getSimpleName());
61 }
62
63 /**
64 * @tpTestDetails Test for new client
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testNewClient() {
69 UserEntity u = new UserEntity();
70 u.setUsername("user");
71
72 UserEntityWebservice serviceClient = client.target(generateBaseUrl()).proxy(UserEntityWebservice.class);
73 UserEntity newUser = serviceClient.create(u);
74
75 assertEquals("Wrong response from proxy", "user", newUser.getUsername());
76 }
77
78 /**
79 * @tpTestDetails Test for old client
80 * @tpSince RESTEasy 3.0.16
81 */
82 @Test
83 public void testOldClient() {
84 UserEntity u = new UserEntity();
85 u.setUsername("user");
86
87 UserEntityWebservice serviceClient = ProxyFactory.create(UserEntityWebservice.class, generateBaseUrl());
88 UserEntity newUser = serviceClient.create(u);
89
90 assertEquals("Wrong response from proxy", "user", newUser.getUsername());
91 }
92 }
+0
-129
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/TypeMappingJettisonTest.java less more
0 package org.jboss.resteasy.test.providers.jettison;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.providers.jettison.resource.TypeMappingBean;
8 import org.jboss.resteasy.test.providers.jettison.resource.TypeMappingResource;
9 import org.jboss.resteasy.util.HttpHeaderNames;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.After;
15 import org.junit.Before;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.core.Response;
20 import java.util.HashMap;
21 import java.util.Map;
22
23 import static org.junit.Assert.assertEquals;
24
25 /**
26 * @tpSubChapter Jettison provider
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Type mapping test
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class TypeMappingJettisonTest {
34
35 static ResteasyClient client;
36
37 @Deployment
38 public static Archive<?> deploy() {
39 WebArchive war = TestUtil.prepareArchive(TypeMappingJettisonTest.class.getSimpleName());
40 war.addAsManifestResource("jboss-deployment-structure-no-jackson.xml", "jboss-deployment-structure.xml");
41 war.addClass(TypeMappingBean.class);
42
43 Map<String, String> params = new HashMap<>();
44 params.put("resteasy.media.type.mappings", "xml : application/xml, json : application/json");
45 return TestUtil.finishContainerPrepare(war, params, TypeMappingResource.class);
46 }
47
48 @Before
49 public void init() {
50 client = new ResteasyClientBuilder().build();
51 }
52
53 @After
54 public void after() throws Exception {
55 client.close();
56 }
57
58 private String generateURL(String path) {
59 return PortProviderUtil.generateURL(path, TypeMappingJettisonTest.class.getSimpleName());
60 }
61
62 private void requestAndAssert(String path, String extension, String accept,
63 String expectedContentType) throws Exception {
64 String url = generateURL("/test/" + path);
65 if (extension != null) {
66 url = url + "." + extension;
67 }
68 Response response;
69 if (accept != null) {
70 response = client.target(url).request().header(HttpHeaderNames.ACCEPT, accept).get();
71 } else {
72 response = client.target(url).request().get();
73 }
74 assertEquals("Request for " + url + " returned a non-200 status", 200, response.getStatus());
75 assertEquals("Request for " + url + " returned an unexpected content type",
76 expectedContentType, response.getStringHeaders().getFirst("Content-type"));
77 response.close();
78 }
79
80 /**
81 * @tpTestDetails Test for extensions: xml -> application/xml, json -> application/json
82 * @tpSince RESTEasy 3.0.16
83 */
84 @Test
85 public void extensionTest() throws Exception {
86 // acceptXMLOnlyRequestNoProducesNoExtension() throws Exception {
87 requestAndAssert("noproduces", null, "application/xml", "application/xml;charset=UTF-8");
88
89 // acceptJSONOnlyRequestNoProducesNoExtension() throws Exception {
90 requestAndAssert("noproduces", null, "application/json", "application/json");
91
92 // acceptNullRequestNoProducesJSONExtension() throws Exception {
93 requestAndAssert("noproduces", "json", null, "application/json");
94
95 // acceptNullRequestNoProducesXMLExtension() throws Exception {
96 requestAndAssert("noproduces", "xml", null, "application/xml;charset=UTF-8");
97
98
99 // acceptJSONOnlyRequestNoProducesJSONExtension() throws Exception {
100 requestAndAssert("noproduces", "json", "application/json", "application/json");
101
102 // acceptJSONOnlyRequestNoProducesXMLExtension() throws Exception {
103 requestAndAssert("noproduces", "xml", "application/json", "application/xml;charset=UTF-8");
104
105 // acceptJSONAndXMLRequestNoProducesJSONExtension() throws Exception {
106 requestAndAssert("noproduces", "json", "application/json, application/xml",
107 "application/json");
108
109 // acceptXMLAndJSONRequestNoProducesJSONExtension() throws Exception {
110 requestAndAssert("noproduces", "json", "application/xml, application/json",
111 "application/json");
112
113 // acceptXMLOnlyRequestNoProducesXMLExtension() throws Exception {
114 requestAndAssert("noproduces", "xml", "application/xml", "application/xml;charset=UTF-8");
115
116 // acceptXMLOnlyRequestNoProducesJSONExtension() throws Exception {
117 requestAndAssert("noproduces", "json", "application/xml", "application/json");
118
119 // acceptJSONAndXMLRequestNoProducesXMLExtension() throws Exception {
120 requestAndAssert("noproduces", "xml", "application/json, application/xml",
121 "application/xml;charset=UTF-8");
122
123 // acceptXMLAndJSONRequestNoProducesXMLExtension() throws Exception {
124 requestAndAssert("noproduces", "xml", "application/xml, application/json",
125 "application/xml;charset=UTF-8");
126 }
127
128 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/BaseClassFromTypeListCustomer.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "customer")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class BaseClassFromTypeListCustomer {
10 @XmlElement
11 private String name;
12
13 public BaseClassFromTypeListCustomer() {
14 }
15
16 public BaseClassFromTypeListCustomer(final String name) {
17 this.name = name;
18 }
19
20 public String getName() {
21 return name;
22 }
23 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/BaseClassFromTypeListInAccountsIntf.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2
3 public interface BaseClassFromTypeListInAccountsIntf extends BaseClassFromTypeListStoreIntf<BaseClassFromTypeListCustomer> {
4 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/BaseClassFromTypeListResource.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.Path;
5 import java.util.ArrayList;
6 import java.util.List;
7
8 @Path("/")
9 public class BaseClassFromTypeListResource implements BaseClassFromTypeListInAccountsIntf {
10 public List<BaseClassFromTypeListCustomer> list() {
11 ArrayList<BaseClassFromTypeListCustomer> set = new ArrayList<BaseClassFromTypeListCustomer>();
12 set.add(new BaseClassFromTypeListCustomer("bill"));
13 set.add(new BaseClassFromTypeListCustomer("monica"));
14
15 return set;
16 }
17
18 public void put(List<BaseClassFromTypeListCustomer> customers) {
19 Assert.assertEquals("bill", customers.get(0).getName());
20 Assert.assertEquals("monica", customers.get(1).getName());
21 }
22 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/BaseClassFromTypeListStoreIntf.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.Wrapped;
3 import org.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.PUT;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.Consumes;
10 import java.util.List;
11
12 public interface BaseClassFromTypeListStoreIntf<T> {
13 @GET
14 @Path("/intf")
15 @Produces("application/json")
16 @BadgerFish
17 @Wrapped
18 List<T> list();
19
20 @PUT
21 @Path("/intf")
22 @Consumes("application/json")
23 void put(@Wrapped @BadgerFish List<T> list);
24 }
+0
-48
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/Book.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAttribute;
3 import javax.xml.bind.annotation.XmlElement;
4 import javax.xml.bind.annotation.XmlRootElement;
5
6 @XmlRootElement(name = "book")
7 public class Book {
8 private String author;
9 private String ISBN;
10 private String title;
11
12 public Book() {
13 }
14
15 public Book(String author, String ISBN, String title) {
16 this.author = author;
17 this.ISBN = ISBN;
18 this.title = title;
19 }
20
21 @XmlElement
22 public String getAuthor() {
23 return author;
24 }
25
26 public void setAuthor(String author) {
27 this.author = author;
28 }
29
30 @XmlElement
31 public String getISBN() {
32 return ISBN;
33 }
34
35 public void setISBN(String ISBN) {
36 this.ISBN = ISBN;
37 }
38
39 @XmlAttribute
40 public String getTitle() {
41 return title;
42 }
43
44 public void setTitle(String title) {
45 this.title = title;
46 }
47 }
+0
-43
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/BookStoreClient.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.PUT;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8 import java.util.Collection;
9
10 @Path("/bookstore")
11 public interface BookStoreClient {
12
13 @GET
14 @Path("/books/{isbn}")
15 @Produces("text/xml")
16 Book getBookByISBN(@PathParam("isbn") String isbn);
17
18 @PUT
19 @Path("/books")
20 @Consumes("text/xml")
21 void addBook(Book book);
22
23 @GET
24 @Path("/books")
25 @Produces("text/xml")
26 Collection<Book> getAllBooks();
27
28 @GET
29 @Path("/books/{isbn}")
30 @Produces("application/json")
31 Book getBookByISBNJson(@PathParam("isbn") String isbn);
32
33 @PUT
34 @Path("/books")
35 @Consumes("application/json")
36 void addBookJson(Book book);
37
38 @GET
39 @Path("/books")
40 @Produces("application/json")
41 Collection<Book> getAllBooksJson();
42 }
+0
-44
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/BookStoreResource.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.PUT;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8 import java.util.Collection;
9 import java.util.HashMap;
10 import java.util.Map;
11
12 @Path("/bookstore")
13 public class BookStoreResource {
14 private static Map<String, Book> availableBooks = new HashMap<>();
15
16 static {
17 availableBooks.put("596529260", new Book("Leonard Richardson", "596529260", "RESTful Web Services"));
18 availableBooks.put("3897217279", new Book("Sam Ruby", "3897217279", "Web Services mit REST"));
19 }
20
21 @GET
22 @Path("/books/{isbn}")
23 @Produces({"text/xml", "application/json"})
24 public Book getBookByISBN(@PathParam("isbn") String isbn) {
25 return availableBooks.get(isbn);
26 }
27
28 @PUT
29 @Path("/books")
30 @Consumes({"text/xml", "application/json"})
31 public void addBook(Book book) {
32 availableBooks.put(book.getISBN(), book);
33 }
34
35 @GET
36 @Path("/books")
37 @Produces({"text/xml", "application/json"})
38 public Collection<Book> getAllBooks() {
39 return availableBooks.values();
40 }
41
42
43 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/CRUDEntityWebservice.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;
4
5 public interface CRUDEntityWebservice {
6
7 @POST
8 @Path("/")
9 UserEntity create(UserEntity entity);
10 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/ContentTypeMatchingError.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlElement;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement
6 public class ContentTypeMatchingError {
7 private String name = "foo";
8
9 @XmlElement
10 public String getName() {
11 return name;
12 }
13
14 public void setName(String name) {
15 this.name = name;
16 }
17 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/ContentTypeMatchingErrorException.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 public class ContentTypeMatchingErrorException extends RuntimeException {
3
4 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/ContentTypeMatchingErrorExceptionMapper.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.ws.rs.core.Response;
3 import javax.ws.rs.ext.ExceptionMapper;
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class ContentTypeMatchingErrorExceptionMapper implements ExceptionMapper<ContentTypeMatchingErrorException> {
8 public Response toResponse(ContentTypeMatchingErrorException exception) {
9 return Response.status(412).entity(new ContentTypeMatchingError()).build();
10 }
11 }
+0
-34
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/ContentTypeMatchingMapperResource.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/mapper")
7 public class ContentTypeMatchingMapperResource {
8 @Path("produces")
9 @Produces("application/xml")
10 @GET
11 public String getProduces() {
12 throw new ContentTypeMatchingErrorException();
13 }
14
15 @Path("accepts-produces")
16 @Produces({"application/xml", "application/json"})
17 @GET
18 public String getAcceptsProduces() {
19 throw new ContentTypeMatchingErrorException();
20 }
21
22 @Path("accepts")
23 @GET
24 public String getAccepts() {
25 throw new ContentTypeMatchingErrorException();
26 }
27
28 @Path("accepts-entity")
29 @GET
30 public ContentTypeMatchingError getEntity() {
31 return new ContentTypeMatchingError();
32 }
33 }
+0
-188
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JettisonCustomer.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlRootElement;
6 import javax.xml.bind.annotation.XmlTransient;
7 import java.io.Serializable;
8 import java.text.DateFormat;
9 import java.text.ParseException;
10 import java.util.Calendar;
11 import java.util.Date;
12 import java.util.GregorianCalendar;
13 import java.util.Locale;
14
15 @XmlRootElement
16 @XmlAccessorType(XmlAccessType.FIELD)
17 public class JettisonCustomer implements Serializable {
18
19 private static final long serialVersionUID = -6949084426046457758L;
20
21 @XmlAttribute(name = "id", required = true)
22 protected Long id = null;
23
24 @XmlAttribute(required = true)
25 protected String surname = "";
26
27 protected String firstName = "";
28
29 @XmlAttribute(required = true)
30 protected String customerNumber = "NnVn-001";
31
32 protected Date since = null;
33
34 @XmlTransient
35 protected int activeYears;
36
37 protected String details;
38
39 @XmlTransient
40 protected Date generated = null;
41
42 @XmlAttribute
43 protected Date updated = null;
44
45 public JettisonCustomer() {
46 super();
47 }
48
49 public Long getId() {
50 return id;
51 }
52
53 public void setId(Long id) {
54 this.id = id;
55 }
56
57 public String getSurname() {
58 return surname;
59 }
60
61 public void setSurname(String surname) {
62 this.surname = surname;
63 }
64
65 public String getFirstName() {
66 return firstName;
67 }
68
69 public void setFirstName(String firstName) {
70 this.firstName = firstName;
71 }
72
73 public String getCustomerNumber() {
74 return customerNumber;
75 }
76
77 public void setCustomerNumber(String customerNumber) {
78 this.customerNumber = customerNumber;
79 }
80
81 public Date getSince() {
82 return since;
83 }
84
85 public void setSince(Date since) {
86 this.since = since;
87 }
88
89 public int getActiveYears() {
90 final GregorianCalendar now = new GregorianCalendar();
91 final GregorianCalendar sinceCal = new GregorianCalendar();
92
93 Date temp = since;
94 if (temp == null) {
95 temp = new Date();
96 }
97
98 sinceCal.setTime(temp);
99 activeYears = now.get(Calendar.YEAR) - sinceCal.get(Calendar.YEAR);
100
101 return activeYears;
102 }
103
104 public String getSinceAsString(int style, Locale locale) {
105 Date temp = since;
106 if (temp == null) {
107 temp = new Date();
108 }
109
110 final DateFormat df = DateFormat.getDateInstance(style, locale);
111 return df.format(temp);
112 }
113
114 public void setSince(String since, int style, Locale locale) {
115 final DateFormat df = DateFormat.getDateInstance(style, locale);
116
117 try {
118 this.since = df.parse(since);
119 } catch (ParseException pe) {
120 throw new RuntimeException(pe);
121 }
122 }
123
124 public void setActiveYears(int activeYears) {
125 this.activeYears = activeYears;
126 }
127
128 public String getDetails() {
129 return details;
130 }
131
132 public void setDetails(String details) {
133 this.details = details;
134 }
135
136 public Date getGenerated() {
137 return generated;
138 }
139
140 public void setGenerated(Date generated) {
141 this.generated = generated;
142 }
143
144 public Date getUpdated() {
145 return updated;
146 }
147
148 public void setUpdated(Date updated) {
149 this.updated = updated;
150 }
151
152 @Override
153 public String toString() {
154 return "JettisonCustomer{" +
155 "id=" + id +
156 ", surname='" + surname + '\'' +
157 ", firstName='" + firstName + '\'' +
158 ", customerNumber='" + customerNumber + '\'' +
159 ", since=" + getSinceAsString(DateFormat.MEDIUM, Locale.ENGLISH) +
160 ", activeYears=" + getActiveYears() +
161 ", details='" + details + '\'' +
162 ", generated=" + generated +
163 ", updated=" + updated +
164 '}';
165 }
166
167 @Override
168 public boolean equals(Object o) {
169 if (this == o) return true;
170 if (o == null || getClass() != o.getClass()) return false;
171
172 JettisonCustomer that = (JettisonCustomer) o;
173
174 if (surname != null ? !surname.equals(that.surname) : that.surname != null) return false;
175 if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) return false;
176 return since != null ? since.equals(that.since) : that.since == null;
177
178 }
179
180 @Override
181 public int hashCode() {
182 int result = surname != null ? surname.hashCode() : 0;
183 result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
184 result = 31 * result + (since != null ? since.hashCode() : 0);
185 return result;
186 }
187 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JettisonCustomerList.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlElementRef;
3 import javax.xml.bind.annotation.XmlRootElement;
4 import java.util.Collection;
5
6 @XmlRootElement(name = "customers")
7 public class JettisonCustomerList {
8
9 @XmlElementRef
10 public Collection<JettisonCustomer> customers;
11
12 public JettisonCustomerList() {
13 }
14
15 public JettisonCustomerList(Collection<JettisonCustomer> customers) {
16 this.customers = customers;
17 }
18
19 public int size() {
20 return customers.size();
21 }
22 }
+0
-42
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JettisonCustomerManagementResource.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.json.Mapped;
3 import org.jboss.resteasy.annotations.providers.jaxb.json.XmlNsMap;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.MediaType;
10 import java.util.ArrayList;
11 import java.util.Date;
12 import java.util.List;
13
14 @Path("/management")
15 @Produces(MediaType.APPLICATION_XML)
16 @Consumes(MediaType.APPLICATION_XML)
17 public class JettisonCustomerManagementResource {
18
19 @GET
20 @Path("/customers")
21 @Produces(MediaType.APPLICATION_JSON)
22 @Mapped(namespaceMap = {
23 @XmlNsMap(namespace = "http://namespace.org/customermanagement", jsonName = "cusotmers")
24 })
25 public JettisonCustomerList findCutomerJSON() {
26
27 int capacity = 4;
28 final List<JettisonCustomer> customers = new ArrayList<>(capacity);
29 for (int i = 0; i < capacity; i++) {
30 final JettisonCustomer cust = new JettisonCustomer();
31 cust.setId(Long.valueOf(i));
32 cust.setSurname("Lastname" + i);
33 cust.setSince(new Date());
34
35 customers.add(cust);
36 }
37
38 final JettisonCustomerList customerList = new JettisonCustomerList(customers);
39 return customerList;
40 }
41 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JettisonMediaTypeObject.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class JettisonMediaTypeObject {
10 @XmlAttribute
11 String name = "bill";
12
13 public String getName() {
14 return name;
15 }
16
17 public void setName(String name) {
18 this.name = name;
19 }
20 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JettisonMediaTypeService.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/test")
7 public class JettisonMediaTypeService {
8 @GET
9 @Path("bug")
10 @Produces({"application/json;charset=UTF-8"})
11 public JettisonMediaTypeObject bug() {
12 return new JettisonMediaTypeObject();
13 }
14
15 @GET
16 @Path("nobug")
17 @Produces({"application/json"})
18 public JettisonMediaTypeObject nobug() {
19 return new JettisonMediaTypeObject();
20 }
21 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JsonCollectionFoo.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAttribute;
3 import javax.xml.bind.annotation.XmlRootElement;
4 import javax.xml.bind.annotation.XmlAccessorType;
5 import javax.xml.bind.annotation.XmlAccessType;
6
7 @XmlRootElement
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class JsonCollectionFoo {
10 @XmlAttribute
11 private String test;
12
13 public JsonCollectionFoo() {
14 }
15
16 public JsonCollectionFoo(final String test) {
17 this.test = test;
18 }
19
20 public String getTest() {
21 return test;
22 }
23
24 public void setTest(String test) {
25 this.test = test;
26 }
27 }
+0
-65
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JsonCollectionMyNamespacedResource.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.json.Mapped;
3 import org.jboss.resteasy.annotations.providers.jaxb.json.XmlNsMap;
4 import org.junit.Assert;
5
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.GET;
9 import javax.ws.rs.Consumes;
10 import javax.ws.rs.POST;
11 import java.util.List;
12
13 @Path("/namespaced")
14 public class JsonCollectionMyNamespacedResource {
15 @Path("/array")
16 @Produces("application/json;charset=UTF-8")
17 @GET
18 @Mapped(namespaceMap = @XmlNsMap(namespace = "http://foo.com", jsonName = "foo.com"))
19 public JsonCollectionNamespacedFoo[] get() throws Exception {
20 JsonCollectionNamespacedFoo[] foo = {new JsonCollectionNamespacedFoo("bill{"), new JsonCollectionNamespacedFoo("monica\"}")};
21 return foo;
22 }
23
24 @Path("/array")
25 @Produces("application/json")
26 @Consumes("application/json")
27 @POST
28 public JsonCollectionNamespacedFoo[] array(JsonCollectionNamespacedFoo[] foo) {
29 Assert.assertEquals("The size of the array is not the expected one", 2, foo.length);
30 Assert.assertEquals("The first element of the array is not the expected one", foo[0].getTest(), "bill{");
31 Assert.assertEquals("The second element of the array is not the expected one", foo[1].getTest(), "monica\"}");
32 return foo;
33 }
34
35 @Path("/list")
36 @Produces("application/json")
37 @Consumes("application/json")
38 @POST
39 public List<JsonCollectionNamespacedFoo> list(List<JsonCollectionNamespacedFoo> foo) {
40 Assert.assertEquals("The length of the list is not the expected one", 2, foo.size());
41 Assert.assertEquals("The first element of the list is not the expected one", foo.get(0).getTest(), "bill{");
42 Assert.assertEquals("The second element of the list is not the expected one", foo.get(1).getTest(), "monica\"}");
43 return foo;
44 }
45
46
47 @Path("/empty/array")
48 @Produces("application/json")
49 @Consumes("application/json")
50 @POST
51 public JsonCollectionNamespacedFoo[] emptyArray(JsonCollectionNamespacedFoo[] foo) {
52 Assert.assertEquals("The size of the array is not the expected one", 0, foo.length);
53 return foo;
54 }
55
56 @Path("/empty/list")
57 @Produces("application/json")
58 @Consumes("application/json")
59 @POST
60 public List<JsonCollectionNamespacedFoo> emptyList(List<JsonCollectionNamespacedFoo> foo) {
61 Assert.assertEquals("The length of the list is not the expected one", 0, foo.size());
62 return foo;
63 }
64 }
+0
-71
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JsonCollectionMyResource.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.core.messagebody.WriterUtility;
4 import org.junit.Assert;
5
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.GET;
9 import javax.ws.rs.Consumes;
10 import javax.ws.rs.POST;
11 import java.util.List;
12
13 @Path("/")
14 public class JsonCollectionMyResource {
15
16 protected static final Logger logger = Logger.getLogger(JsonCollectionMyResource.class.getName());
17
18 @Path("/array")
19 @Produces("application/json;charset=UTF-8")
20 @GET
21 public JsonCollectionFoo[] get() throws Exception {
22 JsonCollectionFoo[] foo = {new JsonCollectionFoo("bill{"), new JsonCollectionFoo("monica\"}")};
23 logger.info("START");
24 logger.info(WriterUtility.asString(foo, "application/json"));
25 logger.info("FINISH");
26 return foo;
27 }
28
29 @Path("/array")
30 @Produces("application/json")
31 @Consumes("application/json")
32 @POST
33 public JsonCollectionFoo[] array(JsonCollectionFoo[] foo) {
34 Assert.assertEquals("The size of the array is not the expected one", 2, foo.length);
35 Assert.assertEquals("The first element of the array is not the expected one", foo[0].getTest(), "bill{");
36 Assert.assertEquals("The second element of the array is not the expected one", foo[1].getTest(), "monica\"}");
37 return foo;
38 }
39
40 @Path("/list")
41 @Produces("application/json")
42 @Consumes("application/json")
43 @POST
44 public List<JsonCollectionFoo> list(List<JsonCollectionFoo> foo) {
45 logger.info("POST LIST");
46 Assert.assertEquals("The length of the list is not the expected one", 2, foo.size());
47 Assert.assertEquals("The first element of the list is not the expected one", foo.get(0).getTest(), "bill{");
48 Assert.assertEquals("The second element of the list is not the expected one", foo.get(1).getTest(), "monica\"}");
49 return foo;
50 }
51
52
53 @Path("/empty/array")
54 @Produces("application/json")
55 @Consumes("application/json")
56 @POST
57 public JsonCollectionFoo[] emptyArray(JsonCollectionFoo[] foo) {
58 Assert.assertEquals("The size of the array is not the expected one", 0, foo.length);
59 return foo;
60 }
61
62 @Path("/empty/list")
63 @Produces("application/json")
64 @Consumes("application/json")
65 @POST
66 public List<JsonCollectionFoo> emptyList(List<JsonCollectionFoo> foo) {
67 Assert.assertEquals("The length of the list is not the expected one", 0, foo.size());
68 return foo;
69 }
70 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JsonCollectionNamespacedFoo.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlAttribute;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "foo", namespace = "http://foo.com")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class JsonCollectionNamespacedFoo {
10 @XmlAttribute
11 private String test;
12
13 public JsonCollectionNamespacedFoo() {
14 }
15
16 public JsonCollectionNamespacedFoo(final String test) {
17 this.test = test;
18 }
19
20 public String getTest() {
21 return test;
22 }
23
24 public void setTest(String test) {
25 this.test = test;
26 }
27 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JsonMapFoo.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAttribute;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement
6 public class JsonMapFoo {
7 @XmlAttribute
8 private String name;
9
10 public JsonMapFoo() {
11 }
12
13 public JsonMapFoo(final String name) {
14 this.name = name;
15 }
16
17 public String getName() {
18 return name;
19 }
20 }
+0
-44
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/JsonMapResource.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.Path;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.Consumes;
8 import javax.ws.rs.GET;
9 import java.util.HashMap;
10 import java.util.Map;
11
12 @Path("/map")
13 public class JsonMapResource {
14 @POST
15 @Produces("application/json")
16 @Consumes("application/json")
17 public Map<String, JsonMapFoo> post(Map<String, JsonMapFoo> map) {
18 Assert.assertEquals("The map doesn't have the correct size", 2, map.size());
19 Assert.assertNotNull("The map doesn't contain the value", map.get("bill"));
20 Assert.assertNotNull("The map doesn't contain the value", map.get("monica"));
21 Assert.assertEquals("The map doesn't contain the correct value", map.get("bill").getName(), "bill");
22 Assert.assertEquals("The map doesn't contain the correct value", map.get("monica").getName(), "monica");
23 return map;
24 }
25
26 @POST
27 @Produces("application/json")
28 @Consumes("application/json")
29 @Path("empty")
30 public Map<String, JsonMapFoo> postEmpty(Map<String, JsonMapFoo> map) {
31 Assert.assertEquals("The map was expected to be empty", 0, map.size());
32 return map;
33 }
34
35 @GET
36 @Produces("application/json")
37 public Map<String, JsonMapFoo> get() {
38 HashMap<String, JsonMapFoo> map = new HashMap<String, JsonMapFoo>();
39 map.put("bill", new JsonMapFoo("bill"));
40 map.put("monica", new JsonMapFoo("monica"));
41 return map;
42 }
43 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/MyService.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 public class MyService implements UserEntityWebservice {
3 public UserEntity create(UserEntity entity) {
4 return entity;
5 }
6 }
+0
-51
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/NamespaceMappingResource.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import org.jboss.resteasy.annotations.providers.jaxb.json.Mapped;
3 import org.jboss.resteasy.annotations.providers.jaxb.json.XmlNsMap;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/test/v1")
12 public class NamespaceMappingResource {
13 @POST
14 @Consumes("application/*+json")
15 @Produces("application/*+json")
16 @Mapped(namespaceMap = {
17 @XmlNsMap(jsonName = "test", namespace = "http://www.example.org/b/Test"),
18 @XmlNsMap(jsonName = "can", namespace = "http://www.example.org/a/TestCanonical")
19 })
20 public NamespaceMappingTestExtends updateTestExtends(@Mapped(namespaceMap = {
21 @XmlNsMap(jsonName = "test", namespace = "http://www.example.org/b/Test"),
22 @XmlNsMap(jsonName = "can", namespace = "http://www.example.org/a/TestCanonical")
23 }) NamespaceMappingTestExtends data) {
24 return data;
25 }
26
27 @GET
28 @Produces("application/*+json")
29 @Mapped(namespaceMap = {
30 @XmlNsMap(jsonName = "test", namespace = "http://www.example.org/b/Test"),
31 @XmlNsMap(jsonName = "can", namespace = "http://www.example.org/a/TestCanonical")
32 })
33 public NamespaceMappingTestExtends getTestExtends() {
34 NamespaceMappingTestExtends result = new NamespaceMappingTestExtends();
35 result.setId("12121");
36 result.setName("Test");
37 result.setDesc("Desc");
38 result.setElement2("Test");
39 result.setSomeMoreEl("test");
40 return result;
41 }
42
43 @Path("/manual")
44 @Produces("application/*+json")
45 @GET
46 public String getManual() {
47 return null;
48 }
49
50 }
+0
-107
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/NamespaceMappingTestBase.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlSeeAlso;
6 import javax.xml.bind.annotation.XmlType;
7
8
9 /**
10 * <p>Java class for NamespaceMappingTestBase complex type.
11 * <p>
12 * <p>The following schema fragment specifies the expected content contained within this class.
13 * <p>
14 * <pre>
15 * &lt;complexType name="NamespaceMappingTestBase">
16 * &lt;complexContent>
17 * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
18 * &lt;sequence>
19 * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
20 * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
21 * &lt;element name="desc" type="{http://www.w3.org/2001/XMLSchema}string"/>
22 * &lt;/sequence>
23 * &lt;/restriction>
24 * &lt;/complexContent>
25 * &lt;/complexType>
26 * </pre>
27 */
28 @XmlAccessorType(XmlAccessType.FIELD)
29 @XmlType(name = "NamespaceMappingTestBase", propOrder = {
30 "id",
31 "name",
32 "desc"
33 })
34 @XmlSeeAlso({
35 NamespaceMappingTestExtends.class
36 })
37 public class NamespaceMappingTestBase {
38
39 @XmlElement(required = true)
40 protected String id;
41 @XmlElement(required = true)
42 protected String name;
43 @XmlElement(required = true)
44 protected String desc;
45
46 /**
47 * Gets the value of the id property.
48 *
49 * @return possible object is
50 * {@link String }
51 */
52 public String getId() {
53 return id;
54 }
55
56 /**
57 * Sets the value of the id property.
58 *
59 * @param value allowed object is
60 * {@link String }
61 */
62 public void setId(String value) {
63 this.id = value;
64 }
65
66 /**
67 * Gets the value of the name property.
68 *
69 * @return possible object is
70 * {@link String }
71 */
72 public String getName() {
73 return name;
74 }
75
76 /**
77 * Sets the value of the name property.
78 *
79 * @param value allowed object is
80 * {@link String }
81 */
82 public void setName(String value) {
83 this.name = value;
84 }
85
86 /**
87 * Gets the value of the desc property.
88 *
89 * @return possible object is
90 * {@link String }
91 */
92 public String getDesc() {
93 return desc;
94 }
95
96 /**
97 * Sets the value of the desc property.
98 *
99 * @param value allowed object is
100 * {@link String }
101 */
102 public void setDesc(String value) {
103 this.desc = value;
104 }
105
106 }
+0
-80
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/NamespaceMappingTestExtends.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlType;
6
7
8 /**
9 * <p>Java class for NamespaceMappingTestExtends complex type.
10 * <p>
11 * <p>The following schema fragment specifies the expected content contained within this class.
12 * <p>
13 * <pre>
14 * &lt;complexType name="NamespaceMappingTestExtends">
15 * &lt;complexContent>
16 * &lt;extension base="{http://www.example.org/a/TestCanonical}NamespaceMappingTestBase">
17 * &lt;sequence>
18 * &lt;element name="someMoreEl" type="{http://www.w3.org/2001/XMLSchema}string"/>
19 * &lt;element name="element2" type="{http://www.w3.org/2001/XMLSchema}string"/>
20 * &lt;/sequence>
21 * &lt;/extension>
22 * &lt;/complexContent>
23 * &lt;/complexType>
24 * </pre>
25 */
26 @XmlAccessorType(XmlAccessType.FIELD)
27 @XmlType(name = "NamespaceMappingTestExtends", propOrder = {
28 "someMoreEl",
29 "element2"
30 })
31 public class NamespaceMappingTestExtends
32 extends NamespaceMappingTestBase {
33
34 @XmlElement(required = true)
35 protected String someMoreEl;
36 @XmlElement(required = true)
37 protected String element2;
38
39 /**
40 * Gets the value of the someMoreEl property.
41 *
42 * @return possible object is
43 * {@link String }
44 */
45 public String getSomeMoreEl() {
46 return someMoreEl;
47 }
48
49 /**
50 * Sets the value of the someMoreEl property.
51 *
52 * @param value allowed object is
53 * {@link String }
54 */
55 public void setSomeMoreEl(String value) {
56 this.someMoreEl = value;
57 }
58
59 /**
60 * Gets the value of the element2 property.
61 *
62 * @return possible object is
63 * {@link String }
64 */
65 public String getElement2() {
66 return element2;
67 }
68
69 /**
70 * Sets the value of the element2 property.
71 *
72 * @param value allowed object is
73 * {@link String }
74 */
75 public void setElement2(String value) {
76 this.element2 = value;
77 }
78
79 }
+0
-49
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/ObjectFactory.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.JAXBElement;
3 import javax.xml.bind.annotation.XmlElementDecl;
4 import javax.xml.bind.annotation.XmlRegistry;
5 import javax.xml.namespace.QName;
6
7
8 /**
9 * This class is used from NamespaceMappingTest
10 *
11 * This object contains factory methods for each
12 * Java content interface and Java element interface
13 * generated in the org.example.b.test package.
14 * <p>An ObjectFactory allows you to programatically
15 * construct new instances of the Java representation
16 * for XML content. The Java representation of XML
17 * content can consist of schema derived interfaces
18 * and classes representing the binding of schema
19 * type definitions, element declarations and model
20 * groups. Factory methods for each of these are
21 * provided in this class.
22 */
23 @XmlRegistry
24 public class ObjectFactory {
25
26 private static final QName _TestExtends_QNAME = new QName("http://www.example.org/b/Test", "NamespaceMappingTestExtends");
27
28 /**
29 * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.example.b.test
30 */
31 public ObjectFactory() {
32 }
33
34 /**
35 * Create an instance of {@link NamespaceMappingTestExtends }
36 */
37 public NamespaceMappingTestExtends createTestExtends() {
38 return new NamespaceMappingTestExtends();
39 }
40
41 /**
42 * Create an instance of {@link JAXBElement }{@code <}{@link NamespaceMappingTestExtends }{@code >}}
43 */
44 @XmlElementDecl(namespace = "http://www.example.org/b/Test", name = "NamespaceMappingTestExtends")
45 public JAXBElement<NamespaceMappingTestExtends> createTestExtends(NamespaceMappingTestExtends value) {
46 return new JAXBElement<NamespaceMappingTestExtends>(_TestExtends_QNAME, NamespaceMappingTestExtends.class, null, value);
47 }
48 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/TypeMappingBean.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlRootElement;
3
4 @XmlRootElement
5 public class TypeMappingBean {
6 private String name;
7
8 public TypeMappingBean() {
9
10 }
11
12 public TypeMappingBean(final String name) {
13 this.name = name;
14 }
15
16 public String getName() {
17 return name;
18 }
19
20 public void setName(String name) {
21 this.name = name;
22 }
23
24 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/TypeMappingResource.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 @Path("/test")
6 public class TypeMappingResource {
7
8 @GET
9 @Path("/noproduces")
10 public TypeMappingBean get() {
11 return new TypeMappingBean("name");
12 }
13 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/UserEntity.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlAccessorType(XmlAccessType.NONE)
8 @XmlRootElement(name = "user")
9 public class UserEntity {
10
11 @XmlElement
12 private String username;
13
14 public UserEntity() {
15 super();
16 }
17
18 public String getUsername() {
19 return username;
20 }
21
22 public void setUsername(String username) {
23 this.username = username;
24 }
25
26 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/jettison/resource/UserEntityWebservice.java less more
0 package org.jboss.resteasy.test.providers.jettison.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/user")
7 @Produces({"application/xml", "application/json"})
8 @Consumes({"application/xml", "application/json"})
9 public interface UserEntityWebservice extends CRUDEntityWebservice {
10
11 }
+0
-569
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/ContextProvidersTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4 import java.util.ArrayList;
5 import java.util.HashMap;
6 import java.util.HashSet;
7 import java.util.Iterator;
8 import java.util.List;
9 import java.util.Map;
10 import java.util.Set;
11
12 import javax.enterprise.util.AnnotationLiteral;
13 import javax.ws.rs.client.Client;
14 import javax.ws.rs.client.ClientBuilder;
15 import javax.ws.rs.client.Entity;
16 import javax.ws.rs.client.WebTarget;
17 import javax.ws.rs.core.GenericType;
18 import javax.ws.rs.core.MediaType;
19 import javax.ws.rs.core.Response;
20
21
22 import org.apache.logging.log4j.LogManager;
23 import org.apache.logging.log4j.Logger;
24 import org.jboss.arquillian.container.test.api.Deployment;
25 import org.jboss.arquillian.container.test.api.RunAsClient;
26 import org.jboss.arquillian.junit.Arquillian;
27 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
28 import org.jboss.resteasy.annotations.providers.multipart.PartType;
29 import org.jboss.resteasy.annotations.providers.multipart.XopWithMultipartRelated;
30 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
31 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
32 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
33 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
34 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
35 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
36 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
37 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedInput;
38 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedOutput;
39 import org.jboss.resteasy.test.providers.multipart.resource.ContextProvidersCustomer;
40 import org.jboss.resteasy.test.providers.multipart.resource.ContextProvidersCustomerForm;
41 import org.jboss.resteasy.test.providers.multipart.resource.ContextProvidersName;
42 import org.jboss.resteasy.test.providers.multipart.resource.ContextProvidersResource;
43 import org.jboss.resteasy.test.providers.multipart.resource.ContextProvidersXop;
44 import org.jboss.resteasy.util.HttpResponseCodes;
45 import org.jboss.resteasy.utils.PortProviderUtil;
46 import org.jboss.resteasy.utils.TestUtil;
47 import org.jboss.shrinkwrap.api.Archive;
48 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
49 import org.jboss.shrinkwrap.api.spec.WebArchive;
50 import org.junit.Assert;
51 import org.junit.Test;
52 import org.junit.runner.RunWith;
53
54 import static org.hamcrest.CoreMatchers.hasItems;
55 import static org.hamcrest.CoreMatchers.is;
56
57 /**
58 * @tpSubChapter Multipart provider
59 * @tpChapter Integration tests
60 * @tpTestCaseDetails Regression test for RESTEASY-1119.
61 * Unable to find contextual data of type: javax.ws.rs.ext.Providers if ClientBuilder.newClient is used.
62 * @tpSince RESTEasy 3.0.16
63 */
64 @SuppressWarnings("deprecation")
65 @RunWith(Arquillian.class)
66 @RunAsClient
67 public class ContextProvidersTest {
68
69 protected final Logger logger = LogManager.getLogger(ContextProvidersTest.class.getName());
70
71 protected enum Version {
72 TWO,
73 THREE
74 }
75
76 public static final Annotation PART_TYPE_APPLICATION_XML = new S1() {
77 private static final long serialVersionUID = 1L;
78
79 @Override
80 public String value() {
81 return "application/xml";
82 }
83 };
84 public static final Annotation MULTIPART_FORM = new S2() {
85 private static final long serialVersionUID = 1L;
86 };
87 public static final Annotation XOP_WITH_MULTIPART_RELATED = new S3() {
88 private static final long serialVersionUID = 1L;
89 };
90 static final MediaType MULTIPART_MIXED = new MediaType("multipart", "mixed");
91 static final MediaType MULTIPART_FORM_DATA = new MediaType("multipart", "form-data");
92 static final MediaType MULTIPART_RELATED = new MediaType("multipart", "related");
93 static final javax.ws.rs.core.GenericType<List<ContextProvidersName>> LIST_NAME_TYPE = new javax.ws.rs.core.GenericType<List<ContextProvidersName>>() {
94 };
95
96 @Deployment
97 public static Archive<?> createTestArchive() {
98 WebArchive war = TestUtil.prepareArchive(ContextProvidersTest.class.getSimpleName());
99 war.addClasses(ContextProvidersCustomer.class, ContextProvidersCustomerForm.class, ContextProvidersName.class, ContextProvidersXop.class, PortProviderUtil.class);
100 war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
101 return TestUtil.finishContainerPrepare(war, null, ContextProvidersResource.class);
102 }
103
104 /**
105 * @tpTestDetails Form data in get request is used.
106 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
107 * @tpSince RESTEasy 3.0.16
108 */
109 @Test
110 public void testGetFormData() throws Exception {
111 doTestGetFormData(Version.TWO);
112 doTestGetFormData(Version.THREE);
113 }
114
115 public void doTestGetFormData(Version version) throws Exception {
116 try {
117 MultipartFormDataInput entity = get(version, "/get/form", MultipartFormDataInput.class);
118
119 // Get parts by name.
120 ContextProvidersCustomer c = entity.getFormDataPart("bill", ContextProvidersCustomer.class, null);
121 Assert.assertEquals("Wrong response", "Bill", c.getName());
122 String s = entity.getFormDataPart("bob", String.class, null);
123 Assert.assertEquals("Wrong response", "Bob", s);
124
125 // Iterate over list of parts.
126 Map<String, List<InputPart>> map = entity.getFormDataMap();
127 for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
128 String key = it.next();
129 logger.info("key: " + key);
130 List<InputPart> list = map.get(key);
131 for (Iterator<InputPart> it2 = list.iterator(); it2.hasNext(); ) {
132 InputPart inputPart = it2.next();
133 if (MediaType.APPLICATION_XML_TYPE.equals(inputPart.getMediaType())) {
134 c = inputPart.getBody(ContextProvidersCustomer.class, null);
135 Assert.assertEquals("Wrong response", "Bill", c.getName());
136 } else {
137 s = inputPart.getBody(String.class, null);
138 Assert.assertEquals("Wrong response", "Bob", s);
139 }
140 }
141 }
142 } catch (Exception e) {
143 throw new RuntimeException(TestUtil.getErrorMessageForKnownIssue("RESTEASY-1119"), e);
144 }
145 }
146
147 /**
148 * @tpTestDetails Mixed data in get request is used.
149 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
150 * @tpSince RESTEasy 3.0.16
151 */
152 @Test
153 public void testGetMixed() throws Exception {
154 doTestGetMixed(Version.TWO);
155 doTestGetMixed(Version.THREE);
156 }
157
158 void doTestGetMixed(Version version) throws Exception {
159 try {
160 MultipartInput entity = get(version, "/get/mixed", MultipartInput.class);
161
162 // Iterate over list of parts.
163 List<InputPart> parts = entity.getParts();
164 for (Iterator<InputPart> it = parts.iterator(); it.hasNext(); ) {
165 InputPart inputPart = it.next();
166 if (MediaType.APPLICATION_XML_TYPE.equals(inputPart.getMediaType())) {
167 ContextProvidersCustomer c = inputPart.getBody(ContextProvidersCustomer.class, null);
168 Assert.assertEquals("Wrong response", "Bill", c.getName());
169 } else {
170 String s = inputPart.getBody(String.class, null);
171 Assert.assertEquals("Wrong response", "Bob", s);
172 }
173 }
174 } catch (Exception e) {
175 throw new RuntimeException(TestUtil.getErrorMessageForKnownIssue("RESTEASY-1119"), e);
176 }
177 }
178
179 /**
180 * @tpTestDetails List data in get request is used.
181 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
182 * @tpSince RESTEasy 3.0.16
183 */
184 @Test
185 public void testGetList() throws Exception {
186 doTestGetList(Version.TWO);
187 doTestGetList(Version.THREE);
188 }
189
190 void doTestGetList(Version version) throws Exception {
191 try {
192 MultipartInput entity = get(version, "/get/list", MultipartInput.class);
193
194 // Iterate over list of parts.
195 List<InputPart> parts = entity.getParts();
196 Set<String> customers = new HashSet<String>();
197 for (Iterator<InputPart> it = parts.iterator(); it.hasNext(); ) {
198 InputPart inputPart = it.next();
199 customers.add(inputPart.getBody(ContextProvidersCustomer.class, null).getName());
200 }
201 Assert.assertThat("Wrong count of customers from response", new Integer(customers.size()), is(2));
202 Assert.assertThat("Received customers list do not contain all items", customers, hasItems("Bill"));
203 Assert.assertThat("Received customers list do not contain all items", customers, hasItems("Bob"));
204 } catch (Exception e) {
205 throw new RuntimeException(TestUtil.getErrorMessageForKnownIssue("RESTEASY-1119"), e);
206 }
207 }
208
209 /**
210 * @tpTestDetails Map data in get request is used.
211 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
212 * @tpSince RESTEasy 3.0.16
213 */
214 @Test
215 public void testGetMap() throws Exception {
216 doTestGetMap(Version.TWO);
217 doTestGetMap(Version.THREE);
218 }
219
220 public void doTestGetMap(Version version) throws Exception {
221 try {
222 MultipartFormDataInput entity = get(version, "/get/map", MultipartFormDataInput.class);
223
224 // Get parts by name.
225 ContextProvidersCustomer c = entity.getFormDataPart("bill", ContextProvidersCustomer.class, null);
226 Assert.assertEquals("Wrong response", "Bill", c.getName());
227 c = entity.getFormDataPart("bob", ContextProvidersCustomer.class, null);
228 Assert.assertEquals("Wrong response", "Bob", c.getName());
229
230 // Iterate over map of parts.
231 Map<String, List<InputPart>> map = entity.getFormDataMap();
232 Set<String> customers = new HashSet<String>();
233 for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
234 String key = it.next();
235 List<InputPart> list = map.get(key);
236 for (Iterator<InputPart> it2 = list.iterator(); it2.hasNext(); ) {
237 InputPart inputPart = it2.next();
238 customers.add(inputPart.getBody(ContextProvidersCustomer.class, null).getName());
239 }
240 }
241 Assert.assertThat("Wrong count of customers from response", new Integer(customers.size()), is(2));
242 Assert.assertThat("Received customers list do not contain all items", customers, hasItems("Bill"));
243 Assert.assertThat("Received customers list do not contain all items", customers, hasItems("Bob"));
244 } catch (Exception e) {
245 throw new RuntimeException(TestUtil.getErrorMessageForKnownIssue("RESTEASY-1119"), e);
246 }
247 }
248
249 /**
250 * @tpTestDetails Related data in get request is used.
251 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
252 * @tpSince RESTEasy 3.0.16
253 */
254 @Test
255 public void testGetRelated() throws Exception {
256 doTestGetRelated(Version.TWO);
257 doTestGetRelated(Version.THREE);
258 }
259
260 void doTestGetRelated(Version version) throws Exception {
261 try {
262 MultipartRelatedInput entity = get(version, "/get/related", MultipartRelatedInput.class);
263
264 // Iterate over map of parts.
265 Map<String, InputPart> map = entity.getRelatedMap();
266 Set<String> keys = map.keySet();
267 Assert.assertEquals(2, keys.size());
268 Assert.assertThat("Wrong count of keys from response", new Integer(keys.size()), is(2));
269 Assert.assertTrue(keys.contains("bill"));
270 Assert.assertTrue(keys.contains("bob"));
271 Assert.assertThat("Missing key from response", keys, hasItems("bill"));
272 Assert.assertThat("Missing key from response", keys, hasItems("bob"));
273 Set<String> parts = new HashSet<String>();
274 for (Iterator<InputPart> it = map.values().iterator(); it.hasNext(); ) {
275 parts.add(it.next().getBody(String.class, null));
276 }
277 Assert.assertThat("Received customers list do not contain all items", parts, hasItems("Bill"));
278 Assert.assertThat("Received customers list do not contain all items", parts, hasItems("Bob"));
279 } catch (Exception e) {
280 throw new RuntimeException(TestUtil.getErrorMessageForKnownIssue("RESTEASY-1119"), e);
281 }
282 }
283
284 /**
285 * @tpTestDetails Multipart form data in get request is used.
286 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
287 * @tpSince RESTEasy 3.0.16
288 */
289 @Test
290 public void testGetMultipartForm() throws Exception {
291 doTestGetMultipartForm(Version.TWO);
292 doTestGetMultipartForm(Version.THREE);
293 }
294
295 void doTestGetMultipartForm(Version version) throws Exception {
296 Annotation[] annotations = new Annotation[1];
297 annotations[0] = MULTIPART_FORM;
298 ContextProvidersCustomerForm form = get(version, "/get/multipartform", ContextProvidersCustomerForm.class, annotations);
299 ContextProvidersCustomer customer = form.getCustomer();
300 Assert.assertEquals("Wrong response", "Bill", customer.getName());
301 }
302
303 /**
304 * @tpTestDetails Xop data in get request is used.
305 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
306 * @tpSince RESTEasy 3.0.16
307 */
308 @Test
309 public void testGetXop() throws Exception {
310 doTestGetXop(Version.TWO);
311 doTestGetXop(Version.THREE);
312 }
313
314 void doTestGetXop(Version version) throws Exception {
315 Annotation[] annotations = new Annotation[1];
316 annotations[0] = XOP_WITH_MULTIPART_RELATED;
317 ContextProvidersXop xop = get(version, "/get/xop", ContextProvidersXop.class, annotations);
318 Assert.assertEquals("Wrong response", "goodbye world", new String(xop.getBytes()));
319 }
320
321 /**
322 * @tpTestDetails Mixed data in post request is used.
323 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
324 * @tpSince RESTEasy 3.0.16
325 */
326 @Test
327 public void testPostMixed() throws Exception {
328 doTestPostMixed(Version.TWO);
329 doTestPostMixed(Version.THREE);
330 }
331
332 @SuppressWarnings("unchecked")
333 void doTestPostMixed(Version version) throws Exception {
334 MultipartOutput output = new MultipartOutput();
335 output.addPart(new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE);
336 output.addPart("Bob", MediaType.TEXT_PLAIN_TYPE);
337 Annotation[] annotations = new Annotation[1];
338 annotations[0] = PART_TYPE_APPLICATION_XML;
339 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
340 names = post(version, "/post/mixed", output, MULTIPART_MIXED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
341 Assert.assertEquals(2, names.size());
342 Assert.assertTrue(names.contains(new ContextProvidersName("Bill")));
343 Assert.assertTrue(names.contains(new ContextProvidersName("Bob")));
344 }
345
346 /**
347 * @tpTestDetails Form data in post request is used.
348 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
349 * @tpSince RESTEasy 3.0.16
350 */
351 @Test
352 public void testPostFormData() throws Exception {
353 doTestPostFormData(Version.TWO);
354 doTestPostFormData(Version.THREE);
355 }
356
357 @SuppressWarnings("unchecked")
358 public void doTestPostFormData(Version version) throws Exception {
359
360 MultipartFormDataOutput output = new MultipartFormDataOutput();
361 output.addFormData("bill", new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE);
362 output.addFormData("bob", "Bob", MediaType.TEXT_PLAIN_TYPE);
363 Annotation[] annotations = new Annotation[1];
364 annotations[0] = PART_TYPE_APPLICATION_XML;
365 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
366 names = post(version, "/post/form", output, MULTIPART_FORM_DATA, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
367 Assert.assertThat("Wrong count of customers from response", new Integer(names.size()), is(2));
368 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bill")));
369 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bob")));
370 }
371
372 /**
373 * @tpTestDetails List data in post request is used.
374 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
375 * @tpSince RESTEasy 3.0.16
376 */
377 @Test
378 public void testPostList() throws Exception {
379 doTestPostList(Version.TWO);
380 doTestPostList(Version.THREE);
381 }
382
383 @SuppressWarnings("unchecked")
384 public void doTestPostList(Version version) throws Exception {
385 List<ContextProvidersCustomer> customers = new ArrayList<ContextProvidersCustomer>();
386 customers.add(new ContextProvidersCustomer("Bill"));
387 customers.add(new ContextProvidersCustomer("Bob"));
388 Annotation[] annotations = new Annotation[1];
389 annotations[0] = PART_TYPE_APPLICATION_XML;
390 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
391 names = post(version, "/post/list", customers, MULTIPART_MIXED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
392 Assert.assertThat("Wrong count of customers from response", new Integer(names.size()), is(2));
393 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bill")));
394 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bob")));
395 }
396
397 /**
398 * @tpTestDetails Map data in post request is used.
399 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
400 * @tpSince RESTEasy 3.0.16
401 */
402 @Test
403 public void testPostMap() throws Exception {
404 doTestPostMap(Version.TWO);
405 doTestPostMap(Version.THREE);
406 }
407
408 @SuppressWarnings("unchecked")
409 public void doTestPostMap(Version version) throws Exception {
410 Map<String, ContextProvidersCustomer> customers = new HashMap<String, ContextProvidersCustomer>();
411 customers.put("bill", new ContextProvidersCustomer("Bill"));
412 customers.put("bob", new ContextProvidersCustomer("Bob"));
413 Annotation[] annotations = new Annotation[1];
414 annotations[0] = PART_TYPE_APPLICATION_XML;
415 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
416 names = post(version, "/post/map", customers, MULTIPART_FORM_DATA, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
417 Assert.assertThat("Wrong count of customers from response", new Integer(names.size()), is(2));
418 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("bill:Bill")));
419 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("bob:Bob")));
420 }
421
422 /**
423 * @tpTestDetails Related data in post request is used.
424 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
425 * @tpSince RESTEasy 3.0.16
426 */
427 @Test
428 public void testPostRelated() throws Exception {
429 doTestPostRelated(Version.TWO);
430 doTestPostRelated(Version.THREE);
431 }
432
433 @SuppressWarnings("unchecked")
434 void doTestPostRelated(Version version) throws Exception {
435 MultipartRelatedOutput output = new MultipartRelatedOutput();
436 output.setStartInfo("text/html");
437 output.addPart("Bill", new MediaType("image", "png"), "bill", "binary");
438 output.addPart("Bob", new MediaType("image", "png"), "bob", "binary");
439 Annotation[] annotations = new Annotation[1];
440 annotations[0] = PART_TYPE_APPLICATION_XML;
441 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
442 names = post(version, "/post/related", output, MULTIPART_RELATED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
443 Assert.assertThat("Wrong count of customers from response", new Integer(names.size()), is(2));
444 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bill")));
445 Assert.assertThat("Received customers list do not contain all items", names, hasItems(new ContextProvidersName("Bob")));
446 }
447
448 /**
449 * @tpTestDetails Multipart form data in post request is used.
450 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
451 * @tpSince RESTEasy 3.0.16
452 */
453 @Test
454 public void testPostMultipartForm() throws Exception {
455 doTestPostMultipartForm(Version.TWO);
456 doTestPostMultipartForm(Version.THREE);
457 }
458
459 void doTestPostMultipartForm(Version version) throws Exception {
460 ContextProvidersCustomerForm form = new ContextProvidersCustomerForm();
461 form.setCustomer(new ContextProvidersCustomer("Bill"));
462 Annotation[] annotations = new Annotation[1];
463 annotations[0] = MULTIPART_FORM;
464 String name = post(version, "/post/multipartform", form, MULTIPART_FORM_DATA, String.class, null, annotations);
465 Assert.assertEquals("Wrong response", "Bill", name);
466 }
467
468 /**
469 * @tpTestDetails Xop data in post request is used.
470 * @tpPassCrit RE should be able to find contextual data of type: javax.ws.rs.ext.Providers.
471 * @tpSince RESTEasy 3.0.16
472 */
473 @Test
474 public void testPostXop() throws Exception {
475 doTestPostXop(Version.TWO);
476 doTestPostXop(Version.THREE);
477 }
478
479 void doTestPostXop(Version version) throws Exception {
480 ContextProvidersXop xop = new ContextProvidersXop("hello world".getBytes());
481 Annotation[] annotations = new Annotation[1];
482 annotations[0] = XOP_WITH_MULTIPART_RELATED;
483 String s = post(version, "/post/xop", xop, MULTIPART_RELATED, String.class, null, annotations);
484 Assert.assertEquals("Wrong response", "hello world", s);
485 }
486
487 <T> T get(Version version, String path, Class<T> clazz) throws Exception {
488 return get(version, path, clazz, null);
489 }
490
491 <T> T get(Version version, String path, Class<T> clazz, Annotation[] annotations) throws Exception {
492 try {
493 switch (version) {
494 case TWO: {
495 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
496
497 ClientResponse<T> response = request.get(clazz);
498 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
499 T entity = response.getEntity(clazz, null, annotations);
500 return entity;
501 }
502
503 case THREE: {
504 Client client = ClientBuilder.newClient();
505 WebTarget target = client.target(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
506 Response response = target.request().get();
507 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
508 T entity = response.readEntity(clazz, annotations);
509 return entity;
510 }
511
512 default:
513 throw new Exception("Unknown version of response: " + version);
514 }
515 } catch (Exception e) {
516 throw new RuntimeException(TestUtil.getErrorMessageForKnownIssue("RESTEASY-1119"), e);
517 }
518 }
519
520 @SuppressWarnings({"unchecked"})
521 <S, T> T post(Version version, String path, S payload, MediaType mediaType, Class<T> returnType, Type genericReturnType, Annotation[] annotations) throws Exception {
522 switch (version) {
523 case TWO: {
524 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
525 request.body(mediaType, payload, payload.getClass(), null, annotations);
526 ClientResponse<T> response = request.post();
527 T entity = null;
528 if (genericReturnType != null) {
529 entity = response.getEntity(returnType, genericReturnType);
530 } else {
531 entity = response.getEntity(returnType);
532 }
533
534 return entity;
535 }
536
537 case THREE: {
538 Client client = ClientBuilder.newClient();
539 WebTarget target = client.target(PortProviderUtil.generateURL(path, ContextProvidersTest.class.getSimpleName()));
540 Entity<S> entity = Entity.entity(payload, mediaType, annotations);
541 Response response = target.request().post(entity);
542 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
543 T result = null;
544 if (genericReturnType != null) {
545 result = response.readEntity(new GenericType<T>(genericReturnType));
546 } else {
547 result = response.readEntity(returnType);
548 }
549 return result;
550 }
551
552 default:
553 throw new Exception("Unknown version of response: " + version);
554 }
555 }
556
557 public abstract static class S1 extends AnnotationLiteral<PartType> implements PartType {
558 private static final long serialVersionUID = 1L;
559 }
560
561 public abstract static class S2 extends AnnotationLiteral<MultipartForm> implements MultipartForm {
562 private static final long serialVersionUID = 1L;
563 }
564
565 public abstract static class S3 extends AnnotationLiteral<XopWithMultipartRelated> implements XopWithMultipartRelated {
566 private static final long serialVersionUID = 1L;
567 }
568 }
+0
-107
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/EmbeddedMultipartTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
9 import org.jboss.resteasy.test.providers.multipart.resource.EmbeddedMultipartCustomer;
10 import org.jboss.resteasy.test.providers.multipart.resource.EmbeddedMultipartResource;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.Assert;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.InternalServerErrorException;
21 import javax.ws.rs.client.Entity;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Multipart provider
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Regression test for RESTEASY-929
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class EmbeddedMultipartTest {
34
35 protected static final MediaType MULTIPART_MIXED = new MediaType("multipart", "mixed");
36
37 @Deployment
38 public static Archive<?> deploy() {
39 WebArchive war = TestUtil.prepareArchive(EmbeddedMultipartTest.class.getSimpleName());
40 war.addClass(EmbeddedMultipartCustomer.class);
41 return TestUtil.finishContainerPrepare(war, null, EmbeddedMultipartResource.class);
42 }
43
44 private String generateURL(String path) {
45 return PortProviderUtil.generateURL(path, EmbeddedMultipartTest.class.getSimpleName());
46 }
47
48 /**
49 * @tpTestDetails Test embedded part of multipart message
50 * @tpSince RESTEasy 3.0.16
51 */
52 @Test
53 public void testEmbedded() {
54 ResteasyClient client = new ResteasyClientBuilder().build();
55 ResteasyWebTarget target = client.target(generateURL("/embedded"));
56 EmbeddedMultipartCustomer customer = new EmbeddedMultipartCustomer("bill");
57 MultipartOutput innerPart = new MultipartOutput();
58 innerPart.addPart(customer, MediaType.APPLICATION_XML_TYPE);
59 MultipartOutput outerPart = new MultipartOutput();
60 outerPart.addPart(innerPart, MULTIPART_MIXED);
61 Entity<MultipartOutput> entity = Entity.entity(outerPart, MULTIPART_MIXED);
62 String response = target.request().post(entity, String.class);
63 Assert.assertEquals("Wrong content of response", "bill", response);
64 client.close();
65 }
66
67 /**
68 * @tpTestDetails Test complete multipart message
69 * @tpSince RESTEasy 3.0.16
70 */
71 @Test
72 public void testCustomer() {
73 ResteasyClient client = new ResteasyClientBuilder().build();
74 ResteasyWebTarget target = client.target(generateURL("/customer"));
75 EmbeddedMultipartCustomer customer = new EmbeddedMultipartCustomer("bill");
76 MultipartOutput outerPart = new MultipartOutput();
77 outerPart.addPart(customer, MediaType.APPLICATION_XML_TYPE);
78 Entity<MultipartOutput> entity = Entity.entity(outerPart, MULTIPART_MIXED);
79 String response = target.request().post(entity, String.class);
80 Assert.assertEquals("Wrong content of response", "bill", response);
81 client.close();
82 }
83
84 /**
85 * @tpTestDetails Test exception in embedded multipart message
86 * @tpSince RESTEasy 3.0.16
87 */
88 @Test
89 public void testInvalid() {
90 ResteasyClient client = new ResteasyClientBuilder().build();
91 try {
92 ResteasyWebTarget target = client.target(generateURL("/invalid"));
93 EmbeddedMultipartCustomer customer = new EmbeddedMultipartCustomer("bill");
94 MultipartOutput outerPart = new MultipartOutput();
95 outerPart.addPart(customer, MediaType.APPLICATION_XML_TYPE);
96 Entity<MultipartOutput> entity = Entity.entity(outerPart, MULTIPART_MIXED);
97 target.request().post(entity, String.class);
98 Assert.fail("Exception is expected");
99 } catch (InternalServerErrorException e) {
100 Response response = e.getResponse();
101 Assert.assertEquals("Wrong type of exception", HttpResponseCodes.SC_INTERNAL_SERVER_ERROR, response.getStatus());
102 } finally {
103 client.close();
104 }
105 }
106 }
+0
-60
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/EmptyInputStreamMultipartProviderTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.test.providers.multipart.resource.EmptyInputStreamMultipartProviderMyBean;
7 import org.jboss.resteasy.test.providers.multipart.resource.EmptyInputStreamMultipartProviderResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16 import javax.ws.rs.client.Client;
17 import javax.ws.rs.client.ClientBuilder;
18 import javax.ws.rs.client.WebTarget;
19 import javax.ws.rs.core.Response;
20
21 /**
22 * @tpSubChapter Multipart provider
23 * @tpChapter Integration tests
24 * @tpTestCaseDetails Regression test for RESTEASY-204.
25 * POJO with empty InputStream field returned as "mutlipart/form-data" produces no headers in multipart
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class EmptyInputStreamMultipartProviderTest {
31
32 protected final Logger logger = Logger.getLogger(EmptyInputStreamMultipartProviderTest.class.getName());
33
34 @Deployment
35 public static Archive<?> deploy() {
36 WebArchive war = TestUtil.prepareArchive(EmptyInputStreamMultipartProviderTest.class.getSimpleName());
37 return TestUtil.finishContainerPrepare(war, null, EmptyInputStreamMultipartProviderResource.class, EmptyInputStreamMultipartProviderMyBean.class);
38 }
39
40 private String generateURL(String path) {
41 return PortProviderUtil.generateURL(path, EmptyInputStreamMultipartProviderTest.class.getSimpleName());
42 }
43
44 /**
45 * @tpTestDetails Resource returning POJO with empty InputStream field, the response is checked to contain the header
46 * @tpSince RESTEasy 3.0.16
47 */
48 @Test
49 public void test() throws Exception {
50 Client client = ClientBuilder.newClient();
51 WebTarget target = client.target(generateURL("/rest/zba"));
52 Response response = target.request().get();
53 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
54 String string = response.readEntity(String.class);
55 logger.info(string);
56 Assert.assertTrue("The response doesn't contain the expected header", string.indexOf("Content-Length") > -1);
57 }
58
59 }
+0
-67
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/GenericTypeMultipartTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
7 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
8 import org.jboss.resteasy.spi.ResteasyProviderFactory;
9 import org.jboss.resteasy.test.providers.multipart.resource.GenericTypeResource;
10 import org.jboss.resteasy.test.providers.multipart.resource.GenericTypeStringListReaderWriter;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Entity;
20 import javax.ws.rs.core.GenericType;
21 import javax.ws.rs.core.MediaType;
22 import java.util.ArrayList;
23 import java.util.List;
24
25 /**
26 * @tpSubChapter Multipart provider
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Regression test for JBEAP-1795
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 public class GenericTypeMultipartTest {
33 public static final GenericType<List<String>> stringListType = new GenericType<List<String>>() {
34 };
35
36
37 @Deployment
38 public static Archive<?> deploy() {
39 WebArchive war = TestUtil.prepareArchive(GenericTypeMultipartTest.class.getSimpleName());
40 war.addClasses(TestUtil.class, PortProviderUtil.class);
41 return TestUtil.finishContainerPrepare(war, null, GenericTypeResource.class, GenericTypeStringListReaderWriter.class);
42 }
43
44 private String generateURL(String path) {
45 return PortProviderUtil.generateURL(path, GenericTypeMultipartTest.class.getSimpleName());
46 }
47
48 /**
49 * @tpTestDetails List is in request.
50 * @tpSince RESTEasy 3.0.16
51 */
52 @Test
53 public void testGenericType() throws Exception {
54 ResteasyClient client = new ResteasyClientBuilder().register(GenericTypeStringListReaderWriter.class).build();
55 ResteasyWebTarget target = client.target(generateURL("/test"));
56 MultipartFormDataOutput output = new MultipartFormDataOutput();
57 List<String> list = new ArrayList<>();
58 list.add("darth");
59 list.add("sidious");
60 output.addFormData("key", list, stringListType, MediaType.APPLICATION_XML_TYPE);
61 Entity<MultipartFormDataOutput> entity = Entity.entity(output, MediaType.MULTIPART_FORM_DATA_TYPE);
62 String response = target.request().post(entity, String.class);
63 Assert.assertEquals("Wrong response content", "darth sidious ", response);
64 }
65
66 }
+0
-152
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/HeaderFlushedOutputStreamTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
6 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
7 import org.jboss.resteasy.test.providers.multipart.resource.HeaderFlushedOutputStreamBean;
8 import org.jboss.resteasy.test.providers.multipart.resource.HeaderFlushedOutputStreamService;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.Assert;
15 import org.junit.BeforeClass;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.mail.BodyPart;
20 import javax.mail.internet.MimeMultipart;
21 import javax.mail.util.ByteArrayDataSource;
22 import javax.servlet.http.HttpServletResponse;
23 import javax.ws.rs.client.Client;
24 import javax.ws.rs.client.ClientBuilder;
25 import javax.ws.rs.client.Entity;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.Response;
28 import java.io.BufferedInputStream;
29 import java.io.File;
30 import java.io.InputStream;
31
32 /**
33 * @tpSubChapter Multipart provider
34 * @tpChapter Integration tests
35 * @tpTestCaseDetails Regression test for RESTEASY-190
36 * @tpSince RESTEasy 3.0.16
37 */
38 @RunWith(Arquillian.class)
39 @RunAsClient
40 public class HeaderFlushedOutputStreamTest {
41 static Client client;
42
43 @BeforeClass
44 public static void before() throws Exception {
45 client = ClientBuilder.newClient();
46 }
47
48 @AfterClass
49 public static void after() throws Exception {
50 client.close();
51 }
52
53 static final String testFilePath;
54
55 static {
56 testFilePath = TestUtil.getResourcePath(HeaderFlushedOutputStreamTest.class,
57 "HeaderFlushedOutputStreamTestData.txt");
58 }
59
60 @Deployment
61 public static Archive<?> deploy() {
62 WebArchive war = TestUtil.prepareArchive(HeaderFlushedOutputStreamTest.class.getSimpleName());
63 war.addClass(HeaderFlushedOutputStreamBean.class);
64 return TestUtil.finishContainerPrepare(war, null, HeaderFlushedOutputStreamService.class);
65 }
66
67 private static String generateURL(String path) {
68 return PortProviderUtil.generateURL(path, HeaderFlushedOutputStreamTest.class.getSimpleName());
69 }
70
71 private static final String TEST_URI = generateURL("/mime");
72
73 /**
74 * @tpTestDetails Loopback to examine form-data
75 * @tpSince RESTEasy 3.0.16
76 */
77 @Test
78 public void testPost() throws Exception {
79 // prepare file
80 File file = new File(testFilePath);
81 Assert.assertTrue("File " + testFilePath + " doesn't exists", file.exists());
82 // test logic
83 MultipartOutput mpo = new MultipartOutput();
84 mpo.addPart("This is Value 1", MediaType.TEXT_PLAIN_TYPE);
85 mpo.addPart("This is Value 2", MediaType.TEXT_PLAIN_TYPE);
86 mpo.addPart(file, MediaType.TEXT_PLAIN_TYPE);
87 Response response = client.target(TEST_URI).request().post(Entity.entity(mpo, MediaType.MULTIPART_FORM_DATA_TYPE));
88 BufferedInputStream in = new BufferedInputStream(response.readEntity(InputStream.class));
89 String contentType = response.getHeaderString("content-type");
90 ByteArrayDataSource ds = new ByteArrayDataSource(in, contentType);
91 MimeMultipart mimeMultipart = new MimeMultipart(ds);
92 Assert.assertEquals("Wrong count of parts of response", mimeMultipart.getCount(), 3);
93 response.close();
94 }
95
96
97 /**
98 * @tpTestDetails Test post method
99 * @tpSince RESTEasy 3.0.16
100 */
101 @Test
102 public void testPostForm() throws Exception {
103 // prepare file
104 File file = new File(testFilePath);
105 Assert.assertTrue("File " + testFilePath + " doesn't exists", file.exists());
106 // test logic
107 MultipartFormDataOutput mpfdo = new MultipartFormDataOutput();
108 mpfdo.addFormData("part1", "This is Value 1", MediaType.TEXT_PLAIN_TYPE);
109 mpfdo.addFormData("part2", "This is Value 2", MediaType.TEXT_PLAIN_TYPE);
110 mpfdo.addFormData("data.txt", file, MediaType.TEXT_PLAIN_TYPE);
111
112 Response response = client.target(TEST_URI).request().post(Entity.entity(mpfdo, MediaType.MULTIPART_FORM_DATA_TYPE));
113 BufferedInputStream in = new BufferedInputStream(response.readEntity(InputStream.class));
114
115 String contentType = response.getHeaderString("content-type");
116 ByteArrayDataSource ds = new ByteArrayDataSource(in, contentType);
117 MimeMultipart mimeMultipart = new MimeMultipart(ds);
118 Assert.assertEquals("Wrong count of parts of response", mimeMultipart.getCount(), 3);
119 response.close();
120 }
121
122 /**
123 * @tpTestDetails Test get method
124 * @tpSince RESTEasy 3.0.16
125 */
126 @Test
127 public void testGet() throws Exception {
128
129 Response response = client.target(TEST_URI).request().get();
130
131
132 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
133 BufferedInputStream in = new BufferedInputStream(response.readEntity(InputStream.class));
134 String contentType = response.getHeaderString("content-type");
135 ByteArrayDataSource ds = new ByteArrayDataSource(in, contentType);
136 MimeMultipart mimeMultipart = new MimeMultipart(ds);
137 Assert.assertEquals("Wrong count of parts of response", mimeMultipart.getCount(), 1);
138
139 BodyPart part = mimeMultipart.getBodyPart(0);
140 InputStream is = part.getInputStream();
141
142 Assert.assertEquals("Wrong count of parts of response", 3, part.getSize());
143
144 char[] output = new char[3];
145 output[0] = (char) is.read();
146 output[1] = (char) is.read();
147 output[2] = (char) is.read();
148 String str = new String(output);
149 Assert.assertEquals("Wrong content of first part of response", "bla", str);
150 }
151 }
+0
-462
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/InputPartDefaultCharsetOverwriteTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16;
6 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8;
7 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16;
8 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8;
9 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16;
10 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8;
11 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultCharsetOverwriteService;
12 import org.jboss.resteasy.util.Encode;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.asset.StringAsset;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.AfterClass;
19 import org.junit.Assert;
20 import org.junit.BeforeClass;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Client;
25 import javax.ws.rs.client.ClientBuilder;
26 import javax.ws.rs.client.Entity;
27 import javax.ws.rs.core.Response;
28 import java.nio.charset.Charset;
29 import java.util.Random;
30
31 /**
32 * @tpSubChapter Multipart provider
33 * @tpChapter Integration tests
34 * @tpTestCaseDetails Regression test for RESTEASY-723
35 * @tpSince RESTEasy 3.0.16
36 */
37 @RunWith(Arquillian.class)
38 @RunAsClient
39 public class InputPartDefaultCharsetOverwriteTest {
40 private static final org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger(InputPartDefaultCharsetOverwriteTest.class);
41
42 static Client client;
43
44 public static final String UTF_8 = "UTF-8";
45 public static final String UTF_16 = "UTF-16";
46 public static final String TEXT_PLAIN = "text/plain";
47 public static final String TEXT_HTTP = "text/http";
48 public static final String TEXT_PLAIN_WITH_CHARSET_US_ASCII = normalize("text/plain; charset=US-ASCII");
49 public static final String TEXT_PLAIN_WITH_CHARSET_UTF_16 = normalize("text/plain; charset=UTF-16");
50 public static final String TEXT_HTTP_WITH_CHARSET_US_ASCII = normalize("text/http; charset=US-ASCII");
51 public static final String TEXT_HTTP_WITH_CHARSET_UTF_8 = normalize("text/http; charset=UTF-8");
52 public static final String TEXT_HTTP_WITH_CHARSET_UTF_16 = normalize("text/http; charset=UTF-16");
53 public static final String APPLICATION_XML = normalize("application/xml");
54 public static final String APPLICATION_XML_WITH_CHARSET_US_ASCII = normalize("application/xml; charset=US-ASCII");
55 public static final String APPLICATION_XML_WITH_CHARSET_UTF_8 = normalize("application/xml; charset=UTF-8");
56 public static final String APPLICATION_XML_WITH_CHARSET_UTF_16 = normalize("application/xml; charset=UTF-16");
57 public static final String APPLICATION_OCTET_STREAM = normalize("application/octet-stream");
58 public static final String abc_us_ascii = "abc";
59 public static final byte[] abc_us_ascii_bytes = abc_us_ascii.getBytes(Charset.forName("us-ascii"));
60 public static final String abc_utf8 = new String("abc\u20AC");
61 public static final byte[] abc_utf8_bytes = abc_utf8.getBytes(Charset.forName("utf-8"));
62 public static final String abc_utf16 = new String("abc\u20AC");
63 public static final byte[] abc_utf16_bytes = abc_utf16.getBytes(Charset.forName("utf-16"));
64 public static final String TEXT_PLAIN_WITH_CHARSET_UTF_8 = normalize("text/plain; charset=UTF-8");
65
66 @BeforeClass
67 public static void init() {
68 client = ClientBuilder.newClient();
69 }
70
71 @AfterClass
72 public static void after() throws Exception {
73 client.close();
74 client = null;
75 }
76
77 @Deployment(name = "InputPartDefaultCharsetOverwriteTest")
78 public static Archive<?> createTestArchiveBasic() {
79 WebArchive war = TestUtil.prepareArchive(InputPartDefaultCharsetOverwriteTest.class.getSimpleName());
80 war.addClasses(InputPartDefaultCharsetOverwriteTest.class);
81 war.addClasses(TestUtil.class, PortProviderUtil.class);
82 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultCharsetOverwriteService.class);
83 }
84
85 @Deployment(name = "InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8")
86 public static Archive<?> createTestArchiveContentTypeCharsetUTF8() {
87 WebArchive war = TestUtil.prepareArchive(InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8.class.getSimpleName());
88 war.addClasses(InputPartDefaultCharsetOverwriteTest.class);
89 war.addClasses(TestUtil.class, PortProviderUtil.class);
90 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8.class,
91 InputPartDefaultCharsetOverwriteService.class);
92 }
93
94 @Deployment(name = "InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16")
95 public static Archive<?> createTestArchiveContentTypeCharsetUTF8ContentTypeCharsetUTF16() {
96 WebArchive war = TestUtil.prepareArchive(InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16.class.getSimpleName());
97 war.addClasses(InputPartDefaultCharsetOverwriteTest.class);
98 war.addClasses(TestUtil.class, PortProviderUtil.class);
99 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16.class,
100 InputPartDefaultCharsetOverwriteService.class);
101 }
102
103 @Deployment(name = "InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8")
104 public static Archive<?> createTestArchiveContentTypeNoCharsetUTF8() {
105 WebArchive war = TestUtil.prepareArchive(InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8.class.getSimpleName());
106 war.addClasses(InputPartDefaultCharsetOverwriteTest.class);
107 war.addClasses(TestUtil.class, PortProviderUtil.class);
108 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8.class,
109 InputPartDefaultCharsetOverwriteService.class);
110 }
111
112 @Deployment(name = "InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16")
113 public static Archive<?> createTestArchiveContentTypeNoCharsetUTF16() {
114 WebArchive war = TestUtil.prepareArchive(InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16.class.getSimpleName());
115 war.addClasses(InputPartDefaultCharsetOverwriteTest.class);
116 war.addClasses(TestUtil.class, PortProviderUtil.class);
117 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16.class,
118 InputPartDefaultCharsetOverwriteService.class);
119 }
120
121 @Deployment(name = "InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8")
122 public static Archive<?> createTestArchiveNoContentTypeCharsetUTF8() {
123 WebArchive war = TestUtil.prepareArchive(InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.class.getSimpleName());
124 war.addClasses(InputPartDefaultCharsetOverwriteTest.class);
125 war.addClasses(TestUtil.class, PortProviderUtil.class);
126 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.class,
127 InputPartDefaultCharsetOverwriteService.class);
128 }
129
130 @Deployment(name = "InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16")
131 public static Archive<?> createTestArchiveNoContentTypeCharsetUTF16() {
132 WebArchive war = TestUtil.prepareArchive(InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16.class.getSimpleName());
133 war.addClasses(InputPartDefaultCharsetOverwriteTest.class);
134 war.addClasses(TestUtil.class, PortProviderUtil.class);
135 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16.class,
136 InputPartDefaultCharsetOverwriteService.class);
137 }
138
139 /**
140 * @tpTestDetails Test UTF8 content-type, no charset, preprocessor with no content-type
141 * @tpSince RESTEasy 3.0.16
142 */
143 @Test
144 public void testUTF8ContentTypeNoCharsetPreprocessorWithNoContentTypeCharset() throws Exception {
145 doTestWithContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_PLAIN, TEXT_PLAIN_WITH_CHARSET_UTF_8, InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.class);
146 }
147
148 /**
149 * @tpTestDetails The tests use no interceptor.
150 * @tpSince RESTEasy 3.0.16
151 */
152 @Test
153 public void noInterceptorTest() throws Exception {
154 // testNoContentTypeDefault
155 doTestNoContentTypeInMessage(abc_us_ascii_bytes, abc_us_ascii, TEXT_PLAIN_WITH_CHARSET_US_ASCII, InputPartDefaultCharsetOverwriteTest.class);
156 // testContentTypeNoCharsetDefault
157 doTestWithContentTypeInMessage(abc_us_ascii_bytes, abc_us_ascii, TEXT_HTTP,
158 TEXT_HTTP_WITH_CHARSET_US_ASCII, InputPartDefaultCharsetOverwriteTest.class);
159 // testContentTypeCharsetDefaultUTF8
160 doTestWithContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_8,
161 TEXT_HTTP_WITH_CHARSET_UTF_8, InputPartDefaultCharsetOverwriteTest.class);
162 // testContentTypeCharsetDefaultUTF16
163 doTestWithContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_16,
164 TEXT_HTTP_WITH_CHARSET_UTF_16, InputPartDefaultCharsetOverwriteTest.class);
165 // testNoContentTypeInputPartContentTypeUTF8
166 doTestNoContentTypeInMessageContentTypeInQuery(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_8,
167 TEXT_HTTP_WITH_CHARSET_UTF_8, InputPartDefaultCharsetOverwriteTest.class);
168 // testNoContentTypeInputPartContentTypeUTF16
169 doTestNoContentTypeInMessageContentTypeInQuery(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_16,
170 TEXT_HTTP_WITH_CHARSET_UTF_16, InputPartDefaultCharsetOverwriteTest.class);
171 // testContentTypeInputPartContentTypeUTF8
172 doTestWithContentTypeInMessageContentTypeInQuery(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_16, TEXT_HTTP_WITH_CHARSET_UTF_8,
173 TEXT_HTTP_WITH_CHARSET_UTF_8, InputPartDefaultCharsetOverwriteTest.class);
174 // testContentTypeInputPartContentTypeUTF16
175 doTestWithContentTypeInMessageContentTypeInQuery(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_8, TEXT_HTTP_WITH_CHARSET_UTF_16,
176 TEXT_HTTP_WITH_CHARSET_UTF_16, InputPartDefaultCharsetOverwriteTest.class);
177 }
178
179 /**
180 * @tpTestDetails The tests use an interceptor that installs a content-type but no charset.
181 * @tpSince RESTEasy 3.0.16
182 */
183 @Test
184 public void interceptorNoCharsetYesContentType() throws Exception {
185 // testNoContentTypePreprocessorWithContentTypeNoCharsetUTF8
186 doTestNoContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_8,
187 InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8.class);
188 // testNoContentTypePreprocessorWithContentTypeNoCharsetUTF16
189 doTestNoContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_16,
190 InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16.class);
191 // testContentTypeNoCharsetPreprocessorWithContentTypeNoCharsetUTF8
192 doTestWithContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_PLAIN, TEXT_PLAIN_WITH_CHARSET_UTF_8,
193 InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.class);
194 // testContentTypeNoCharsetPreprocessorWithContentTypeNoCharsetUTF16
195 doTestWithContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_PLAIN, TEXT_PLAIN_WITH_CHARSET_UTF_16,
196 InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16.class);
197 // testContentTypeCharsetPreprocessorWithContentTypeNoCharsetUTF8
198 doTestWithContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_PLAIN_WITH_CHARSET_UTF_8, TEXT_PLAIN_WITH_CHARSET_UTF_8,
199 InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16.class);
200 // testContentTypeCharsetPreprocessorWithContentTypeNoCharsetUTF16
201 doTestWithContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_PLAIN_WITH_CHARSET_UTF_16, TEXT_PLAIN_WITH_CHARSET_UTF_16,
202 InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8.class);
203 // testNoContentTypePreprocessorWithContentTypeNoCharsetInputPartContentTypeUTF8
204 doTestNoContentTypeInMessageContentTypeInQuery(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_8, TEXT_HTTP_WITH_CHARSET_UTF_8,
205 InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16.class);
206 // testNoContentTypePreprocessorWithContentTypeNoCharsetInputPartContentTypeUTF16
207 doTestNoContentTypeInMessageContentTypeInQuery(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_16, TEXT_HTTP_WITH_CHARSET_UTF_16,
208 InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8.class);
209 // testContentTypePreprocessorWithContentTypeNoCharsetInputPartContentTypeUTF8
210 doTestWithContentTypeInMessageContentTypeInQuery(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_16, TEXT_HTTP_WITH_CHARSET_UTF_8,
211 TEXT_HTTP_WITH_CHARSET_UTF_8, InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16.class);
212 // testContentTypereprocessorWithContentTypeNoCharsetInputPartContentTypeUTF16
213 doTestWithContentTypeInMessageContentTypeInQuery(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_8, TEXT_HTTP_WITH_CHARSET_UTF_16,
214 TEXT_HTTP_WITH_CHARSET_UTF_16, InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8.class);
215 }
216
217 /**
218 * @tpTestDetails The tests use an interceptor that installs a charset but no content-type.
219 * @tpSince RESTEasy 3.0.16
220 */
221 @Test
222 public void testNoContentTypePreprocessorWithNoContentTypeCharsetUTF8() throws Exception {
223 // testNoContentTypePreprocessorWithNoContentTypeCharsetUTF8
224 doTestNoContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_PLAIN_WITH_CHARSET_UTF_8,
225 InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.class);
226 // testNoContentTypePreprocessorWithNoContentTypeCharsetUTF16
227 doTestNoContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_PLAIN_WITH_CHARSET_UTF_16,
228 InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16.class);
229 // testContentTypeNoCharsetPreprocessorWithNoContentTypeCharsetUTF8
230 doTestWithContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_HTTP, TEXT_HTTP_WITH_CHARSET_UTF_8,
231 InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.class);
232 // testContentTypeNoCharsetPreprocessorWithNoContentTypeCharsetUTF16
233 doTestWithContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_HTTP, TEXT_HTTP_WITH_CHARSET_UTF_16,
234 InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16.class);
235 // testContentTypeCharsetPreprocessorWithNoContentTypeCharset8
236 doTestWithContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_PLAIN_WITH_CHARSET_UTF_8, TEXT_PLAIN_WITH_CHARSET_UTF_8,
237 InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16.class);
238 // testContentTypeCharsetPreprocessorWithNoContentTypeCharset16
239 doTestWithContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_PLAIN_WITH_CHARSET_UTF_16, TEXT_PLAIN_WITH_CHARSET_UTF_16,
240 InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.class);
241 // testNoContentTypePreprocessorWithNoContentTypeCharsetInputPartContentTypeUTF8
242 doTestNoContentTypeInMessageContentTypeInQuery(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_8, TEXT_HTTP_WITH_CHARSET_UTF_8,
243 InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16.class);
244 // testNoContentTypePreprocessorWithNoContentTypeCharsetInputPartContentTypeUTF16
245 doTestNoContentTypeInMessageContentTypeInQuery(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_16,
246 TEXT_HTTP_WITH_CHARSET_UTF_16, InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.class);
247 // testContentTypePreprocessorWithNoContentTypeCharsetInputPartContentTypeUTF8
248 doTestWithContentTypeInMessageContentTypeInQuery(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_16, TEXT_HTTP_WITH_CHARSET_UTF_8,
249 TEXT_HTTP_WITH_CHARSET_UTF_8, InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16.class);
250 // testContentTypereprocessorWithNoContentTypeCharsetInputPartContentTypeUTF16
251 doTestWithContentTypeInMessageContentTypeInQuery(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_8, TEXT_HTTP_WITH_CHARSET_UTF_16,
252 TEXT_HTTP_WITH_CHARSET_UTF_16, InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.class);
253 }
254
255 /**
256 * @tpTestDetails The tests use an interceptor that installs both a content-type and a charset.
257 * @tpSince RESTEasy 3.0.16
258 */
259 @Test
260 public void testNoContentTypePreprocessorWithContentTypeCharset8() throws Exception {
261 // testNoContentTypePreprocessorWithContentTypeCharset8
262 doTestNoContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_8,
263 InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8.class);
264 // testNoContentTypePreprocessorWithContentTypeCharset16
265 doTestNoContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_16,
266 InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16.class);
267 // testContentTypeNoCharsetPreprocessorWithContentTypeCharset8
268 doTestWithContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_PLAIN, TEXT_PLAIN_WITH_CHARSET_UTF_8,
269 InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8.class);
270 // testContentTypeNoCharsetPreprocessorWithContentTypeCharset16
271 doTestWithContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_PLAIN, TEXT_PLAIN_WITH_CHARSET_UTF_16,
272 InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16.class);
273 // testContentTypeCharsetPreprocessorWithContentTypeCharset8
274 doTestWithContentTypeInMessage(abc_utf8_bytes, abc_utf8, TEXT_PLAIN_WITH_CHARSET_UTF_8, TEXT_PLAIN_WITH_CHARSET_UTF_8,
275 InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16.class);
276 // testContentTypeCharsetPreprocessorWithContentTypeCharset16
277 doTestWithContentTypeInMessage(abc_utf16_bytes, abc_utf16, TEXT_PLAIN_WITH_CHARSET_UTF_16, TEXT_PLAIN_WITH_CHARSET_UTF_16,
278 InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8.class);
279 // testNoContentTypePreprocessorWithContentTypeCharsetInputPartContentTypeUTF8
280 doTestNoContentTypeInMessageContentTypeInQuery(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_8, TEXT_HTTP_WITH_CHARSET_UTF_8,
281 InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16.class);
282 // testNoContentTypePreprocessorWithContentTypeCharsetInputPartContentTypeUTF16
283 doTestNoContentTypeInMessageContentTypeInQuery(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_16, TEXT_HTTP_WITH_CHARSET_UTF_16,
284 InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8.class);
285 // testContentTypePreprocessorWithContentTypeCharsetInputPartContentTypeUTF8
286 doTestWithContentTypeInMessageContentTypeInQuery(abc_utf8_bytes, abc_utf8, TEXT_HTTP_WITH_CHARSET_UTF_16, TEXT_HTTP_WITH_CHARSET_UTF_8,
287 TEXT_HTTP_WITH_CHARSET_UTF_8, InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16.class);
288 // testContentTypereprocessorWithContentTypeCharsetInputPartContentTypeUTF16
289 doTestWithContentTypeInMessageContentTypeInQuery(abc_utf16_bytes, abc_utf16, TEXT_HTTP_WITH_CHARSET_UTF_8, TEXT_HTTP_WITH_CHARSET_UTF_16,
290 TEXT_HTTP_WITH_CHARSET_UTF_16, InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8.class);
291 }
292
293 /**
294 * @tpTestDetails The tests use a non-text media type.
295 * @tpSince RESTEasy 3.0.16
296 */
297 //////////////////////////////////////////////////////////////////////////////////////////
298 //
299 //////////////////////////////////////////////////////////////////////////////////////////
300 @Test
301 public void testApplicationXmlUSAscii() throws Exception {
302 // testApplicationXmlUSAscii
303 doTestWithContentTypeInMessage(abc_us_ascii_bytes, abc_us_ascii, APPLICATION_XML_WITH_CHARSET_US_ASCII,
304 APPLICATION_XML_WITH_CHARSET_US_ASCII, InputPartDefaultCharsetOverwriteTest.class);
305 // testApplicationXmlUTF8
306 doTestWithContentTypeInMessage(abc_utf8_bytes, abc_utf8, APPLICATION_XML_WITH_CHARSET_UTF_8,
307 APPLICATION_XML_WITH_CHARSET_UTF_8, InputPartDefaultCharsetOverwriteTest.class);
308 // testApplicationXmlUTF16
309 doTestWithContentTypeInMessage(abc_utf16_bytes, abc_utf16, APPLICATION_XML_WITH_CHARSET_UTF_16,
310 APPLICATION_XML_WITH_CHARSET_UTF_16, InputPartDefaultCharsetOverwriteTest.class);
311 // testApplicationOctetStreamUSAscii
312 doTestByteArray(abc_us_ascii_bytes, APPLICATION_OCTET_STREAM, InputPartDefaultCharsetOverwriteTest.class);
313 // testApplicationOctetStreamUTF8
314 doTestByteArray(abc_utf8_bytes, APPLICATION_OCTET_STREAM, InputPartDefaultCharsetOverwriteTest.class);
315 // testApplicationOctetStreamUTF16
316 doTestByteArray(abc_utf16_bytes, APPLICATION_OCTET_STREAM, InputPartDefaultCharsetOverwriteTest.class);
317 // testByteArray
318 byte[] body = new byte[512];
319 Random r = new Random(System.currentTimeMillis());
320 r.nextBytes(body);
321 doTestByteArray(body, APPLICATION_OCTET_STREAM, InputPartDefaultCharsetOverwriteTest.class);
322 }
323
324 private static void doTestNoContentTypeInMessage(byte[] body, String expectedBody, String expectedContentType, Class<?> providerClass) throws Exception {
325 byte[] start = ("--boo\r\nContent-Disposition: form-data; name=\"foo\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n").getBytes();
326 byte[] end = "\r\n--boo--\r\n".getBytes();
327 byte[] buf = new byte[start.length + body.length + end.length];
328 int pos0 = 0;
329 int pos1 = pos0 + start.length;
330 int pos2 = pos1 + body.length;
331 System.arraycopy(start, 0, buf, pos0, start.length);
332 System.arraycopy(body, 0, buf, pos1, body.length);
333 System.arraycopy(end, 0, buf, pos2, end.length);
334 Response response = client.target(PortProviderUtil.generateURL("/test/", providerClass.getSimpleName())).request()
335 .post(Entity.entity(buf, "multipart/form-data; boundary=boo"));
336 String responseStr = response.readEntity(String.class);
337 logger.info("status: " + response.getStatus());
338 logger.info("client response: " + responseStr);
339 Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10);
340 String[] answer = responseStr.split(":");
341 Assert.assertEquals("Wrong size of response", 3, answer.length);
342 logger.info("response charset: " + answer[0]);
343 Assert.assertEquals("Response has wrong encoding", normalize(expectedContentType), normalize(answer[0]));
344 Assert.assertEquals("Wrong content of response", expectedBody, answer[1]);
345 Assert.assertEquals("Wrong content of response", expectedBody, answer[2]);
346 response.close();
347 }
348
349 private static void doTestWithContentTypeInMessage(byte[] body, String expectedBody, String inputContentType, String expectedContentType, Class<?> deployment) throws Exception {
350 byte[] start = ("--boo\r\nContent-Disposition: form-data; name=\"foo\"\r\nContent-Type: ").getBytes();
351 byte[] middle = (inputContentType + "\r\n\r\n").getBytes();
352 byte[] end = "\r\n--boo--\r\n".getBytes();
353 byte[] buf = new byte[start.length + middle.length + body.length + end.length];
354 int pos0 = 0;
355 int pos1 = pos0 + start.length;
356 int pos2 = pos1 + middle.length;
357 int pos3 = pos2 + body.length;
358 System.arraycopy(start, 0, buf, pos0, start.length);
359 System.arraycopy(middle, 0, buf, pos1, middle.length);
360 System.arraycopy(body, 0, buf, pos2, body.length);
361 System.arraycopy(end, 0, buf, pos3, end.length);
362 Response response = client.target(PortProviderUtil.generateURL("/test/", deployment.getSimpleName())).request()
363 .post(Entity.entity(buf, "multipart/form-data; boundary=boo"));
364 String responseStr = response.readEntity(String.class);
365 logger.info("status: " + response.getStatus());
366 logger.info("client response: " + responseStr);
367 Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10);
368 String[] answer = responseStr.split(":");
369 Assert.assertEquals("Wrong size of response", 3, answer.length);
370 logger.info("response charset: " + answer[0]);
371 Assert.assertEquals("Response has wrong encoding", normalize(expectedContentType), normalize(answer[0]));
372 Assert.assertEquals("Wrong content of response", expectedBody, answer[1]);
373 Assert.assertEquals("Wrong content of response", expectedBody, answer[2]);
374 }
375
376 private static void doTestNoContentTypeInMessageContentTypeInQuery(
377 byte[] body, String expectedBody, String queryContentType, String expectedContentType, Class<?> deployment) throws Exception {
378 byte[] start = ("--boo\r\nContent-Disposition: form-data; name=\"foo\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n").getBytes();
379 byte[] end = "\r\n--boo--\r\n".getBytes();
380 byte[] buf = new byte[start.length + body.length + end.length];
381 int pos0 = 0;
382 int pos1 = pos0 + start.length;
383 int pos2 = pos1 + body.length;
384 System.arraycopy(start, 0, buf, pos0, start.length);
385 System.arraycopy(body, 0, buf, pos1, body.length);
386 System.arraycopy(end, 0, buf, pos2, end.length);
387 Response response = client.target(PortProviderUtil.generateURL("/query?contentType=" + Encode.encodeQueryParamAsIs(queryContentType), deployment.getSimpleName())).request()
388 .post(Entity.entity(buf, "multipart/form-data; boundary=boo"));
389 String responseStr = response.readEntity(String.class);
390 logger.info("status: " + response.getStatus());
391 logger.info("client response: " + responseStr);
392 Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10);
393 String[] answer = responseStr.split(":");
394 Assert.assertEquals("Wrong size of response", 3, answer.length);
395 logger.info("response charset: " + answer[0]);
396 Assert.assertEquals("Response has wrong encoding", normalize(expectedContentType), normalize(answer[0]));
397 Assert.assertEquals("Wrong content of response", expectedBody, answer[1]);
398 Assert.assertEquals("Wrong content of response", expectedBody, answer[2]);
399 }
400
401 private static void doTestWithContentTypeInMessageContentTypeInQuery(
402 byte[] body, String expectedBody, String inputContentType, String queryContentType, String expectedContentType, Class<?> deployment) throws Exception {
403 byte[] start = ("--boo\r\nContent-Disposition: form-data; name=\"foo\"\r\nContent-Type: ").getBytes();
404 byte[] middle = (inputContentType + "\r\n\r\n").getBytes();
405 byte[] end = "\r\n--boo--\r\n".getBytes();
406 byte[] buf = new byte[start.length + middle.length + body.length + end.length];
407 int pos0 = 0;
408 int pos1 = pos0 + start.length;
409 int pos2 = pos1 + middle.length;
410 int pos3 = pos2 + body.length;
411 System.arraycopy(start, 0, buf, pos0, start.length);
412 System.arraycopy(middle, 0, buf, pos1, middle.length);
413 System.arraycopy(body, 0, buf, pos2, body.length);
414 System.arraycopy(end, 0, buf, pos3, end.length);
415 Response response = client.target(PortProviderUtil.generateURL("/query?contentType=" + Encode.encodeQueryParamAsIs(queryContentType), deployment.getSimpleName())).request()
416 .post(Entity.entity(buf, "multipart/form-data; boundary=boo"));
417 String responseStr = response.readEntity(String.class);
418 logger.info("status: " + response.getStatus());
419 logger.info("client response: " + responseStr);
420 Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10);
421 String[] answer = responseStr.split(":");
422 Assert.assertEquals("Wrong size of response", 3, answer.length);
423 logger.info("response charset: " + answer[0]);
424 Assert.assertEquals("Response has wrong encoding", normalize(expectedContentType), normalize(answer[0]));
425 Assert.assertEquals("Wrong content of response", expectedBody, answer[1]);
426 Assert.assertEquals("Wrong content of response", expectedBody, answer[2]);
427 }
428
429 private static void doTestByteArray(byte[] body, String contentType, Class<?> deployment) throws Exception {
430 byte[] start = ("--boo\r\nContent-Disposition: form-data; name=\"foo\"\r\nContent-Type: " + contentType + "\r\n\r\n").getBytes();
431 byte[] end = "\r\n--boo--\r\n".getBytes();
432 byte[] buf = new byte[start.length + body.length + end.length];
433 int pos0 = 0;
434 int pos1 = pos0 + start.length;
435 int pos2 = pos1 + body.length;
436 System.arraycopy(start, 0, buf, pos0, start.length);
437 System.arraycopy(body, 0, buf, pos1, body.length);
438 System.arraycopy(end, 0, buf, pos2, end.length);
439 Response response = client.target(PortProviderUtil.generateURL("/bytes/", deployment.getSimpleName())).request()
440 .post(Entity.entity(buf, "multipart/form-data; boundary=boo"));
441 logger.info("status: " + response.getStatus());
442 Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10);
443 byte[] b = response.readEntity(byte[].class);
444 for (int i = 0; i < body.length; i++) {
445 StringBuilder errorMessage = new StringBuilder();
446 errorMessage.append("Wrong content of response: ").append(i).append(": ").append(body[i]).append(" != ").append(b[i]);
447 Assert.assertEquals(errorMessage.toString(), body[i], b[i]);
448 }
449 }
450
451 private static String normalize(String s) {
452 String sl = s.toLowerCase();
453 StringBuffer sb = new StringBuffer();
454 for (int i = 0; i < s.length(); i++) {
455 if (sl.charAt(i) != ' ' && sl.charAt(i) != '"') {
456 sb.append(sl.charAt(i));
457 }
458 }
459 return sb.toString();
460 }
461 }
+0
-94
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/InputPartDefaultContentTypeEncodingOverwriteTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeEncodingOverwriteService;
8 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeEncodingOverwriteSetterPreProcessorInterceptor;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.asset.StringAsset;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Assert;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.client.Entity;
21 import javax.ws.rs.client.WebTarget;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.core.Response;
24
25 /**
26 * @tpSubChapter Multipart provider
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Test for default content type encoding of multipart provider
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class InputPartDefaultContentTypeEncodingOverwriteTest {
34 public static final String TEXT_PLAIN_WITH_CHARSET_UTF_8 = "text/plain; charset=utf-8";
35
36 @Deployment
37 public static Archive<?> createTestArchive() {
38 WebArchive war = TestUtil.prepareArchive(InputPartDefaultContentTypeEncodingOverwriteTest.class.getSimpleName());
39 war.addClasses(InputPartDefaultContentTypeEncodingOverwriteTest.class);
40 war.addClasses(TestUtil.class, PortProviderUtil.class);
41 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultContentTypeEncodingOverwriteSetterPreProcessorInterceptor.class,
42 InputPartDefaultContentTypeEncodingOverwriteService.class);
43 }
44
45 private static String generateURL(String path) {
46 return PortProviderUtil.generateURL(path, InputPartDefaultContentTypeEncodingOverwriteTest.class.getSimpleName());
47 }
48
49
50 private static final String TEST_URI = generateURL("");
51
52 /**
53 * @tpTestDetails Test for old client
54 * @tpSince RESTEasy 3.0.16
55 */
56 @Test
57 public void testContentTypeOldClient() throws Exception {
58 String message = "--boo\r\n"
59 + "Content-Disposition: form-data; name=\"foo\"\r\n"
60 + "Content-Transfer-Encoding: 8bit\r\n\r\n" + "bar\r\n"
61 + "--boo--\r\n";
62
63 ClientRequest request = new ClientRequest(TEST_URI + "/mime");
64 request.body("multipart/form-data; boundary=boo", message.getBytes());
65 ClientResponse<String> response = request.post(String.class);
66 Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10);
67 Assert.assertEquals("Response text is wrong",
68 MediaType.valueOf(TEXT_PLAIN_WITH_CHARSET_UTF_8),
69 MediaType.valueOf(response.getEntity()));
70 }
71
72 /**
73 * @tpTestDetails Test for new client
74 * @tpSince RESTEasy 3.0.16
75 */
76 @Test
77 public void testContentTypeNewClient() throws Exception {
78 String message = "--boo\r\n"
79 + "Content-Disposition: form-data; name=\"foo\"\r\n"
80 + "Content-Transfer-Encoding: 8bit\r\n\r\n" + "bar\r\n"
81 + "--boo--\r\n";
82
83 Client client = ClientBuilder.newClient();
84 WebTarget target = client.target(generateURL("/mime"));
85 Entity entity = Entity.entity(message, "multipart/form-data; boundary=boo");
86 Response response = target.request().post(entity);
87
88 Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10);
89 Assert.assertEquals("Response text is wrong",
90 MediaType.valueOf(TEXT_PLAIN_WITH_CHARSET_UTF_8),
91 MediaType.valueOf(response.readEntity(String.class)));
92 }
93 }
+0
-107
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteContainerBean;
8 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteOldInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteService;
10 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteXmlBean;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.AfterClass;
16 import org.junit.Assert;
17 import org.junit.BeforeClass;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.client.Client;
22 import javax.ws.rs.client.ClientBuilder;
23 import javax.ws.rs.client.Entity;
24 import javax.ws.rs.client.WebTarget;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @tpSubChapter Multipart provider
30 * @tpChapter Integration tests
31 * @tpTestCaseDetails MultiPart provider should be able to process xml, if wildcard is set. Wildcard is set in deprecated version of interceptor.
32 * @tpSince RESTEasy 3.0.16
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest {
37
38 public static final String WILDCARD_WITH_CHARSET_UTF_8 = MediaType.APPLICATION_XML + "; charset=UTF-8"; // this mediatype works correctly
39 private static Client client;
40
41 @Deployment
42 public static Archive<?> createTestArchive() {
43 WebArchive war = TestUtil.prepareArchive(InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.class.getSimpleName());
44 war.addClasses(InputPartDefaultContentTypeWildcardOverwriteContainerBean.class);
45 war.addClasses(InputPartDefaultContentTypeWildcardOverwriteXmlBean.class, InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.class);
46 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultContentTypeWildcardOverwriteOldInterceptor.class,
47 InputPartDefaultContentTypeWildcardOverwriteService.class);
48 }
49
50 @BeforeClass
51 public static void before() throws Exception
52 {
53 client = ClientBuilder.newClient();
54 }
55
56 @AfterClass
57 public static void after() throws Exception
58 {
59 client.close();
60 }
61
62 /**
63 * @tpTestDetails Test for old client
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testContentTypeOldClient() throws Exception {
68 String message = "--boo\r\n"
69 + "Content-Disposition: form-data; name=\"foo\"\r\n"
70 + "Content-Transfer-Encoding: 8bit\r\n\r\n"
71 + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
72 + "<inputPartDefaultContentTypeWildcardOverwriteXmlBean><myInt>27</myInt><myString>Lorem Ipsum</myString></inputPartDefaultContentTypeWildcardOverwriteXmlBean>\r\n"
73 + "--boo--\r\n";
74
75 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/mime", InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.class.getSimpleName()));
76
77 request.body("multipart/form-data; boundary=boo", message.getBytes("utf-8"));
78 ClientResponse<String> response = request.post(String.class);
79 Assert.assertEquals("MultiPart provider is unable to process xml, if media type is set in interceptor",
80 20, response.getStatus() / 10);
81 Assert.assertEquals("Response text is wrong", "27", response.getEntity());
82 }
83
84 /**
85 * @tpTestDetails Test for new client
86 * @tpSince RESTEasy 3.0.16
87 */
88 @Test
89 public void testContentTypeNewClient() throws Exception {
90 String message = "--boo\r\n"
91 + "Content-Disposition: form-data; name=\"foo\"\r\n"
92 + "Content-Transfer-Encoding: 8bit\r\n\r\n"
93 + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
94 + "<inputPartDefaultContentTypeWildcardOverwriteXmlBean><myInt>27</myInt><myString>Lorem Ipsum</myString></inputPartDefaultContentTypeWildcardOverwriteXmlBean>\r\n"
95 + "--boo--\r\n";
96
97
98 WebTarget target = client.target(PortProviderUtil.generateURL("/mime", InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.class.getSimpleName()));
99 Entity entity = Entity.entity(message, "multipart/form-data; boundary=boo");
100 Response response = target.request().post(entity);
101
102 Assert.assertEquals("MultiPart provider is unable to process xml, if media type is set in interceptor",
103 20, response.getStatus() / 10);
104 Assert.assertEquals("Response text is wrong", "27", response.readEntity(String.class));
105 }
106 }
+0
-95
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/InputPartDefaultContentTypeWildcardOverwriteNewInterceptorTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteContainerBean;
8 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteNewInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteService;
10 import org.jboss.resteasy.test.providers.multipart.resource.InputPartDefaultContentTypeWildcardOverwriteXmlBean;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Client;
20 import javax.ws.rs.client.ClientBuilder;
21 import javax.ws.rs.client.Entity;
22 import javax.ws.rs.client.WebTarget;
23 import javax.ws.rs.core.MediaType;
24 import javax.ws.rs.core.Response;
25
26
27 /**
28 * @tpSubChapter Multipart provider
29 * @tpChapter Integration tests
30 * @tpTestCaseDetails MultiPart provider should be able to process xml, if wildcard is set. Wildcard is set in new version of interceptor.
31 * @tpSince RESTEasy 3.0.16
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class InputPartDefaultContentTypeWildcardOverwriteNewInterceptorTest {
36
37 public static final String WILDCARD_WITH_CHARSET_UTF_8 = MediaType.APPLICATION_XML + "; charset=UTF-8"; // this mediatype works correctly
38
39 @Deployment
40 public static Archive<?> createTestArchive() {
41 WebArchive war = TestUtil.prepareArchive(InputPartDefaultContentTypeWildcardOverwriteNewInterceptorTest.class.getSimpleName());
42 war.addClasses(InputPartDefaultContentTypeWildcardOverwriteContainerBean.class);
43 war.addClasses(InputPartDefaultContentTypeWildcardOverwriteXmlBean.class, InputPartDefaultContentTypeWildcardOverwriteNewInterceptorTest.class);
44 return TestUtil.finishContainerPrepare(war, null, InputPartDefaultContentTypeWildcardOverwriteNewInterceptor.class,
45 InputPartDefaultContentTypeWildcardOverwriteService.class);
46 }
47
48 /**
49 * @tpTestDetails Test for old client
50 * @tpSince RESTEasy 3.0.16
51 */
52 @Test
53 public void testContentTypeOldClient() throws Exception {
54 String message = "--boo\r\n"
55 + "Content-Disposition: form-data; name=\"foo\"\r\n"
56 + "Content-Transfer-Encoding: 8bit\r\n\r\n"
57 + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
58 + "<inputPartDefaultContentTypeWildcardOverwriteXmlBean><myInt>27</myInt><myString>Lorem Ipsum</myString></inputPartDefaultContentTypeWildcardOverwriteXmlBean>\r\n"
59 + "--boo--\r\n";
60
61 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/mime", InputPartDefaultContentTypeWildcardOverwriteNewInterceptorTest.class.getSimpleName()));
62
63 request.body("multipart/form-data; boundary=boo", message.getBytes("utf-8"));
64 ClientResponse<String> response = request.post(String.class);
65 Assert.assertEquals("MultiPart provider is unable to process xml, if media type is set in interceptor",
66 20, response.getStatus() / 10);
67 Assert.assertEquals("Response text is wrong", "27", response.getEntity());
68 }
69
70 /**
71 * @tpTestDetails Test for new client
72 * @tpSince RESTEasy 3.0.16
73 */
74 @Test
75 public void testContentTypeNewClient() throws Exception {
76 String message = "--boo\r\n"
77 + "Content-Disposition: form-data; name=\"foo\"\r\n"
78 + "Content-Transfer-Encoding: 8bit\r\n\r\n"
79 + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
80 + "<inputPartDefaultContentTypeWildcardOverwriteXmlBean><myInt>27</myInt><myString>Lorem Ipsum</myString></inputPartDefaultContentTypeWildcardOverwriteXmlBean>\r\n"
81 + "--boo--\r\n";
82
83
84
85 Client client = ClientBuilder.newClient();
86 WebTarget target = client.target(PortProviderUtil.generateURL("/mime", InputPartDefaultContentTypeWildcardOverwriteNewInterceptorTest.class.getSimpleName()));
87 Entity entity = Entity.entity(message, "multipart/form-data; boundary=boo");
88 Response response = target.request().post(entity);
89
90 Assert.assertEquals("MultiPart provider is unable to process xml, if media type is set in interceptor",
91 20, response.getStatus() / 10);
92 Assert.assertEquals("Response text is wrong", "27", response.readEntity(String.class));
93 }
94 }
+0
-307
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/MimeMultipartProviderTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
7 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
8 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
9 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedOutput;
10 import org.jboss.resteasy.test.providers.multipart.resource.MimeMultipartProviderClient;
11 import org.jboss.resteasy.test.providers.multipart.resource.MimeMultipartProviderCustomer;
12 import org.jboss.resteasy.test.providers.multipart.resource.MimeMultipartProviderResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Assert;
19 import org.junit.BeforeClass;
20 import org.junit.AfterClass;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 import javax.activation.DataHandler;
25 import javax.mail.internet.MimeMultipart;
26 import javax.mail.util.ByteArrayDataSource;
27 import javax.servlet.http.HttpServletResponse;
28 import javax.ws.rs.client.Client;
29 import javax.ws.rs.client.ClientBuilder;
30 import javax.ws.rs.client.Entity;
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.Response;
33 import javax.xml.bind.JAXBContext;
34 import javax.xml.bind.JAXBException;
35 import java.io.BufferedInputStream;
36 import java.io.File;
37 import java.io.InputStream;
38 import java.io.StringWriter;
39 import java.util.ArrayList;
40 import java.util.LinkedHashMap;
41 import java.util.Map;
42
43 /**
44 * @tpSubChapter Multipart provider
45 * @tpChapter Integration tests
46 * @tpSince RESTEasy 3.0.16
47 */
48 @RunWith(Arquillian.class)
49 @RunAsClient
50 public class MimeMultipartProviderTest {
51
52 private static Logger logger = Logger.getLogger(MimeMultipartProviderTest.class);
53 private static final String TEST_URI = generateURL("/mime");
54 static Client client;
55
56 private static final String ERR_NUMBER = "The number of enclosed bodypart objects doesn't match to the expectation";
57
58 @BeforeClass
59 public static void before() throws Exception {
60 client = ClientBuilder.newClient();
61 }
62
63 @AfterClass
64 public static void after() throws Exception {
65 client.close();
66 }
67
68 static final String testFilePath = TestUtil.getResourcePath(MimeMultipartProviderTest.class, "HeaderFlushedOutputStreamTestData.txt");
69
70 @Deployment
71 public static Archive<?> deploy() {
72 WebArchive war = TestUtil.prepareArchive(MimeMultipartProviderTest.class.getSimpleName());
73 return TestUtil.finishContainerPrepare(war, null, MimeMultipartProviderResource.class, MimeMultipartProviderCustomer.class);
74 }
75
76 private static String generateURL(String path) {
77 return PortProviderUtil.generateURL(path, MimeMultipartProviderTest.class.getSimpleName());
78 }
79
80 /**
81 * @tpTestDetails MultipartFormDataOutput entity in put request with data from file is used
82 * @tpSince RESTEasy 3.0.16
83 */
84 @Test
85 public void testPutForm() throws Exception {
86 // prepare file
87 File file = new File(testFilePath);
88 Assert.assertTrue("File " + testFilePath + " doesn't exists", file.exists());
89
90 MultipartFormDataOutput mpfdo = new MultipartFormDataOutput();
91 mpfdo.addFormData("part1", "This is Value 1", MediaType.TEXT_PLAIN_TYPE);
92 mpfdo.addFormData("part2", "This is Value 2", MediaType.TEXT_PLAIN_TYPE);
93 mpfdo.addFormData("data.txt", file, MediaType.TEXT_PLAIN_TYPE);
94
95 Response response = client.target(TEST_URI).request()
96 .put(Entity.entity(mpfdo, MediaType.MULTIPART_FORM_DATA_TYPE));
97 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
98 String responseBody = response.readEntity(String.class);
99 Assert.assertEquals(ERR_NUMBER, responseBody, "Count: 3");
100 }
101
102 /**
103 * @tpTestDetails MultipartOutput entity in put request with data from file is used
104 * @tpSince RESTEasy 3.0.16
105 */
106 @Test
107 public void testPut() throws Exception {
108 // prepare file
109 File file = new File(testFilePath);
110 Assert.assertTrue("File " + testFilePath + " doesn't exists", file.exists());
111
112 MultipartOutput mpo = new MultipartOutput();
113 mpo.addPart("This is Value 1", MediaType.TEXT_PLAIN_TYPE);
114 mpo.addPart("This is Value 2", MediaType.TEXT_PLAIN_TYPE);
115 mpo.addPart(file, MediaType.TEXT_PLAIN_TYPE);
116
117 Response response = client.target(TEST_URI).request()
118 .put(Entity.entity(mpo, MediaType.MULTIPART_FORM_DATA_TYPE));
119
120 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
121 String responseBody = response.readEntity(String.class);
122 Assert.assertEquals(ERR_NUMBER, responseBody, "Count: 3");
123 }
124
125 /**
126 * @tpTestDetails MultipartFormDataOutput entity in put request with created by jxb marshaller is used
127 * @tpSince RESTEasy 3.0.16
128 */
129 @Test
130 public void testForm() throws Exception {
131 testMultipart(TEST_URI + "/form");
132 testMultipart(TEST_URI + "/form/map");
133 testMultipart(TEST_URI + "/form/class");
134 testMultipart(TEST_URI + "/multi");
135 testMultipart(TEST_URI + "/multi/list");
136 }
137
138 private void testMultipart(String uri) throws Exception {
139 MultipartFormDataOutput mpfdo = new MultipartFormDataOutput();
140 mpfdo.addFormData("bill", createCustomerData("bill"), MediaType.APPLICATION_XML_TYPE);
141 mpfdo.addFormData("monica", createCustomerData("monica"), MediaType.APPLICATION_XML_TYPE);
142
143 Response response = client.target(uri).request()
144 .put(Entity.entity(mpfdo, MediaType.MULTIPART_FORM_DATA_TYPE));
145 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
146 response.close();
147 }
148
149 /**
150 * @tpTestDetails MultipartOutput entity in put request with manually created jaxb objects is used
151 * @tpSince RESTEasy 3.0.16
152 */
153 @Test
154 public void testMultipartOutput() throws Exception {
155 MimeMultipartProviderClient proxy = ProxyBuilder.builder(MimeMultipartProviderClient.class, client.target(generateURL(""))).build();
156 MultipartOutput output = new MultipartOutput();
157 output.addPart(new MimeMultipartProviderCustomer("bill"), MediaType.APPLICATION_XML_TYPE);
158 output.addPart(new MimeMultipartProviderCustomer("monica"), MediaType.APPLICATION_XML_TYPE);
159 proxy.putMixed(output);
160 }
161
162 /**
163 * @tpTestDetails MultipartFormDataOutput entity in put request with manually created jaxb objects is used
164 * @tpSince RESTEasy 3.0.16
165 */
166 @Test
167 public void testMultipartFormDataOutput() throws Exception {
168 MimeMultipartProviderClient proxy = ProxyBuilder.builder(MimeMultipartProviderClient.class, client.target(generateURL(""))).build();
169 MultipartFormDataOutput output = new MultipartFormDataOutput();
170 output.addFormData("bill", new MimeMultipartProviderCustomer("bill"), MediaType.APPLICATION_XML_TYPE);
171 output.addFormData("monica", new MimeMultipartProviderCustomer("monica"), MediaType.APPLICATION_XML_TYPE);
172 proxy.putFormData(output);
173 }
174
175 /**
176 * @tpTestDetails MultipartRelatedOutput entity in put request with manually generated xml is used
177 * @tpSince RESTEasy 3.0.16
178 */
179 @Test
180 public void testMultipartRelatedOutput() throws Exception {
181 MimeMultipartProviderClient proxy = ProxyBuilder.builder(MimeMultipartProviderClient.class, client.target(generateURL(""))).build();
182 MultipartRelatedOutput output = new MultipartRelatedOutput();
183 output.setStartInfo("text/xml");
184
185 Map<String, String> mediaTypeParameters = new LinkedHashMap<String, String>();
186 mediaTypeParameters.put("charset", "UTF-8");
187 mediaTypeParameters.put("type", "text/xml");
188 output
189 .addPart(
190 "<m:data xmlns:m='http://example.org/stuff'>"
191 + "<m:photo><xop:Include xmlns:xop='http://www.w3.org/2004/08/xop/include' href='cid:http://example.org/me.png'/></m:photo>"
192 + "<m:sig><xop:Include xmlns:xop='http://www.w3.org/2004/08/xop/include' href='cid:http://example.org/my.hsh'/></m:sig>"
193 + "</m:data>", new MediaType("application",
194 "xop+xml", mediaTypeParameters),
195 "<mymessage.xml@example.org>", "8bit");
196 output.addPart("// binary octets for png",
197 new MediaType("image", "png"), "<http://example.org/me.png>",
198 "binary");
199 output.addPart("// binary octets for signature", new MediaType(
200 "application", "pkcs7-signature"),
201 "<http://example.org/me.hsh>", "binary");
202 proxy.putRelated(output);
203 }
204
205 /**
206 * @tpTestDetails List is send in put request with the @PartType annotation
207 * @tpSince RESTEasy 3.0.16
208 */
209 @Test
210 public void testMultipartList() throws Exception {
211 MimeMultipartProviderClient proxy = ProxyBuilder.builder(MimeMultipartProviderClient.class, client.target(generateURL(""))).build();
212 ArrayList<MimeMultipartProviderCustomer> mimeMultipartProviderCustomers = new ArrayList<MimeMultipartProviderCustomer>();
213 mimeMultipartProviderCustomers.add(new MimeMultipartProviderCustomer("bill"));
214 mimeMultipartProviderCustomers.add(new MimeMultipartProviderCustomer("monica"));
215 proxy.putMixedList(mimeMultipartProviderCustomers);
216 }
217
218 /**
219 * @tpTestDetails Map is send in put request with the @PartType annotation
220 * @tpSince RESTEasy 3.0.16
221 */
222 @Test
223 public void testMultipartMap() throws Exception {
224 MimeMultipartProviderClient proxy = ProxyBuilder.builder(MimeMultipartProviderClient.class, client.target(generateURL(""))).build();
225 LinkedHashMap<String, MimeMultipartProviderCustomer> customers = new LinkedHashMap<String, MimeMultipartProviderCustomer>();
226 customers.put("bill", new MimeMultipartProviderCustomer("bill"));
227 customers.put("monica", new MimeMultipartProviderCustomer("monica"));
228 proxy.putFormDataMap(customers);
229 }
230
231 /**
232 * @tpTestDetails Custom Form type in put request with @MultipartForm annotation
233 * @tpSince RESTEasy 3.0.16
234 */
235 @Test
236 public void testMultipartForm() throws Exception {
237 MimeMultipartProviderClient proxy = ProxyBuilder.builder(MimeMultipartProviderClient.class, client.target(generateURL(""))).build();
238 MimeMultipartProviderResource.Form form = new MimeMultipartProviderResource.Form(
239 new MimeMultipartProviderCustomer("bill"), new MimeMultipartProviderCustomer("monica"));
240 proxy.putFormDataMap(form);
241 }
242
243 /**
244 * @tpTestDetails Custom jaxb object in put request with @XopWithMultipartRelated
245 * @tpSince RESTEasy 3.0.16
246 */
247 @Test
248 public void testXop() throws Exception {
249 MimeMultipartProviderClient proxy = ProxyBuilder.builder(MimeMultipartProviderClient.class, client.target(generateURL(""))).build();
250 MimeMultipartProviderResource.Xop xop = new MimeMultipartProviderResource.Xop(
251 new MimeMultipartProviderCustomer("bill\u00E9"), new MimeMultipartProviderCustomer("monica"),
252 "Hello Xop World!".getBytes("UTF-8"), new DataHandler(
253 new ByteArrayDataSource("Hello Xop World!"
254 .getBytes("UTF-8"),
255 MediaType.APPLICATION_OCTET_STREAM)));
256 proxy.putXop(xop);
257 }
258
259 private String createCustomerData(String name) throws JAXBException {
260 JAXBContext context = JAXBContext.newInstance(MimeMultipartProviderCustomer.class);
261 StringWriter writer = new StringWriter();
262 context.createMarshaller().marshal(new MimeMultipartProviderCustomer(name), writer);
263 String data = writer.toString();
264 return data;
265 }
266
267 /**
268 * @tpTestDetails Client sends get request for InputStream from the server
269 * @tpSince RESTEasy 3.0.16
270 */
271 @Test
272 public void testGet() throws Exception {
273 Response response = client.target(TEST_URI).request().get();
274 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
275 BufferedInputStream in = new BufferedInputStream(response.readEntity(InputStream.class));
276 String contentType = response.getStringHeaders().getFirst("content-type");
277 ByteArrayDataSource ds = new ByteArrayDataSource(in, contentType);
278 MimeMultipart mimeMultipart = new MimeMultipart(ds);
279 Assert.assertEquals(ERR_NUMBER, mimeMultipart.getCount(), 2);
280 response.close();
281 }
282
283 /**
284 * @tpTestDetails Client sends post request with "multipart/form-data" and boundary definition
285 * @tpSince RESTEasy 3.0.16
286 */
287 @Test
288 public void testFile() throws Exception {
289 Response response = client.target(TEST_URI + "/file/test").request()
290 .post(Entity.entity(form, "multipart/form-data; boundary=---------------------------52524491016334132001492192799"));
291 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
292 response.close();
293 }
294
295 private static final String form = "-----------------------------52524491016334132001492192799\r\n"
296 + "Content-Disposition: form-data; name=\"submit-name\"\r\n"
297 + "\r\n"
298 + "Bill\r\n"
299 + "-----------------------------52524491016334132001492192799\r\n"
300 + "Content-Disposition: form-data; name=\"files\"; filename=\"stuff.txt\"\r\n"
301 + "Content-Type: text/plain\r\n"
302 + "\r\n"
303 + "hello world\r\n"
304 + "\r\n"
305 + "-----------------------------52524491016334132001492192799--";
306 }
+0
-66
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/NullPartTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ProxyFactory;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.providers.multipart.resource.MyServiceProxy;
8 import org.jboss.resteasy.test.providers.multipart.resource.NullPartBean;
9 import org.jboss.resteasy.test.providers.multipart.resource.NullPartService;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.Assert;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 /**
19 * @tpSubChapter Multipart provider
20 * @tpChapter Integration tests
21 * @tpTestCaseDetails Test proxy with null part of message with multipart provider
22 * @tpSince RESTEasy 3.0.16
23 */
24 @RunWith(Arquillian.class)
25 @RunAsClient
26 public class NullPartTest {
27 @Deployment
28 public static Archive<?> deploy() {
29 WebArchive war = TestUtil.prepareArchive(NullPartTest.class.getSimpleName());
30 war.addClasses(NullPartBean.class, MyServiceProxy.class);
31 return TestUtil.finishContainerPrepare(war, null, NullPartService.class);
32 }
33
34 private static String generateBaseUrl() {
35 return PortProviderUtil.generateBaseUrl(NullPartTest.class.getSimpleName());
36 }
37
38 /**
39 * @tpTestDetails Test new client
40 * @tpSince RESTEasy 3.0.16
41 */
42 @Test
43 public void testNewClient() throws Exception {
44 MyServiceProxy proxy = new ResteasyClientBuilder().build().target(generateBaseUrl()).proxy(MyServiceProxy.class);
45
46 NullPartBean bean = proxy.createMyBean(); // should just be ok
47 Assert.assertNotNull(bean);
48 Assert.assertNull(bean.getSomeBinary());
49 }
50
51 /**
52 * @tpTestDetails Test old client
53 * @tpSince RESTEasy 3.0.16
54 */
55 @Test
56 public void testOldClient() throws Exception {
57 MyServiceProxy proxy = ProxyFactory.create(MyServiceProxy.class, generateBaseUrl());
58
59 NullPartBean bean = proxy.createMyBean(); // should just be ok
60 Assert.assertNotNull(bean);
61 Assert.assertNull(bean.getSomeBinary());
62 }
63
64
65 }
+0
-56
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/ProxyTest.java less more
0 package org.jboss.resteasy.test.providers.multipart;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
6 import org.jboss.resteasy.test.providers.multipart.resource.ProxyApiService;
7 import org.jboss.resteasy.test.providers.multipart.resource.ProxyAttachment;
8 import org.jboss.resteasy.test.providers.multipart.resource.ProxyResource;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Test;
14 import org.junit.runner.RunWith;
15
16 /**
17 * @tpSubChapter Multipart provider
18 * @tpChapter Integration tests
19 * @tpTestCaseDetails Test proxy with multipart provider
20 * @tpSince RESTEasy 3.0.16
21 */
22 @RunWith(Arquillian.class)
23 @RunAsClient
24 public class ProxyTest {
25
26 @Deployment
27 public static Archive<?> deploy() {
28 WebArchive war = TestUtil.prepareArchive(ProxyTest.class.getSimpleName());
29 war.addClass(ProxyApiService.class);
30 war.addClass(ProxyAttachment.class);
31 return TestUtil.finishContainerPrepare(war, null, ProxyResource.class);
32 }
33
34 private static String generateBaseUrl() {
35 return PortProviderUtil.generateBaseUrl(ProxyTest.class.getSimpleName());
36 }
37
38 /**
39 * @tpTestDetails ProxyAttachment object and string object is in request
40 * @tpSince RESTEasy 3.0.16
41 */
42 @Test
43 public void testNewBuilder() {
44 ProxyApiService apiService = new ResteasyClientBuilder().build().target(generateBaseUrl()).proxy(ProxyApiService.class);
45 tryCall(apiService);
46 }
47
48 private void tryCall(ProxyApiService apiService) {
49 ProxyAttachment attachment = new ProxyAttachment();
50 attachment.setData("foo".getBytes());
51 apiService.postAttachment(attachment, "some-key"); // any exception in ProxyResource would be thrown from proxy too, no assert needed
52 }
53
54
55 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ContextProvidersCustomer.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "customer")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class ContextProvidersCustomer {
10 @XmlElement
11 private String name;
12
13 public ContextProvidersCustomer() {
14 }
15
16 public ContextProvidersCustomer(final String name) {
17 this.name = name;
18 }
19
20 public String getName() {
21 return name;
22 }
23 }
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ContextProvidersCustomerForm.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2
3 import javax.ws.rs.FormParam;
4
5 import org.jboss.resteasy.annotations.providers.multipart.PartType;
6
7 public class ContextProvidersCustomerForm {
8 @FormParam("customer")
9 @PartType("application/xml")
10 private ContextProvidersCustomer customer;
11
12 public ContextProvidersCustomer getCustomer() {
13 return customer;
14 }
15
16 public void setCustomer(ContextProvidersCustomer cust) {
17 this.customer = cust;
18 }
19 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ContextProvidersName.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "name")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class ContextProvidersName {
10 @XmlElement
11 private String name;
12
13 public ContextProvidersName() {
14 }
15
16 public ContextProvidersName(final String name) {
17 this.name = name;
18 }
19
20 public String getName() {
21 return name;
22 }
23
24 public boolean equals(Object o) {
25 if (o == null) {
26 return false;
27 }
28 if (!(o instanceof ContextProvidersName)) {
29 return false;
30 }
31 return name.equals(((ContextProvidersName) o).getName());
32 }
33
34 public int hashCode() {
35 return super.hashCode();
36 }
37 }
+0
-208
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ContextProvidersResource.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.HashMap;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Map;
9
10 import javax.ws.rs.Consumes;
11 import javax.ws.rs.GET;
12 import javax.ws.rs.POST;
13 import javax.ws.rs.Path;
14 import javax.ws.rs.Produces;
15 import javax.ws.rs.core.MediaType;
16
17 import org.jboss.logging.Logger;
18 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
19 import org.jboss.resteasy.annotations.providers.multipart.PartType;
20 import org.jboss.resteasy.annotations.providers.multipart.XopWithMultipartRelated;
21 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
22 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
23 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
24 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
25 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
26 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedInput;
27 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedOutput;
28
29 @Path("")
30 public class ContextProvidersResource {
31
32 private static Logger logger = Logger.getLogger(ContextProvidersResource.class);
33
34 @GET
35 @Produces("multipart/mixed")
36 @Path("get/mixed")
37 public MultipartOutput getMixed() {
38 logger.info("entering getMixed()");
39 MultipartOutput output = new MultipartOutput();
40 output.addPart(new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE);
41 output.addPart("Bob", MediaType.TEXT_PLAIN_TYPE);
42 return output;
43 }
44
45 @GET
46 @Produces("multipart/form-data")
47 @MultipartForm
48 @Path("get/form")
49 public MultipartFormDataOutput getForm() {
50 logger.info("entering getForm()");
51 MultipartFormDataOutput output = new MultipartFormDataOutput();
52 output.addFormData("bill", new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE, "tmp1");
53 output.addFormData("bob", "Bob", MediaType.TEXT_PLAIN_TYPE);
54 return output;
55 }
56
57 @GET
58 @Produces("multipart/mixed")
59 @PartType("application/xml")
60 @Path("get/list")
61 public List<ContextProvidersCustomer> getList() {
62 logger.info("entering getList()");
63 List<ContextProvidersCustomer> list = new ArrayList<ContextProvidersCustomer>();
64 list.add(new ContextProvidersCustomer("Bill"));
65 list.add(new ContextProvidersCustomer("Bob"));
66 return list;
67 }
68
69 @GET
70 @Produces("multipart/form-data")
71 @PartType("application/xml")
72 @Path("get/map")
73 public Map<String, ContextProvidersCustomer> getMap() {
74 logger.info("entering getMap()");
75 Map<String, ContextProvidersCustomer> map = new HashMap<String, ContextProvidersCustomer>();
76 map.put("bill", new ContextProvidersCustomer("Bill"));
77 map.put("bob", new ContextProvidersCustomer("Bob"));
78 return map;
79 }
80
81 @GET
82 @Produces("multipart/related")
83 @Path("get/related")
84 public MultipartRelatedOutput getRelated() {
85 logger.info("entering getRelated()");
86 MultipartRelatedOutput output = new MultipartRelatedOutput();
87 output.setStartInfo("text/html");
88 output.addPart("Bill", new MediaType("image", "png"), "bill", "binary");
89 output.addPart("Bob", new MediaType("image", "png"), "bob", "binary");
90 return output;
91 }
92
93 @GET
94 @Path("get/multipartform")
95 @Produces("multipart/form-data")
96 @MultipartForm
97 public ContextProvidersCustomerForm getMultipartForm() {
98 ContextProvidersCustomerForm form = new ContextProvidersCustomerForm();
99 form.setCustomer(new ContextProvidersCustomer("Bill"));
100 return form;
101 }
102
103 @GET
104 @Path("get/xop")
105 @Produces("multipart/related")
106 @XopWithMultipartRelated
107 public ContextProvidersXop getXop() {
108 return new ContextProvidersXop("goodbye world".getBytes());
109 }
110
111 @POST
112 @Consumes("multipart/mixed")
113 @Produces(MediaType.APPLICATION_XML)
114 @Path("post/mixed")
115 public List<ContextProvidersName> postMixed(MultipartInput input) throws IOException {
116 logger.info("entering getMixed()");
117 List<InputPart> list = input.getParts();
118 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
119 for (Iterator<InputPart> it = list.iterator(); it.hasNext(); ) {
120 InputPart inputPart = it.next();
121 if (MediaType.APPLICATION_XML_TYPE.equals(inputPart.getMediaType())) {
122 names.add(new ContextProvidersName(inputPart.getBody(ContextProvidersCustomer.class, null).getName()));
123 } else {
124 names.add(new ContextProvidersName(inputPart.getBody(String.class, null)));
125 }
126 }
127 return names;
128 }
129
130 @POST
131 @Consumes("multipart/form-data")
132 @Produces(MediaType.APPLICATION_XML)
133 @Path("post/form")
134 public List<ContextProvidersName> postForm(MultipartFormDataInput input) throws IOException {
135 logger.info("entering postForm()");
136 Map<String, List<InputPart>> map = input.getFormDataMap();
137 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
138 for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
139 String key = it.next();
140 InputPart inputPart = map.get(key).iterator().next();
141 if (MediaType.APPLICATION_XML_TYPE.equals(inputPart.getMediaType())) {
142 names.add(new ContextProvidersName(inputPart.getBody(ContextProvidersCustomer.class, null).getName()));
143 } else {
144 names.add(new ContextProvidersName(inputPart.getBody(String.class, null)));
145 }
146 }
147 return names;
148 }
149
150 @POST
151 @Consumes("multipart/mixed")
152 @Produces(MediaType.APPLICATION_XML)
153 @Path("post/list")
154 public List<ContextProvidersName> postList(List<ContextProvidersCustomer> customers) throws IOException {
155 logger.info("entering postList()");
156 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
157 for (ContextProvidersCustomer customer : customers) {
158 names.add(new ContextProvidersName(customer.getName()));
159 }
160 return names;
161 }
162
163 @POST
164 @Consumes("multipart/form-data")
165 @Produces(MediaType.APPLICATION_XML)
166 @Path("post/map")
167 public List<ContextProvidersName> postMap(Map<String, ContextProvidersCustomer> customers) throws IOException {
168 logger.info("entering postMap()");
169 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
170 for (Iterator<String> it = customers.keySet().iterator(); it.hasNext(); ) {
171 String key = it.next();
172 ContextProvidersCustomer customer = customers.get(key);
173 names.add(new ContextProvidersName(key + ":" + customer.getName()));
174 }
175 return names;
176 }
177
178 @POST
179 @Consumes("multipart/related")
180 @Produces(MediaType.APPLICATION_XML)
181 @Path("post/related")
182 public List<ContextProvidersName> postRelated(MultipartRelatedInput customers) throws IOException {
183 logger.info("entering postMap()");
184 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
185 for (Iterator<InputPart> it = customers.getParts().iterator(); it.hasNext(); ) {
186 InputPart part = it.next();
187 String name = part.getBody(String.class, null);
188 names.add(new ContextProvidersName(name));
189 }
190 return names;
191 }
192
193 @POST
194 @Consumes("multipart/form-data")
195 @Path("post/multipartform")
196 public String postMultipartForm(@MultipartForm ContextProvidersCustomerForm form) throws IOException {
197 logger.info("entering postMultipartForm()");
198 return form.getCustomer().getName();
199 }
200
201 @POST
202 @Path("post/xop")
203 @Consumes("multipart/related")
204 public String postXop(@XopWithMultipartRelated ContextProvidersXop xop) {
205 return new String(xop.getBytes());
206 }
207 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ContextProvidersXop.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import javax.ws.rs.core.MediaType;
3 import javax.xml.bind.annotation.XmlAccessType;
4 import javax.xml.bind.annotation.XmlAccessorType;
5 import javax.xml.bind.annotation.XmlMimeType;
6 import javax.xml.bind.annotation.XmlRootElement;
7
8 @XmlRootElement
9 @XmlAccessorType(XmlAccessType.FIELD)
10 public class ContextProvidersXop {
11 @XmlMimeType(MediaType.APPLICATION_OCTET_STREAM)
12 private byte[] bytes;
13
14 public ContextProvidersXop(final byte[] bytes) {
15 this.bytes = bytes;
16 }
17
18 public ContextProvidersXop() {
19 }
20
21 public byte[] getBytes() {
22 return bytes;
23 }
24
25 public void setBytes(byte[] bytes) {
26 this.bytes = bytes;
27 }
28 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/EmbeddedMultipartCustomer.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import javax.xml.bind.annotation.XmlElement;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement(name = "customer")
6 public class EmbeddedMultipartCustomer {
7 private String name;
8
9 public EmbeddedMultipartCustomer() {
10 }
11
12 public EmbeddedMultipartCustomer(final String name) {
13 this.name = name;
14 }
15
16 @XmlElement
17 public String getName() {
18 return name;
19 }
20
21 public void setName(String name) {
22 this.name = name;
23 }
24 }
+0
-47
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/EmbeddedMultipartResource.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
3 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
4
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.Response;
11 import java.io.IOException;
12
13 @Path("")
14 public class EmbeddedMultipartResource {
15 @Path("embedded")
16 @POST
17 @Consumes("multipart/mixed")
18 @Produces(MediaType.TEXT_PLAIN)
19 public Response post(MultipartInput input) throws Exception {
20 InputPart inputPart = input.getParts().iterator().next();
21 MultipartInput multipart = inputPart.getBody(MultipartInput.class, null);
22 inputPart = multipart.getParts().iterator().next();
23 EmbeddedMultipartCustomer customer = inputPart.getBody(EmbeddedMultipartCustomer.class, null);
24 return Response.ok(customer.getName()).build();
25 }
26
27 @Path("customer")
28 @POST
29 @Consumes("multipart/mixed")
30 @Produces(MediaType.TEXT_PLAIN)
31 public Response postCustomer(MultipartInput input) throws IOException {
32 InputPart part = input.getParts().iterator().next();
33 EmbeddedMultipartCustomer customer = part.getBody(EmbeddedMultipartCustomer.class, null);
34 return Response.ok(customer.getName()).build();
35 }
36
37 @Path("invalid")
38 @POST
39 @Consumes("multipart/mixed")
40 @Produces(MediaType.TEXT_PLAIN)
41 public Response postInvalid(MultipartInput input) throws IOException {
42 InputPart part = input.getParts().iterator().next();
43 Object o = part.getBody(EmbeddedMultipartResource.class, null);
44 return Response.ok(o).build();
45 }
46 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/EmptyInputStreamMultipartProviderMyBean.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.PartType;
3
4 import javax.ws.rs.FormParam;
5 import javax.ws.rs.core.MediaType;
6 import java.io.InputStream;
7
8 public class EmptyInputStreamMultipartProviderMyBean {
9 @FormParam("someBinary")
10 @PartType(MediaType.APPLICATION_OCTET_STREAM)
11 private InputStream someBinary;
12
13 public InputStream getSomeBinary() {
14 return someBinary;
15 }
16
17 public void setSomeBinary(InputStream someBinary) {
18 this.someBinary = someBinary;
19 }
20 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/EmptyInputStreamMultipartProviderResource.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.MediaType;
8 import java.io.ByteArrayInputStream;
9
10 @Path("/rest/zba")
11 public class EmptyInputStreamMultipartProviderResource {
12 @GET
13 @Produces(MediaType.MULTIPART_FORM_DATA)
14 @MultipartForm
15 public EmptyInputStreamMultipartProviderMyBean get() {
16 EmptyInputStreamMultipartProviderMyBean myBean = new EmptyInputStreamMultipartProviderMyBean();
17 myBean.setSomeBinary(new ByteArrayInputStream(new byte[0]));
18 return myBean;
19 }
20 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/GenericTypeResource.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
3 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
4 import org.jboss.resteasy.test.providers.multipart.GenericTypeMultipartTest;
5
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.Response;
12 import java.io.IOException;
13 import java.util.Iterator;
14 import java.util.List;
15
16 @Path("")
17 public class GenericTypeResource {
18 @POST
19 @Path("test")
20 @Consumes(MediaType.MULTIPART_FORM_DATA)
21 @Produces(MediaType.TEXT_PLAIN)
22 public Response testInputPartSetMediaType(MultipartInput input) throws IOException {
23 List<InputPart> parts = input.getParts();
24 InputPart part = parts.get(0);
25 List<String> body = part.getBody(GenericTypeMultipartTest.stringListType);
26 String reply = "";
27 for (Iterator<String> it = body.iterator(); it.hasNext(); ) {
28 reply += it.next() + " ";
29 }
30 return Response.ok(reply).build();
31 }
32 }
+0
-70
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/GenericTypeStringListReaderWriter.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.test.providers.multipart.GenericTypeMultipartTest;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyReader;
10 import javax.ws.rs.ext.MessageBodyWriter;
11 import java.io.ByteArrayOutputStream;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.OutputStream;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17 import java.util.ArrayList;
18 import java.util.Iterator;
19 import java.util.List;
20
21 @Consumes(MediaType.APPLICATION_XML)
22 @Produces(MediaType.APPLICATION_XML)
23 public class GenericTypeStringListReaderWriter implements MessageBodyReader<List<String>>, MessageBodyWriter<List<String>> {
24 @Override
25 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
26 return GenericTypeMultipartTest.stringListType.getType().equals(genericType);
27 }
28
29 @Override
30 public long getSize(List<String> t, Class<?> type, Type genericType, Annotation[] annotations,
31 MediaType mediaType) {
32 return -1;
33 }
34
35 @Override
36 public void writeTo(List<String> t, Class<?> type, Type genericType, Annotation[] annotations,
37 MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
38 throws IOException, WebApplicationException {
39 List<String> list = t;
40 for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
41 entityStream.write(it.next().getBytes());
42 entityStream.write("\r".getBytes());
43 }
44 }
45
46 @Override
47 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
48 return GenericTypeMultipartTest.stringListType.getType().equals(genericType);
49 }
50
51 @Override
52 public List<String> readFrom(Class<List<String>> type, Type genericType, Annotation[] annotations,
53 MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
54 throws IOException, WebApplicationException {
55 List<String> list = new ArrayList<String>();
56 ByteArrayOutputStream baos = new ByteArrayOutputStream();
57 byte b = (byte) entityStream.read();
58 while (b > -1) {
59 while (b != '\r') {
60 baos.write(b);
61 b = (byte) entityStream.read();
62 }
63 list.add(new String(baos.toByteArray()));
64 baos.reset();
65 b = (byte) entityStream.read();
66 }
67 return list;
68 }
69 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/HeaderFlushedOutputStreamBean.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.PartType;
3
4 import javax.ws.rs.FormParam;
5 import javax.ws.rs.core.MediaType;
6 import java.io.InputStream;
7
8 public class HeaderFlushedOutputStreamBean {
9 @FormParam("someBinary")
10 @PartType(MediaType.APPLICATION_OCTET_STREAM)
11 private InputStream someBinary;
12
13 public InputStream getSomeBinary() {
14 return someBinary;
15 }
16
17 public void setSomeBinary(InputStream someBinary) {
18 this.someBinary = someBinary;
19 }
20 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/HeaderFlushedOutputStreamService.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.HttpHeaders;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.Response;
12 import java.io.ByteArrayInputStream;
13
14 @Path("/mime")
15 public class HeaderFlushedOutputStreamService {
16
17 @POST
18 public Response createMyBean(@Context HttpHeaders headers, String str) {
19 return Response.ok(str, headers.getMediaType()).build();
20 }
21
22 @GET
23 @Produces(MediaType.MULTIPART_FORM_DATA)
24 @MultipartForm
25 public HeaderFlushedOutputStreamBean createMyBean() {
26 HeaderFlushedOutputStreamBean myBean = new HeaderFlushedOutputStreamBean();
27 myBean.setSomeBinary(new ByteArrayInputStream("bla".getBytes()));
28 return myBean;
29 }
30 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteContentTypeCharsetUTF16 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_US_ASCII);
19 request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_16);
20 return null;
21 }
22 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteContentTypeCharsetUTF8 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_US_ASCII);
19 request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_8);
20 return null;
21 }
22 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF16 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_UTF_16);
19 return null;
20 }
21 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteContentTypeNoCharsetUTF8 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, InputPartDefaultCharsetOverwriteTest.TEXT_HTTP_WITH_CHARSET_UTF_8);
19 return null;
20 }
21 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF16 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_16);
19 return null;
20 }
21 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultCharsetOverwriteTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultCharsetOverwriteNoContentTypeCharsetUTF8 implements PreProcessInterceptor {
17 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
18 request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, InputPartDefaultCharsetOverwriteTest.UTF_8);
19 return null;
20 }
21 }
+0
-60
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultCharsetOverwriteService.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.logging.Logger;
3 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
4 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
5
6 import javax.ws.rs.Consumes;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.QueryParam;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.Response;
13 import java.io.IOException;
14 import java.util.List;
15
16 @Path("")
17 public class InputPartDefaultCharsetOverwriteService {
18 private static Logger logger = Logger.getLogger(InputPartDefaultCharsetOverwriteService.class);
19
20 @POST
21 @Path("test")
22 @Consumes(MediaType.MULTIPART_FORM_DATA)
23 @Produces(MediaType.TEXT_PLAIN)
24 public Response testDefaultContentType(MultipartInput input) throws IOException {
25 List<InputPart> parts = input.getParts();
26 InputPart part = parts.get(0);
27 String s1 = part.getBody(String.class, null);
28 String s2 = part.getBodyAsString();
29 String result = part.getMediaType() + ":" + s1 + ":" + s2;
30 logger.info("server response: " + result);
31 return Response.ok(result, part.getMediaType()).build();
32 }
33
34 @POST
35 @Path("query")
36 @Consumes(MediaType.MULTIPART_FORM_DATA)
37 @Produces(MediaType.TEXT_PLAIN)
38 public Response testInputPartSetMediaType(@QueryParam("contentType") String mediaType, MultipartInput input) throws IOException {
39 List<InputPart> parts = input.getParts();
40 InputPart part = parts.get(0);
41 part.setMediaType(MediaType.valueOf(mediaType));
42 String s1 = part.getBody(String.class, null);
43 String s2 = part.getBodyAsString();
44 String result = part.getMediaType() + ":" + s1 + ":" + s2;
45 logger.info("server response: " + result);
46 return Response.ok(result, part.getMediaType()).build();
47 }
48
49 @POST
50 @Path("bytes")
51 @Consumes(MediaType.WILDCARD)
52 @Produces(MediaType.APPLICATION_OCTET_STREAM)
53 public Response testByteArray(MultipartInput input) throws IOException {
54 List<InputPart> parts = input.getParts();
55 InputPart part = parts.get(0);
56 byte[] b = part.getBody(byte[].class, null);
57 return Response.ok(b).build();
58 }
59 }
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultContentTypeEncodingOverwriteService.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.core.MediaType;
9
10 @Path("/mime")
11 public class InputPartDefaultContentTypeEncodingOverwriteService {
12
13 @POST
14 @Consumes(MediaType.MULTIPART_FORM_DATA)
15 @Produces(MediaType.TEXT_PLAIN)
16 public String sendDefaultContentType(MultipartInput input) {
17 return input.getParts().get(0).getMediaType().toString();
18 }
19 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultContentTypeEncodingOverwriteSetterPreProcessorInterceptor.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultContentTypeEncodingOverwriteTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultContentTypeEncodingOverwriteSetterPreProcessorInterceptor implements
17 PreProcessInterceptor {
18
19 public ServerResponse preProcess(HttpRequest request,
20 ResourceMethodInvoker method) throws Failure, WebApplicationException {
21 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY,
22 InputPartDefaultContentTypeEncodingOverwriteTest.TEXT_PLAIN_WITH_CHARSET_UTF_8);
23 return null;
24 }
25
26 }
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultContentTypeWildcardOverwriteContainerBean.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.PartType;
3
4 import javax.ws.rs.FormParam;
5 import javax.ws.rs.core.MediaType;
6
7 public class InputPartDefaultContentTypeWildcardOverwriteContainerBean {
8 @FormParam("foo")
9 @PartType(MediaType.APPLICATION_XML)
10 private InputPartDefaultContentTypeWildcardOverwriteXmlBean foo;
11
12 public InputPartDefaultContentTypeWildcardOverwriteXmlBean getFoo() {
13 return foo;
14 }
15
16 public void setFoo(InputPartDefaultContentTypeWildcardOverwriteXmlBean foo) {
17 this.foo = foo;
18 }
19 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultContentTypeWildcardOverwriteNewInterceptor.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
3 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultContentTypeWildcardOverwriteNewInterceptorTest;
4
5 import javax.ws.rs.container.ContainerRequestContext;
6 import javax.ws.rs.ext.Provider;
7
8 @Provider
9 public class InputPartDefaultContentTypeWildcardOverwriteNewInterceptor implements
10 javax.ws.rs.container.ContainerRequestFilter {
11 @Override
12 public void filter(ContainerRequestContext requestContext) {
13 requestContext.setProperty(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY,
14 InputPartDefaultContentTypeWildcardOverwriteNewInterceptorTest.WILDCARD_WITH_CHARSET_UTF_8);
15 }
16 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultContentTypeWildcardOverwriteOldInterceptor.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.interception.ServerInterceptor;
3 import org.jboss.resteasy.core.ResourceMethodInvoker;
4 import org.jboss.resteasy.core.ServerResponse;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.spi.Failure;
7 import org.jboss.resteasy.spi.HttpRequest;
8 import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
9 import org.jboss.resteasy.test.providers.multipart.InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.ws.rs.ext.Provider;
13
14 @Provider
15 @ServerInterceptor
16 public class InputPartDefaultContentTypeWildcardOverwriteOldInterceptor implements
17 PreProcessInterceptor {
18
19
20 public ServerResponse preProcess(HttpRequest request,
21 ResourceMethodInvoker method) throws Failure, WebApplicationException {
22 request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY,
23 InputPartDefaultContentTypeWildcardOverwriteDeprecatedInterceptorTest.WILDCARD_WITH_CHARSET_UTF_8);
24 return null;
25 }
26
27 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultContentTypeWildcardOverwriteService.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.core.MediaType;
9
10 @Path("/mime")
11 public class InputPartDefaultContentTypeWildcardOverwriteService {
12 @POST
13 @Consumes(MediaType.MULTIPART_FORM_DATA)
14 @Produces(MediaType.TEXT_PLAIN)
15 public int echoMultipartForm(@MultipartForm InputPartDefaultContentTypeWildcardOverwriteContainerBean containerBean) {
16 return containerBean.getFoo().getMyInt();
17 }
18 }
+0
-28
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultContentTypeWildcardOverwriteXmlBean.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlRootElement;
5
6 @XmlRootElement
7 @XmlAccessorType(XmlAccessType.FIELD)
8 public class InputPartDefaultContentTypeWildcardOverwriteXmlBean {
9 private int myInt;
10 private String myString;
11
12 public int getMyInt() {
13 return myInt;
14 }
15
16 public void setMyInt(int myInt) {
17 this.myInt = myInt;
18 }
19
20 public String getMyString() {
21 return myString;
22 }
23
24 public void setMyString(String myString) {
25 this.myString = myString;
26 }
27 }
+0
-58
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/MimeMultipartProviderClient.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.PUT;
4 import javax.ws.rs.Path;
5
6 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
7 import org.jboss.resteasy.annotations.providers.multipart.PartType;
8 import org.jboss.resteasy.annotations.providers.multipart.XopWithMultipartRelated;
9 import org.jboss.resteasy.plugins.providers.multipart.MultipartConstants;
10 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
11 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
12 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedOutput;
13
14 import java.util.List;
15 import java.util.Map;
16
17 @Path("mime")
18 public interface MimeMultipartProviderClient {
19 @Path("mixed")
20 @PUT
21 @Consumes("multipart/mixed")
22 void putMixed(MultipartOutput output);
23
24 @Path("form")
25 @PUT
26 @Consumes("multipart/form-data")
27 void putFormData(MultipartFormDataOutput output);
28
29 @Path("related")
30 @PUT
31 @Consumes(MultipartConstants.MULTIPART_RELATED)
32 void putRelated(MultipartRelatedOutput output);
33
34 @Path("mixed")
35 @PUT
36 @Consumes("multipart/mixed")
37 void putMixedList(
38 @PartType("application/xml") List<MimeMultipartProviderCustomer> mimeMultipartProviderCustomers);
39
40 @Path("form")
41 @PUT
42 @Consumes("multipart/form-data")
43 void putFormDataMap(
44 @PartType("application/xml") Map<String, MimeMultipartProviderCustomer> customers);
45
46 @Path("form/class")
47 @PUT
48 @Consumes("multipart/form-data")
49 void putFormDataMap(
50 @MultipartForm MimeMultipartProviderResource.Form form);
51
52 @Path("xop")
53 @PUT
54 @Consumes(MultipartConstants.MULTIPART_RELATED)
55 void putXop(
56 @XopWithMultipartRelated MimeMultipartProviderResource.Xop bean);
57 }
+0
-25
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/MimeMultipartProviderCustomer.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import javax.xml.bind.annotation.XmlElement;
3 import javax.xml.bind.annotation.XmlRootElement;
4
5 @XmlRootElement(name = "customer")
6 public class MimeMultipartProviderCustomer {
7 private String name;
8
9 public MimeMultipartProviderCustomer() {
10 }
11
12 public MimeMultipartProviderCustomer(final String name) {
13 this.name = name;
14 }
15
16 @XmlElement
17 public String getName() {
18 return name;
19 }
20
21 public void setName(String name) {
22 this.name = name;
23 }
24 }
+0
-364
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/MimeMultipartProviderResource.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
4 import org.jboss.resteasy.annotations.providers.multipart.PartType;
5 import org.jboss.resteasy.annotations.providers.multipart.XopWithMultipartRelated;
6 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
7 import org.jboss.resteasy.plugins.providers.multipart.MultipartConstants;
8 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
9 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
10 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedInput;
11 import org.junit.Assert;
12
13 import javax.activation.DataHandler;
14 import javax.mail.MessagingException;
15 import javax.mail.internet.MimeBodyPart;
16 import javax.mail.internet.MimeMultipart;
17 import javax.ws.rs.Consumes;
18 import javax.ws.rs.FormParam;
19 import javax.ws.rs.GET;
20 import javax.ws.rs.POST;
21 import javax.ws.rs.PUT;
22 import javax.ws.rs.Path;
23 import javax.ws.rs.Produces;
24 import javax.ws.rs.core.MediaType;
25 import javax.xml.bind.annotation.XmlAccessType;
26 import javax.xml.bind.annotation.XmlAccessorType;
27 import javax.xml.bind.annotation.XmlMimeType;
28 import javax.xml.bind.annotation.XmlRootElement;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.io.StringWriter;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36
37 @Path("/mime")
38 public class MimeMultipartProviderResource {
39
40 public static class Form {
41 @FormParam("bill")
42 @PartType("application/xml")
43 private MimeMultipartProviderCustomer bill;
44
45 @FormParam("monica")
46 @PartType("application/xml")
47 private MimeMultipartProviderCustomer monica;
48
49 public Form() {
50 }
51
52 public Form(final MimeMultipartProviderCustomer bill, final MimeMultipartProviderCustomer monica) {
53 this.bill = bill;
54 this.monica = monica;
55 }
56
57 public MimeMultipartProviderCustomer getBill() {
58 return bill;
59 }
60
61 public MimeMultipartProviderCustomer getMonica() {
62 return monica;
63 }
64 }
65
66 @XmlRootElement
67 @XmlAccessorType(XmlAccessType.FIELD)
68 public static class Xop {
69 private MimeMultipartProviderCustomer bill;
70
71 private MimeMultipartProviderCustomer monica;
72
73 @XmlMimeType(MediaType.APPLICATION_OCTET_STREAM)
74 private byte[] myBinary;
75
76 @XmlMimeType(MediaType.APPLICATION_OCTET_STREAM)
77 private DataHandler myDataHandler;
78
79 public Xop() {
80 }
81
82 public Xop(final MimeMultipartProviderCustomer bill, final MimeMultipartProviderCustomer monica, final byte[] myBinary,
83 final DataHandler myDataHandler) {
84 this.bill = bill;
85 this.monica = monica;
86 this.myBinary = myBinary;
87 this.myDataHandler = myDataHandler;
88 }
89
90 public MimeMultipartProviderCustomer getBill() {
91 return bill;
92 }
93
94 public MimeMultipartProviderCustomer getMonica() {
95 return monica;
96 }
97
98 public byte[] getMyBinary() {
99 return myBinary;
100 }
101
102 public DataHandler getMyDataHandler() {
103 return myDataHandler;
104 }
105 }
106
107 public static class Form2 {
108 @FormParam("submit-name")
109 public String name;
110
111 @FormParam("files")
112 public byte[] file;
113 }
114
115 private static Logger logger = Logger.getLogger(MimeMultipartProviderResource.class);
116 private static final String ERR_MULTIPART_PROPERTY = "Property from multipart is not correct";
117 private static final String ERR_MULTIPART_FORM = "Multipart form value is incorrect";
118 private static final String ERR_NUMBER = "The number of enclosed bodypart objects doesn't match to the expectation";
119 private static final String ERR_CUST_NULL = "The customer entity is not expected to be null";
120 private static final String ERR_VALUE = "Unexpected value";
121
122
123 @POST
124 @Path("file/test")
125 @Consumes(MediaType.MULTIPART_FORM_DATA)
126 @Produces("text/html")
127 public String post(@MultipartForm Form2 form) {
128 Assert.assertEquals(ERR_MULTIPART_FORM, "Bill", form.name.trim());
129 Assert.assertEquals(ERR_MULTIPART_FORM, "hello world", new String(form.file).trim());
130 return "hello world";
131 }
132
133 @PUT
134 @Consumes("multipart/form-data")
135 @Produces("text/plain")
136 public String putData(MimeMultipart multipart) {
137 StringBuilder b = new StringBuilder("Count: ");
138 try {
139 b.append(multipart.getCount());
140 for (int i = 0; i < multipart.getCount(); i++) {
141 try {
142 logger.debug(multipart.getBodyPart(i).getContent().toString());
143 logger.debug("bytes available {0}" + multipart.getBodyPart(i).getInputStream().available());
144 } catch (IOException e) {
145 // TODO Auto-generated catch block
146 logger.info(e.getCause());
147 }
148 }
149 } catch (MessagingException e) {
150 // TODO Auto-generated catch block
151 logger.info(e.getCause());
152 }
153 return b.toString();
154 }
155
156 @PUT
157 @Path("form")
158 @Consumes("multipart/form-data")
159 public void putMultipartFormData(MultipartFormDataInput multipart)
160 throws IOException {
161 Assert.assertEquals(ERR_NUMBER, 2, multipart.getParts().size());
162
163 Assert.assertTrue(ERR_MULTIPART_FORM, multipart.getFormDataMap().containsKey("bill"));
164 Assert.assertTrue(ERR_MULTIPART_FORM, multipart.getFormDataMap().containsKey("monica"));
165
166 logger.info(multipart.getFormDataMap().get("bill").get(0).getBodyAsString());
167 MimeMultipartProviderCustomer cust = multipart.getFormDataPart("bill", MimeMultipartProviderCustomer.class, null);
168 Assert.assertNotNull(ERR_CUST_NULL, cust);
169 Assert.assertEquals(ERR_MULTIPART_FORM, "bill", cust.getName());
170
171 cust = multipart.getFormDataPart("monica", MimeMultipartProviderCustomer.class, null);
172 Assert.assertNotNull(ERR_CUST_NULL, cust);
173 Assert.assertEquals(ERR_VALUE, "monica", cust.getName());
174
175 }
176
177 @PUT
178 @Path("related")
179 @Consumes(MultipartConstants.MULTIPART_RELATED)
180 public void putMultipartRelated(MultipartRelatedInput multipart)
181 throws IOException {
182 Assert.assertEquals(ERR_MULTIPART_PROPERTY, MultipartConstants.APPLICATION_XOP_XML, multipart.getType());
183 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "<mymessage.xml@example.org>", multipart.getStart());
184 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "text/xml", multipart.getStartInfo());
185 Assert.assertEquals(ERR_NUMBER, 3, multipart.getParts().size());
186 Iterator<InputPart> inputParts = multipart.getParts().iterator();
187 Assert.assertEquals(ERR_MULTIPART_PROPERTY, inputParts.next(), multipart.getRootPart());
188 InputPart rootPart = multipart.getRootPart();
189
190 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "application", rootPart.getMediaType().getType());
191 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "xop+xml", rootPart.getMediaType().getSubtype());
192 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "UTF-8", rootPart.getMediaType().getParameters().get("charset"));
193 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "text/xml", rootPart.getMediaType().getParameters().get("type"));
194 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "<mymessage.xml@example.org>", rootPart.getHeaders().getFirst("Content-ID"));
195 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "8bit", rootPart.getHeaders().getFirst("Content-Transfer-Encoding"));
196 Assert.assertEquals(ERR_VALUE,
197 "<m:data xmlns:m='http://example.org/stuff'>"
198 + "<m:photo><xop:Include xmlns:xop='http://www.w3.org/2004/08/xop/include' href='cid:http://example.org/me.png'/></m:photo>"
199 + "<m:sig><xop:Include xmlns:xop='http://www.w3.org/2004/08/xop/include' href='cid:http://example.org/my.hsh'/></m:sig>"
200 + "</m:data>", rootPart.getBodyAsString());
201
202 InputPart relatedPart1 = inputParts.next();
203 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "image", relatedPart1.getMediaType().getType());
204 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "png", relatedPart1.getMediaType().getSubtype());
205 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "<http://example.org/me.png>", relatedPart1
206 .getHeaders().getFirst("Content-ID"));
207 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "binary", relatedPart1.getHeaders().getFirst("Content-Transfer-Encoding"));
208 Assert.assertEquals(ERR_VALUE, "// binary octets for png", relatedPart1.getBodyAsString());
209
210 InputPart relatedPart2 = inputParts.next();
211 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "application", relatedPart2.getMediaType().getType());
212 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "pkcs7-signature", relatedPart2.getMediaType().getSubtype());
213 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "<http://example.org/me.hsh>", relatedPart2
214 .getHeaders().getFirst("Content-ID"));
215 Assert.assertEquals(ERR_MULTIPART_PROPERTY, "binary", relatedPart2.getHeaders().getFirst("Content-Transfer-Encoding"));
216 Assert.assertEquals(ERR_VALUE, "// binary octets for signature", relatedPart2.getBodyAsString());
217 }
218
219 @PUT
220 @Path("form/map")
221 @Consumes("multipart/form-data")
222 public void putMultipartMap(Map<String, MimeMultipartProviderCustomer> multipart)
223 throws IOException {
224 Assert.assertEquals(ERR_NUMBER, 2, multipart.size());
225
226 Assert.assertTrue(ERR_VALUE, multipart.containsKey("bill"));
227 Assert.assertTrue(ERR_VALUE, multipart.containsKey("monica"));
228
229 MimeMultipartProviderCustomer cust = multipart.get("bill");
230 Assert.assertNotNull(ERR_CUST_NULL, cust);
231 Assert.assertEquals(ERR_VALUE, "bill", cust.getName());
232
233 cust = multipart.get("monica");
234 Assert.assertNotNull(ERR_CUST_NULL, cust);
235 Assert.assertEquals(ERR_VALUE, "monica", cust.getName());
236
237 }
238
239 @PUT
240 @Path("multi")
241 @Consumes("multipart/form-data")
242 public void putMultipartData(MultipartInput multipart) throws IOException {
243 Assert.assertEquals(ERR_NUMBER, 2, multipart.getParts().size());
244
245 MimeMultipartProviderCustomer cust = multipart.getParts().get(0).getBody(MimeMultipartProviderCustomer.class,
246 null);
247 Assert.assertNotNull(ERR_CUST_NULL, cust);
248 Assert.assertEquals(ERR_VALUE, "bill", cust.getName());
249
250 cust = multipart.getParts().get(1).getBody(MimeMultipartProviderCustomer.class, null);
251 Assert.assertNotNull(ERR_CUST_NULL, cust);
252 Assert.assertEquals(ERR_VALUE, "monica", cust.getName());
253
254 }
255
256 @PUT
257 @Path("mixed")
258 @Consumes("multipart/mixed")
259 public void putMultipartMixed(MultipartInput multipart) throws IOException {
260 Assert.assertEquals(ERR_NUMBER, 2, multipart.getParts().size());
261
262 MimeMultipartProviderCustomer cust = multipart.getParts().get(0).getBody(MimeMultipartProviderCustomer.class,
263 null);
264 Assert.assertNotNull(ERR_CUST_NULL, cust);
265 Assert.assertEquals(ERR_VALUE, "bill", cust.getName());
266
267 cust = multipart.getParts().get(1).getBody(MimeMultipartProviderCustomer.class, null);
268 Assert.assertNotNull(ERR_CUST_NULL, cust);
269 Assert.assertEquals(ERR_VALUE, "monica", cust.getName());
270
271 }
272
273 @PUT
274 @Path("multi/list")
275 @Consumes("multipart/form-data")
276 public void putMultipartList(List<MimeMultipartProviderCustomer> multipart) throws IOException {
277 Assert.assertEquals(ERR_NUMBER, 2, multipart.size());
278
279 MimeMultipartProviderCustomer cust = multipart.get(0);
280 Assert.assertNotNull(ERR_CUST_NULL, cust);
281 Assert.assertEquals(ERR_VALUE, "bill", cust.getName());
282
283 cust = multipart.get(1);
284 Assert.assertNotNull(ERR_CUST_NULL, cust);
285 Assert.assertEquals(ERR_VALUE, "monica", cust.getName());
286
287 }
288
289 @PUT
290 @Path("form/class")
291 @Consumes("multipart/form-data")
292 public void putMultipartForm(@MultipartForm Form form) throws IOException {
293 Assert.assertNotNull(ERR_CUST_NULL, form.getBill());
294 Assert.assertEquals(ERR_VALUE, "bill", form.getBill().getName());
295
296 Assert.assertNotNull(ERR_CUST_NULL, form.getMonica());
297 Assert.assertEquals(ERR_VALUE, "monica", form.getMonica().getName());
298 }
299
300 @PUT
301 @Path("xop")
302 @Consumes(MultipartConstants.MULTIPART_RELATED)
303 public void putXopWithMultipartRelated(@XopWithMultipartRelated Xop xop)
304 throws IOException {
305 Assert.assertNotNull(ERR_CUST_NULL, xop.getBill());
306 Assert.assertEquals(ERR_VALUE, "bill\u00E9", xop.getBill().getName());
307
308 Assert.assertNotNull(ERR_CUST_NULL, xop.getMonica());
309 Assert.assertEquals(ERR_VALUE, "monica", xop.getMonica().getName());
310 Assert.assertNotNull(ERR_CUST_NULL, xop.getMyBinary());
311 Assert.assertNotNull(ERR_CUST_NULL, xop.getMyDataHandler());
312 Assert.assertEquals(ERR_VALUE, "Hello Xop World!", new String(xop.getMyBinary(),
313 "UTF-8"));
314 // lets do it twice to test that we get different InputStream-s each
315 // time.
316 for (int fi = 0; fi < 2; fi++) {
317 InputStream inputStream = xop.getMyDataHandler().getInputStream();
318 InputStreamReader inputStreamReader = null;
319 try {
320 inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
321 StringWriter writer = new StringWriter();
322 char[] buffer = new char[4048];
323 int n = 0;
324 while ((n = inputStreamReader.read(buffer)) != -1) {
325 writer.write(buffer, 0, n);
326 }
327 Assert.assertEquals(ERR_VALUE, "Hello Xop World!", writer.toString());
328 } finally {
329 if (inputStreamReader != null) {
330 inputStreamReader.close();
331 }
332 inputStream.close();
333 }
334 }
335 }
336
337 @PUT
338 @Path("text")
339 @Consumes("multipart/form-data")
340 @Produces("text/plain")
341 public void putData(String multipart) {
342 logger.info(multipart);
343 }
344
345 @GET
346 @Produces("multipart/mixed")
347 public MimeMultipart getMimeMultipart() throws MessagingException {
348 MimeMultipart multipart = new MimeMultipart("mixed");
349 multipart.addBodyPart(createPart("Body of part 1", "text/plain",
350 "This is a description"));
351 multipart.addBodyPart(createPart("Body of part 2", "text/plain",
352 "This is another description"));
353 return multipart;
354 }
355
356 private MimeBodyPart createPart(String value, String type,
357 String description) throws MessagingException {
358 MimeBodyPart part = new MimeBodyPart();
359 part.setDescription(description);
360 part.setContent(value, type);
361 return part;
362 }
363 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/MyServiceProxy.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.MediaType;
8
9 @Path("/mime")
10 public interface MyServiceProxy {
11
12 @GET
13 @Produces(MediaType.MULTIPART_FORM_DATA)
14 @MultipartForm
15 NullPartBean createMyBean();
16 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/NullPartBean.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.PartType;
3
4 import javax.ws.rs.FormParam;
5 import javax.ws.rs.core.MediaType;
6 import java.io.InputStream;
7
8 public class NullPartBean {
9 @FormParam("someBinary")
10 @PartType(MediaType.APPLICATION_OCTET_STREAM)
11 private InputStream someBinary;
12
13
14 public InputStream getSomeBinary() {
15 return someBinary;
16 }
17
18 public void setSomeBinary(InputStream someBinary) {
19 this.someBinary = someBinary;
20 }
21 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/NullPartService.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.MediaType;
8
9 @Path("/mime")
10 public class NullPartService {
11
12 @GET
13 @Produces(MediaType.MULTIPART_FORM_DATA)
14 @MultipartForm
15 public NullPartBean createMyBean() {
16 NullPartBean myBean = new NullPartBean();
17 myBean.setSomeBinary(null);
18
19 return myBean;
20 }
21 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ProxyApiService.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("Api")
10 public interface ProxyApiService {
11
12 @Path("test/{key}")
13 @Consumes("multipart/form-data")
14 @POST
15 void postAttachment(@MultipartForm ProxyAttachment attachment, @PathParam("key") String key);
16 }
+0
-34
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ProxyAttachment.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.PartType;
3
4 import javax.ws.rs.FormParam;
5 import javax.ws.rs.HeaderParam;
6
7 public class ProxyAttachment {
8
9 @HeaderParam("X-Atlassian-Token")
10 @PartType("text/plain")
11 private String multipartHeader = "nocheck";
12
13 @FormParam("file")
14 @PartType("text/plain")
15 private byte[] data;
16
17 public String getMultipartHeader() {
18 return multipartHeader;
19 }
20
21 public void setMultipartHeader(String multipartHeader) {
22 this.multipartHeader = multipartHeader;
23 }
24
25 public byte[] getData() {
26 return data;
27 }
28
29 public void setData(byte[] data) {
30 this.data = data;
31 }
32
33 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ProxyResource.java less more
0 package org.jboss.resteasy.test.providers.multipart.resource;
1
2 public class ProxyResource implements ProxyApiService {
3 @Override
4 public void postAttachment(ProxyAttachment attachment, String key) {
5 }
6 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/CollectionDefaultValueTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.basic.resource.CollectionDefaultValueResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.After;
14 import org.junit.Assert;
15 import org.junit.Before;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.core.Response;
20
21 /**
22 * @tpSubChapter Resteasy-client
23 * @tpChapter Integration tests
24 * @tpTestCaseDetails Test that empty QueryParam list is empty
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class CollectionDefaultValueTest {
30 static ResteasyClient client;
31
32 @Deployment
33 public static Archive<?> deploy() {
34 WebArchive war = TestUtil.prepareArchive(CollectionDefaultValueTest.class.getSimpleName());
35 return TestUtil.finishContainerPrepare(war, null, CollectionDefaultValueResource.class);
36 }
37
38 @Before
39 public void init() {
40 client = new ResteasyClientBuilder().build();
41 }
42
43 @After
44 public void after() throws Exception {
45 client.close();
46 }
47
48 private String generateURL(String path) {
49 return PortProviderUtil.generateURL(path, CollectionDefaultValueTest.class.getSimpleName());
50 }
51
52 /**
53 * @tpTestDetails Test that empty QueryParam list is empty
54 * @tpSince RESTEasy 3.0.16
55 */
56 @Test
57 public void testEmpty() throws Exception {
58 Response response = client.target(generateURL("/collection")).request().get();
59 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
60 response.close();
61 }
62 }
+0
-75
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/ConstructedInjectionTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.TestPortProvider;
6 import org.jboss.resteasy.test.resource.basic.resource.ConstructedInjectionResource;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.AfterClass;
13 import org.junit.Assert;
14 import org.junit.BeforeClass;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.client.WebTarget;
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Resource
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class ConstructedInjectionTest {
30
31 static Client client;
32
33 @Deployment
34 public static Archive<?> deploy() {
35 WebArchive war = TestUtil.prepareArchive(ConstructedInjectionTest.class.getSimpleName());
36 war.addClass(TestPortProvider.class);
37 return TestUtil.finishContainerPrepare(war, null, ConstructedInjectionResource.class);
38 }
39
40 @BeforeClass
41 public static void init() {
42 client = ClientBuilder.newClient();
43 }
44
45 @AfterClass
46 public static void after() throws Exception {
47 client.close();
48 }
49
50 private String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, ConstructedInjectionTest.class.getSimpleName());
52 }
53
54 private void _test(String path) {
55 WebTarget base = client.target(generateURL(path));
56 try {
57 Response response = base.request().get();
58 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
59 response.close();
60 } catch (Exception e) {
61 throw new RuntimeException(e);
62 }
63 }
64
65 /**
66 * @tpTestDetails Test with the resource containing custom constructor with @Context and @QueryParam injection
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void testUriInfo() throws Exception {
71 _test("/simple");
72 }
73
74 }
+0
-55
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/CovariantReturnSubresourceLocatorsTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.basic.resource.CovariantReturnSubresourceLocatorsRootProxy;
8 import org.jboss.resteasy.test.resource.basic.resource.CovariantReturnSubresourceLocatorsSubProxy;
9 import org.jboss.resteasy.test.resource.basic.resource.CovariantReturnSubresourceLocatorsSubProxyRootImpl;
10 import org.jboss.resteasy.test.resource.basic.resource.CovariantReturnSubresourceLocatorsSubProxySubImpl;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.Assert;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Resources
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Test return value of covariant with locators.
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class CovariantReturnSubresourceLocatorsTest {
31
32 @Deployment
33 public static Archive<?> deployUriInfoSimpleResource() {
34 WebArchive war = TestUtil.prepareArchive(CovariantReturnSubresourceLocatorsTest.class.getSimpleName());
35 war.addClasses(CovariantReturnSubresourceLocatorsRootProxy.class, CovariantReturnSubresourceLocatorsSubProxy.class);
36 return TestUtil.finishContainerPrepare(war, null, CovariantReturnSubresourceLocatorsSubProxyRootImpl.class,
37 CovariantReturnSubresourceLocatorsSubProxySubImpl.class);
38 }
39
40 /**
41 * @tpTestDetails Test basic path
42 * @tpSince RESTEasy 3.0.16
43 */
44 @Test
45 public void basicTest() {
46 ResteasyClient client = new ResteasyClientBuilder().build();
47 Response response = client.target(PortProviderUtil.generateURL("/path/sub/xyz",
48 CovariantReturnSubresourceLocatorsTest.class.getSimpleName())).request().get();
49 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
50 Assert.assertEquals("Wrong content of response", "Boo! - xyz", response.readEntity(String.class));
51 response.close();
52 client.close();
53 }
54 }
+0
-204
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/DefaultMediaTypeTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.category.ExpectedFailing;
7 import org.jboss.resteasy.category.NotForForwardCompatibility;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
9 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
10 import org.jboss.resteasy.test.resource.basic.resource.DefaultMediaTypeCustomObject;
11 import org.jboss.resteasy.test.resource.basic.resource.DefaultMediaTypeResource;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.After;
18 import org.junit.Assert;
19 import org.junit.Before;
20 import org.junit.Test;
21 import org.junit.experimental.categories.Category;
22 import org.junit.runner.RunWith;
23
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.client.WebTarget;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.Response;
28 import java.io.ByteArrayOutputStream;
29
30 /**
31 * @tpSubChapter Resources
32 * @tpChapter Integration tests
33 * @tpTestCaseDetails Regression test for JBEAP-2847. DefaultTextPlain should be used, if produce annotation annotation is not used in end-point.
34 * @tpSince RESTEasy 3.0.16
35 */
36 @RunWith(Arquillian.class)
37 @RunAsClient
38 public class DefaultMediaTypeTest {
39
40 protected final Logger logger = Logger.getLogger(DefaultMediaTypeResource.class.getName());
41
42 static ResteasyClient client;
43
44 @Deployment
45 public static Archive<?> deploy() {
46 WebArchive war = TestUtil.prepareArchive(DefaultMediaTypeResource.class.getSimpleName());
47 war.addClass(DefaultMediaTypeCustomObject.class);
48 return TestUtil.finishContainerPrepare(war, null, DefaultMediaTypeResource.class);
49 }
50
51 @Before
52 public void init() {
53 client = new ResteasyClientBuilder().build();
54 }
55
56 @After
57 public void after() throws Exception {
58 client.close();
59 client = null;
60 }
61
62 private String generateURL(String path) {
63 return PortProviderUtil.generateURL(path, DefaultMediaTypeResource.class.getSimpleName());
64 }
65
66 /**
67 * @tpTestDetails Test Date object with produce annotation
68 * @tpSince RESTEasy 3.0.16
69 */
70 @Test
71 public void postDateProduce() throws Exception {
72 WebTarget target = client.target(generateURL("/postDateProduce"));
73 ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
74 for (int i = 0; i < 5000; i++) {
75 baos.write(i);
76 }
77 Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM));
78 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
79 String responseContent = response.readEntity(String.class);
80 logger.info(String.format("Response: %s", responseContent));
81 }
82
83 /**
84 * @tpTestDetails Test Date object without produce annotation
85 * @tpSince RESTEasy 3.0.16
86 */
87 @Test
88 @Category({ ExpectedFailing.class, NotForForwardCompatibility.class })
89 public void postDate() throws Exception {
90 WebTarget target = client.target(generateURL("/postDate"));
91 ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
92 for (int i = 0; i < 5000; i++) {
93 baos.write(i);
94 }
95 Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM));
96 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-4725"), HttpResponseCodes.SC_OK, response.getStatus());
97 String responseContent = response.readEntity(String.class);
98 logger.info(String.format("Response: %s", responseContent));
99 }
100
101 /**
102 * @tpTestDetails Test Foo object with produce annotation
103 * @tpSince RESTEasy 3.0.16
104 */
105 @Test
106 public void postFooProduce() throws Exception {
107 WebTarget target = client.target(generateURL("/postFooProduce"));
108 ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
109 for (int i = 0; i < 5000; i++) {
110 baos.write(i);
111 }
112 Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM));
113 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
114 String responseContent = response.readEntity(String.class);
115 logger.info(String.format("Response: %s", responseContent));
116 }
117
118 /**
119 * @tpTestDetails Test Foo object without produce annotation
120 * @tpSince RESTEasy 3.0.16
121 */
122 @Test
123 @Category({ ExpectedFailing.class, NotForForwardCompatibility.class })
124 public void postFoo() throws Exception {
125 WebTarget target = client.target(generateURL("/postFoo"));
126 ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
127 for (int i = 0; i < 5000; i++) {
128 baos.write(i);
129 }
130 Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM));
131 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-4725"), HttpResponseCodes.SC_OK, response.getStatus());
132 String responseContent = response.readEntity(String.class);
133 logger.info(String.format("Response: %s", responseContent));
134 }
135
136 /**
137 * @tpTestDetails Test int primitive with produce annotation
138 * @tpSince RESTEasy 3.0.16
139 */
140 @Test
141 public void postIntProduce() throws Exception {
142 WebTarget target = client.target(generateURL("/postIntProduce"));
143 ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
144 for (int i = 0; i < 5000; i++) {
145 baos.write(i);
146 }
147 Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM));
148 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
149 String responseContent = response.readEntity(String.class);
150 logger.info(String.format("Response: %s", responseContent));
151 }
152
153 /**
154 * @tpTestDetails Test int primitive without produce annotation
155 * @tpSince RESTEasy 3.0.16
156 */
157 @Test
158 public void postInt() throws Exception {
159 WebTarget target = client.target(generateURL("/postInt"));
160 ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
161 for (int i = 0; i < 5000; i++) {
162 baos.write(i);
163 }
164 Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM));
165 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-2847"), HttpResponseCodes.SC_OK, response.getStatus());
166 String responseContent = response.readEntity(String.class);
167 logger.info(String.format("Response: %s", responseContent));
168 }
169
170 /**
171 * @tpTestDetails Test Integer object with produce annotation
172 * @tpSince RESTEasy 3.0.16
173 */
174 @Test
175 public void postIntegerProduce() throws Exception {
176 WebTarget target = client.target(generateURL("/postIntegerProduce"));
177 ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
178 for (int i = 0; i < 5000; i++) {
179 baos.write(i);
180 }
181 Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM));
182 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
183 String responseContent = response.readEntity(String.class);
184 logger.info(String.format("Response: %s", responseContent));
185 }
186
187 /**
188 * @tpTestDetails Test Integer object without produce annotation
189 * @tpSince RESTEasy 3.0.16
190 */
191 @Test
192 public void postInteger() throws Exception {
193 WebTarget target = client.target(generateURL("/postInteger"));
194 ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
195 for (int i = 0; i < 5000; i++) {
196 baos.write(i);
197 }
198 Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM));
199 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-2847"), HttpResponseCodes.SC_OK, response.getStatus());
200 String responseContent = response.readEntity(String.class);
201 logger.info(String.format("Response: %s", responseContent));
202 }
203 }
+0
-87
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/ExtensionTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.resource.basic.resource.ExtensionResource;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.PortProviderUtil;
8 import org.jboss.resteasy.utils.TestUtil;
9 import org.jboss.shrinkwrap.api.Archive;
10 import org.jboss.shrinkwrap.api.spec.WebArchive;
11 import org.junit.AfterClass;
12 import org.junit.Assert;
13 import org.junit.BeforeClass;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.core.Response;
20 import java.util.HashMap;
21 import java.util.Map;
22
23 /**
24 * @tpSubChapter Resource
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Test for resteasy.media.type.mappings and resteasy.language.mappings parameters
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class ExtensionTest {
32
33 static Client client;
34
35 @Deployment
36 public static Archive<?> deploy() {
37 WebArchive war = TestUtil.prepareArchive(ExtensionTest.class.getSimpleName());
38
39 Map<String, String> params = new HashMap<>();
40 params.put("resteasy.media.type.mappings", "xml : application/xml, html : text/html, txt : text/plain");
41 params.put("resteasy.language.mappings", "en : en-US");
42 return TestUtil.finishContainerPrepare(war, params, ExtensionResource.class);
43 }
44
45 @BeforeClass
46 public static void init() {
47 client = ClientBuilder.newClient();
48 }
49
50 @AfterClass
51 public static void after() throws Exception {
52 client.close();
53 }
54
55 /**
56 * @tpTestDetails Check correct values
57 * @tpSince RESTEasy 3.0.16
58 */
59 @Test
60 public void testIt() {
61 basicTest("/extension.xml", "xml");
62 basicTest("/extension.html.en", "html");
63 basicTest("/extension.en.html", "html");
64 basicTest("/extension/stuff.old.en.txt", "plain");
65 basicTest("/extension/stuff.en.old.txt", "plain");
66 basicTest("/extension/stuff.en.txt.old", "plain");
67 }
68
69 /**
70 * @tpTestDetails Check wrong value
71 * @tpSince RESTEasy 3.0.16
72 */
73 @Test
74 public void testError() {
75 Response response = client.target(PortProviderUtil.generateURL("/extension.junk", ExtensionTest.class.getSimpleName())).request().get();
76 Assert.assertEquals(HttpResponseCodes.SC_NOT_FOUND, response.getStatus());
77 response.close();
78 }
79
80 private void basicTest(String path, String body) {
81 Response response = client.target(PortProviderUtil.generateURL(path, ExtensionTest.class.getSimpleName())).request().get();
82 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
83 Assert.assertEquals("Wrong content of response", body, response.readEntity(String.class));
84 response.close();
85 }
86 }
+0
-92
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/GenericEntityTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.resource.basic.resource.GenericEntityDoubleWriter;
6 import org.jboss.resteasy.test.resource.basic.resource.GenericEntityResource;
7 import org.jboss.resteasy.test.resource.basic.resource.GenericEntitytFloatWriter;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.Assert;
15 import org.junit.BeforeClass;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Client;
20 import javax.ws.rs.client.ClientBuilder;
21 import javax.ws.rs.client.WebTarget;
22 import javax.ws.rs.core.Response;
23
24 /**
25 * @tpSubChapter Resource
26 * @tpChapter Integration tests
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class GenericEntityTest {
32
33 static Client client;
34
35 @Deployment
36 public static Archive<?> deploy() {
37 WebArchive war = TestUtil.prepareArchive(GenericEntityTest.class.getSimpleName());
38 return TestUtil.finishContainerPrepare(war, null, GenericEntityResource.class, GenericEntityDoubleWriter.class,
39 GenericEntitytFloatWriter.class);
40 }
41
42 @BeforeClass
43 public static void init() {
44 client = ClientBuilder.newClient();
45 }
46
47 @AfterClass
48 public static void after() throws Exception {
49 client.close();
50 client = null;
51 }
52
53 private String generateURL(String path) {
54 return PortProviderUtil.generateURL(path, GenericEntityTest.class.getSimpleName());
55 }
56
57 /**
58 * @tpTestDetails Resource returning GenericEntity with custom MessageBodyWriter returning double values
59 * @tpSince RESTEasy 3.0.16
60 */
61 @Test
62 public void testDoubles() {
63 WebTarget base = client.target(generateURL("/doubles"));
64 try {
65 Response response = base.request().get();
66 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
67 String body = response.readEntity(String.class);
68 Assert.assertEquals("The response doesn't contain the expected entity", "45.0D 50.0D ", body);
69 } catch (Exception e) {
70 throw new RuntimeException(e);
71 }
72 }
73
74 /**
75 * @tpTestDetails Resource returning GenericEntity with custom MessageBodyWriter returning float values
76 * @tpSince RESTEasy 3.0.16
77 */
78 @Test
79 public void testFloats() {
80 WebTarget base = client.target(generateURL("/floats"));
81 try {
82 Response response = base.request().get();
83 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
84 String body = response.readEntity(String.class);
85 Assert.assertEquals("The response doesn't contain the expected entity", "45.0F 50.0F ", body);
86 } catch (Exception e) {
87 throw new RuntimeException(e);
88 }
89 }
90
91 }
+0
-67
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/GenericResourceTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import javax.ws.rs.client.ClientBuilder;
3
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.test.resource.basic.resource.GenericResourceCrudResource;
9 import org.jboss.resteasy.test.resource.basic.resource.GenericResourceStudent;
10 import org.jboss.resteasy.test.resource.basic.resource.GenericResourceStudentCrudResource;
11 import org.jboss.resteasy.test.resource.basic.resource.GenericResourceStudentInterface;
12 import org.jboss.resteasy.test.resource.basic.resource.GenericResourceStudentReader;
13 import org.jboss.resteasy.test.resource.basic.resource.GenericResourceStudentWriter;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Assert;
19 import org.junit.BeforeClass;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 /**
24 * @tpSubChapter Resource
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Tests generic resource class
27 * @tpSince RESTEasy 3.0.20
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class GenericResourceTest {
32
33 private static GenericResourceStudentInterface proxy;
34
35 @BeforeClass
36 public static void setup() {
37 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target(generateURL(""));
38 proxy = target.register(GenericResourceStudentReader.class).register(GenericResourceStudentWriter.class).proxy(GenericResourceStudentInterface.class);
39 }
40
41 @Deployment
42 public static Archive<?> deploy() {
43 WebArchive war = TestUtil.prepareArchive(GenericResourceTest.class.getSimpleName());
44 war.addClass(GenericResourceStudent.class);
45 war.addClass(GenericResourceStudentInterface.class);
46 war.addClass(GenericResourceCrudResource.class);
47 return TestUtil.finishContainerPrepare(war, null, GenericResourceStudentCrudResource.class, GenericResourceStudentReader.class, GenericResourceStudentWriter.class);
48 }
49
50 private static String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, GenericResourceTest.class.getSimpleName());
52 }
53
54 @Test
55 public void testGet()
56 {
57 Assert.assertTrue(proxy.get(1).getName().equals("Jozef Hartinger"));
58 }
59
60 @Test
61 public void testPut()
62 {
63 proxy.put(2, new GenericResourceStudent("John Doe"));
64 Assert.assertTrue(proxy.get(2).getName().equals("John Doe"));
65 }
66 }
+0
-82
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/HttpHeadersTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.basic.resource.HttpHeadersResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.Assert;
15 import org.junit.BeforeClass;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.core.Response;
20
21 /**
22 * @tpSubChapter Resources
23 * @tpChapter Integration tests
24 * @tpTestCaseDetails Spec requires that HEAD and OPTIONS are handled in a default manner
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class HttpHeadersTest {
30
31
32 static ResteasyClient client;
33
34 @Deployment
35 public static Archive<?> deploy() throws Exception {
36 WebArchive war = TestUtil.prepareArchive(HttpHeadersTest.class.getSimpleName());
37 return TestUtil.finishContainerPrepare(war, null, HttpHeadersResource.class);
38 }
39
40 @BeforeClass
41 public static void init() {
42 client = new ResteasyClientBuilder().build();
43 }
44
45 @AfterClass
46 public static void close() {
47 client.close();
48 }
49
50 private static String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, HttpHeadersTest.class.getSimpleName());
52 }
53
54 /**
55 * @tpTestDetails Client invokes GET request on a sub resource at /HeadersTest/sub2
56 * with Accept MediaType and Content-Type Headers set;
57 * Verify that HttpHeaders got the property set by the request
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void RequestHeadersTest() throws Exception {
62 String errorMessage = "Wrong content of response";
63 Response response = client.target(generateURL("/HeadersTest/headers")).request()
64 .header("Accept", "text/plain, text/html, text/html;level=1, */*")
65 .header("Content-Type", "application/xml;charset=utf8")
66 .get();
67 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
68 String content = response.readEntity(String.class);
69
70 Assert.assertTrue(errorMessage, -1 < content.indexOf("Accept:"));
71 Assert.assertTrue(errorMessage, -1 < content.indexOf("Content-Type:"));
72 Assert.assertTrue(errorMessage, -1 < content.indexOf("application/xml"));
73 Assert.assertTrue(errorMessage, -1 < content.indexOf("charset=utf8"));
74 Assert.assertTrue(errorMessage, -1 < content.indexOf("text/html"));
75 Assert.assertTrue(errorMessage, -1 < content.indexOf("*/*"));
76
77 response.close();
78 }
79
80
81 }
+0
-66
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/InheritanceTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import javax.ws.rs.client.Client;
3 import javax.ws.rs.client.ClientBuilder;
4 import javax.ws.rs.client.Invocation.Builder;
5 import javax.ws.rs.core.Response;
6
7 import org.jboss.arquillian.container.test.api.Deployment;
8 import org.jboss.arquillian.container.test.api.RunAsClient;
9 import org.jboss.arquillian.junit.Arquillian;
10 import org.jboss.resteasy.test.TestPortProvider;
11 import org.jboss.resteasy.test.resource.basic.resource.InheritenceParentResource;
12 import org.jboss.resteasy.test.resource.basic.resource.InheritenceParentResourceImpl;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.AfterClass;
19 import org.junit.Assert;
20 import org.junit.BeforeClass;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24 /**
25 * @tpSubChapter Resource
26 * @tpChapter Integration tests
27 * @tpTestCaseDetails Tests annotation inheritence from interface.
28 * @tpSince RESTEasy 3.0.20
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class InheritanceTest
33 {
34 private static Client client;
35
36 @Deployment
37 public static Archive<?> deploy() {
38 WebArchive war = TestUtil.prepareArchive(InheritanceTest.class.getSimpleName());
39 war.addClass(InheritenceParentResource.class);
40 return TestUtil.finishContainerPrepare(war, null, InheritenceParentResourceImpl.class);
41 }
42
43 private String generateURL(String path) {
44 return PortProviderUtil.generateURL(path, InheritanceTest.class.getSimpleName());
45 }
46
47 @BeforeClass
48 public static void beforeSub() {
49 client = ClientBuilder.newClient();
50 }
51
52 @AfterClass
53 public static void afterSub() {
54 client.close();
55 }
56
57 @Test
58 public void Test1() throws Exception {
59 Builder builder = client.target(generateURL("/InheritanceTest")).request();
60 builder.header("Accept", "text/plain");
61 Response response = builder.get();
62 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
63 Assert.assertEquals("First", response.readEntity(String.class));
64 }
65 }
+0
-112
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/MatchedResourceTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.basic.resource.MatchedResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.Assert;
15 import org.junit.BeforeClass;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Entity;
20 import javax.ws.rs.client.WebTarget;
21 import javax.ws.rs.core.Response;
22
23 import static org.hamcrest.CoreMatchers.is;
24
25
26 /**
27 * @tpSubChapter Resources
28 * @tpChapter Integration tests
29 * @tpTestCaseDetails Regression tests for RESTEASY-549 and RESTEASY-537
30 * @tpSince RESTEasy 3.0.16
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class MatchedResourceTest {
35
36 static ResteasyClient client;
37
38 @Deployment
39 public static Archive<?> deploy() throws Exception {
40 WebArchive war = TestUtil.prepareArchive(MatchedResourceTest.class.getSimpleName());
41 return TestUtil.finishContainerPrepare(war, null, MatchedResource.class);
42 }
43
44 @BeforeClass
45 public static void init() {
46 client = new ResteasyClientBuilder().build();
47 }
48
49 @AfterClass
50 public static void close() {
51 client.close();
52 }
53
54 private static String generateURL(String path) {
55 return PortProviderUtil.generateURL(path, MatchedResourceTest.class.getSimpleName());
56 }
57
58 /**
59 * @tpTestDetails Regression test for RESTEASY-549
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void testEmpty() throws Exception {
64 WebTarget base = client.target(generateURL("/start"));
65 Response response = base.request().post(Entity.text(""));
66 Assert.assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK));
67 String rtn = response.readEntity(String.class);
68 Assert.assertEquals("started", rtn);
69 response.close();
70
71 base = client.target(generateURL("/start"));
72 response = base.request().post(Entity.entity("<xml/>", "application/xml"));
73 Assert.assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK));
74 rtn = response.readEntity(String.class);
75 Assert.assertEquals("Wrong response content", rtn, "<xml/>");
76 response.close();
77 }
78
79 /**
80 * @tpTestDetails Regression test for RESTEASY-537
81 * @tpSince RESTEasy 3.0.16
82 */
83 @Test
84 public void testMatch() throws Exception {
85 WebTarget base = client.target(generateURL("/match"));
86 Response response = base.request().header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
87 .get();
88 Assert.assertEquals("text/html;charset=UTF-8", response.getHeaders().getFirst("Content-Type"));
89 String res = response.readEntity(String.class);
90 Assert.assertEquals("Wrong response content", "*/*", res);
91 response.close();
92 }
93
94 public void generalPostTest(String uri, String value) {
95 WebTarget base = client.target(uri);
96 Response response = base.request().get();
97 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
98 Assert.assertEquals("Wrong response content", response.readEntity(String.class), value);
99 }
100
101 /**
102 * @tpTestDetails Check post request on resource with @GET annotation
103 * @tpSince RESTEasy 3.0.16
104 */
105 @Test
106 public void testPost() {
107 generalPostTest(generateURL("/test1/foo.xml.en"), "complex");
108 generalPostTest(generateURL("/test2/foo.xml.en"), "complex2");
109 }
110
111 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/MultiInterfaceResLocatorTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
6 import org.jboss.resteasy.test.resource.basic.resource.MultiInterfaceResLocatorIntf1;
7 import org.jboss.resteasy.test.resource.basic.resource.MultiInterfaceResLocatorIntf2;
8 import org.jboss.resteasy.test.resource.basic.resource.MultiInterfaceResLocatorResource;
9 import org.jboss.resteasy.test.resource.basic.resource.MultiInterfaceResLocatorSubresource;
10 import org.jboss.resteasy.util.HttpResponseCodes;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Client;
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Resources
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class MultiInterfaceResLocatorTest {
30
31 @Deployment
32 public static Archive<?> deploy() {
33 WebArchive war = TestUtil.prepareArchive(MultiInterfaceResLocatorTest.class.getSimpleName());
34 war.addClass(MultiInterfaceResLocatorIntf1.class);
35 war.addClass(MultiInterfaceResLocatorIntf2.class);
36 return TestUtil.finishContainerPrepare(war, null, MultiInterfaceResLocatorResource.class, MultiInterfaceResLocatorSubresource.class);
37 }
38
39 private String generateURL(String path) {
40 return PortProviderUtil.generateURL(path, MultiInterfaceResLocatorTest.class.getSimpleName());
41 }
42
43 /**
44 * @tpTestDetails Test for resource with more interfaces.
45 * @tpSince RESTEasy 3.0.16
46 */
47 @Test
48 public void test() throws Exception {
49 Client client = new ResteasyClientBuilder().build();
50 Response response = client.target(generateURL("/test/hello1/")).request().get();
51 String entity = response.readEntity(String.class);
52 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
53 Assert.assertEquals("Wrong content of response", "resourceMethod1", entity);
54
55 response = client.target(generateURL("/test/hello2/")).request().get();
56 entity = response.readEntity(String.class);
57 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
58 Assert.assertEquals("Wrong content of response", "resourceMethod2", entity);
59 }
60 }
+0
-125
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/MultipleAcceptHeaderTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.client.ClientBuilder;
6
7 import org.jboss.arquillian.container.test.api.Deployment;
8 import org.jboss.arquillian.container.test.api.RunAsClient;
9 import org.jboss.arquillian.junit.Arquillian;
10 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 @RunWith(Arquillian.class)
21 @RunAsClient
22 public class MultipleAcceptHeaderTest
23 {
24
25 protected static String APPLICATION_JSON = "Content-Type: application/json";
26
27 protected static String APPLICATION_XML = "Content-Type: application/xml";
28
29 private TestInterfaceClient service;
30
31 @Deployment
32 public static Archive<?> deploy() throws Exception
33 {
34 WebArchive war = TestUtil.prepareArchive(MultipleAcceptHeaderTest.class.getSimpleName());
35 return TestUtil.finishContainerPrepare(war, null, TestResourceServer.class);
36 }
37
38 private String generateBaseUrl()
39 {
40 return PortProviderUtil.generateBaseUrl(MultipleAcceptHeaderTest.class.getSimpleName());
41 }
42
43 @Path("/test")
44 static public class TestResourceServer
45 {
46 @GET
47 @Path("accept")
48 @Produces("application/json")
49 public String acceptJson()
50 {
51 return APPLICATION_JSON;
52 }
53
54 @GET
55 @Path("accept")
56 @Produces(
57 {"application/xml", "text/plain"})
58 public String acceptXml()
59 {
60 return APPLICATION_XML;
61 }
62 }
63
64 @Path("test")
65 interface TestInterfaceClient
66 {
67 @GET
68 @Path("accept")
69 @Produces("application/json")
70 public String getJson();
71
72 @GET
73 @Path("accept")
74 @Produces("application/xml")
75 public String getXml();
76
77 @GET
78 @Path("accept")
79 @Produces(
80 {"application/wrong1", "application/wrong2", "application/xml"})
81 public String getXmlMultiple();
82
83 @GET
84 @Path("accept")
85 @Produces(
86 {"application/wrong1", "text/plain"})
87 public String getXmlPlainMultiple();
88 }
89
90 @Before
91 public void setUp() throws Exception
92 {
93 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target(generateBaseUrl());
94 service = target.proxy(TestInterfaceClient.class);
95 }
96
97 @Test
98 public void testSingleAcceptHeader() throws Exception
99 {
100 String result = service.getJson();
101 Assert.assertEquals(APPLICATION_JSON, result);
102 }
103
104 @Test
105 public void testSingleAcceptHeader2() throws Exception
106 {
107 String result = service.getXml();
108 Assert.assertEquals(APPLICATION_XML, result);
109 }
110
111 @Test
112 public void testMultipleAcceptHeader() throws Exception
113 {
114 String result = service.getXmlMultiple();
115 Assert.assertEquals(APPLICATION_XML, result);
116 }
117
118 @Test
119 public void testMultipleAcceptHeaderSecondHeader() throws Exception
120 {
121 String result = service.getXmlPlainMultiple();
122 Assert.assertEquals(APPLICATION_XML, result);
123 }
124 }
+0
-87
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/MultipleEndpointsWarningTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import javax.ws.rs.client.Client;
3 import javax.ws.rs.client.ClientBuilder;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.Response;
6
7 import org.jboss.arquillian.container.test.api.Deployment;
8 import org.jboss.arquillian.container.test.api.RunAsClient;
9 import org.jboss.arquillian.junit.Arquillian;
10 import org.jboss.resteasy.test.resource.basic.resource.LogHandler;
11 import org.jboss.resteasy.test.resource.basic.resource.MultipleEndpointsWarningResource;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.AfterClass;
17 import org.junit.Assert;
18 import org.junit.BeforeClass;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 /**
23 * @tpSubChapter Resources
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Regression tests for RESTEASY-1398
26 * @tpSince RESTEasy 3.0.20
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class MultipleEndpointsWarningTest
31 {
32 private static Client client;
33
34 @Deployment
35 public static Archive<?> deploy() {
36 WebArchive war = TestUtil.prepareArchive(MultipleEndpointsWarningTest.class.getSimpleName());
37 war.addClass(LogHandler.class);
38 return TestUtil.finishContainerPrepare(war, null, MultipleEndpointsWarningResource.class);
39 }
40
41 private static String generateURL(String path) {
42 return PortProviderUtil.generateURL(path, MultipleEndpointsWarningTest.class.getSimpleName());
43 }
44
45 @BeforeClass
46 public static void setUp() throws Exception {
47 client = ClientBuilder.newClient();
48 client.target(generateURL("/setup")).request().get();
49 }
50
51 @AfterClass
52 public static void tearDown() {
53 client.target(generateURL("/teardown")).request().get();
54 client.close();
55 }
56
57 @Test
58 public void testUnique() throws Exception {
59 Response response = client.target(generateURL("/unique/")).request().accept(MediaType.TEXT_PLAIN).get();
60 Assert.assertEquals("Incorrectly logged " + LogHandler.MESSAGE_CODE, new Long(0), response.readEntity(long.class));
61
62 response = client.target(generateURL("/unique")).request().get();
63 Assert.assertEquals("Incorrectly logged " + LogHandler.MESSAGE_CODE, new Long(0), response.readEntity(long.class));
64
65 response = client.target(generateURL("/unique")).request().accept(MediaType.TEXT_PLAIN).get();
66 Assert.assertEquals("Incorrectly logged " + LogHandler.MESSAGE_CODE, new Long(0), response.readEntity(long.class));
67 }
68
69 @Test
70 public void testDifferentVerbs() throws Exception {
71 Response response = client.target(generateURL("/verbs")).request().accept(MediaType.TEXT_PLAIN).get();
72 Assert.assertEquals("Incorrectly logged " + LogHandler.MESSAGE_CODE, new Long(0), response.readEntity(long.class));
73
74 response = client.target(generateURL("/verbs")).request().accept(MediaType.TEXT_PLAIN, MediaType.WILDCARD).get();
75 Assert.assertEquals("Incorrectly logged " + LogHandler.MESSAGE_CODE, new Long(0), response.readEntity(long.class));
76
77 response = client.target(generateURL("/verbs")).request().get();
78 Assert.assertEquals("Incorrectly logged " + LogHandler.MESSAGE_CODE, new Long(0), response.readEntity(long.class));
79 }
80
81 @Test
82 public void testDuplicate() throws Exception {
83 Response response = client.target(generateURL("/duplicate")).request().get();
84 Assert.assertEquals(LogHandler.MESSAGE_CODE + " should've been logged once", new Long(1), response.readEntity(long.class));
85 }
86 }
+0
-104
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/ParameterSubResTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
6 import org.jboss.resteasy.test.resource.basic.resource.MultiInterfaceResLocatorResource;
7 import org.jboss.resteasy.test.resource.basic.resource.MultiInterfaceResLocatorSubresource;
8 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResConcreteSubImpl;
9 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResDoubleInterface;
10 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResGenericInterface;
11 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResGenericSub;
12 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResInternalInterface;
13 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResRoot;
14 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResRootImpl;
15 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResSub;
16 import org.jboss.resteasy.test.resource.basic.resource.ParameterSubResSubImpl;
17 import org.jboss.resteasy.util.HttpResponseCodes;
18 import org.jboss.resteasy.util.Types;
19 import org.jboss.resteasy.utils.PortProviderUtil;
20 import org.jboss.resteasy.utils.TestUtil;
21 import org.jboss.shrinkwrap.api.Archive;
22 import org.jboss.shrinkwrap.api.spec.WebArchive;
23 import org.junit.After;
24 import org.junit.Assert;
25 import org.junit.Before;
26 import org.junit.Test;
27 import org.junit.runner.RunWith;
28
29 import javax.ws.rs.client.Client;
30 import javax.ws.rs.core.Response;
31
32 /**
33 * @tpSubChapter Resources
34 * @tpChapter Integration tests
35 * @tpTestCaseDetails Test resources with sub-resources with parameters.
36 * @tpSince RESTEasy 3.0.16
37 */
38 @RunWith(Arquillian.class)
39 @RunAsClient
40 public class ParameterSubResTest {
41
42 static Client client;
43
44 @Deployment
45 public static Archive<?> deploy() {
46 WebArchive war = TestUtil.prepareArchive(ParameterSubResTest.class.getSimpleName());
47 war.addClass(MultiInterfaceResLocatorResource.class);
48 war.addClass(MultiInterfaceResLocatorSubresource.class);
49 war.addClass(ParameterSubResConcreteSubImpl.class);
50 war.addClass(ParameterSubResDoubleInterface.class);
51 war.addClass(ParameterSubResGenericInterface.class);
52 war.addClass(ParameterSubResInternalInterface.class);
53 war.addClass(ParameterSubResRoot.class);
54 war.addClass(ParameterSubResSub.class);
55 war.addClass(ParameterSubResSubImpl.class);
56 return TestUtil.finishContainerPrepare(war, null, ParameterSubResRootImpl.class, ParameterSubResGenericSub.class);
57 }
58
59 private String generateURL(String path) {
60 return PortProviderUtil.generateURL(path, ParameterSubResTest.class.getSimpleName());
61 }
62
63 @Before
64 public void init() {
65 client = new ResteasyClientBuilder().build();
66 }
67
68 @After
69 public void after() throws Exception {
70 client.close();
71 }
72
73 /**
74 * @tpTestDetails Check types of parameter.
75 * @tpSince RESTEasy 3.0.16
76 */
77 @Test
78 public void testParametized() throws Exception {
79 Types.findParameterizedTypes(ParameterSubResConcreteSubImpl.class, ParameterSubResInternalInterface.class);
80 }
81
82 /**
83 * @tpTestDetails Check sub resources.
84 * @tpSince RESTEasy 3.0.16
85 */
86 @Test
87 public void testSubResource() throws Exception {
88 Response response = client.target(generateURL("/path/sub/fred")).request().get();
89 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
90 Assert.assertEquals("Wrong content of response", "Boo! - fred", response.readEntity(String.class));
91 }
92
93 /**
94 * @tpTestDetails Check root resource.
95 * @tpSince RESTEasy 3.0.16
96 */
97 @Test
98 public void testRoot() throws Exception {
99 Response response = client.target(generateURL("/generic/sub")).queryParam("foo", "42.0").request().get();
100 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
101 Assert.assertEquals("Wrong content of response", "42.0", response.readEntity(String.class));
102 }
103 }
+0
-68
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/ReponseInfoTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.resource.basic.resource.ReponseInfoResource;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.PortProviderUtil;
8 import org.jboss.resteasy.utils.TestUtil;
9 import org.jboss.shrinkwrap.api.Archive;
10 import org.jboss.shrinkwrap.api.spec.WebArchive;
11 import org.junit.AfterClass;
12 import org.junit.Assert;
13 import org.junit.BeforeClass;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.client.WebTarget;
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Resource
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class ReponseInfoTest {
30
31 static Client client;
32
33 @BeforeClass
34 public static void before() throws Exception {
35 client = ClientBuilder.newClient();
36 }
37
38 @AfterClass
39 public static void close() {
40 client.close();
41 }
42
43 @Deployment
44 public static Archive<?> deploy() {
45 WebArchive war = TestUtil.prepareArchive(ReponseInfoTest.class.getSimpleName());
46 war.addClasses(PortProviderUtil.class, ReponseInfoTest.class);
47 return TestUtil.finishContainerPrepare(war, null, ReponseInfoResource.class);
48 }
49
50 private void basicTest(String path) {
51 WebTarget base = client.target(PortProviderUtil.generateURL(path, ReponseInfoTest.class.getSimpleName()));
52
53 Response response = base.request().get();
54
55 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
56 response.close();
57 }
58
59 /**
60 * @tpTestDetails Check URI location from HTTP headers from response prepared in resource
61 * @tpSince RESTEasy 3.0.16
62 */
63 @Test
64 public void testUriInfo() throws Exception {
65 basicTest("/simple");
66 }
67 }
+0
-86
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/ResourceInfoInjectionTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.category.NotForForwardCompatibility;
6 import org.jboss.resteasy.test.resource.basic.resource.ResourceInfoInjectionFilter;
7 import org.jboss.resteasy.test.resource.basic.resource.ResourceInfoInjectionResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.Assert;
15 import org.junit.BeforeClass;
16 import org.junit.Test;
17 import org.junit.experimental.categories.Category;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.client.Client;
21 import javax.ws.rs.client.ClientBuilder;
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.client.WebTarget;
24 import javax.ws.rs.core.Response;
25
26 /**
27 * @tpSubChapter Resources
28 * @tpChapter Integration tests
29 * @tpTestCaseDetails Regression test for JBEAP-4701
30 * @tpSince RESTEasy 3.0.17
31 */
32 @RunWith(Arquillian.class)
33 @RunAsClient
34 public class ResourceInfoInjectionTest {
35 protected static Client client;
36
37 @BeforeClass
38 public static void init() {
39 client = ClientBuilder.newClient();
40 }
41
42 @AfterClass
43 public static void close() {
44 client.close();
45 }
46
47 private static String generateURL(String path) {
48 return PortProviderUtil.generateURL(path, ResourceInfoInjectionTest.class.getSimpleName());
49 }
50
51 @Deployment
52 public static Archive<?> deployUriInfoSimpleResource() {
53 WebArchive war = TestUtil.prepareArchive(ResourceInfoInjectionTest.class.getSimpleName());
54 return TestUtil.finishContainerPrepare(war, null, ResourceInfoInjectionFilter.class,
55 ResourceInfoInjectionResource.class);
56 }
57
58 /**
59 * @tpTestDetails Check for injecting ResourceInfo object in ContainerResponseFilter
60 * @tpSince RESTEasy 3.0.17
61 */
62 @Test
63 @Category({NotForForwardCompatibility.class})
64 public void testNotFound() throws Exception {
65 WebTarget target = client.target(generateURL("/bogus"));
66 Response response = target.request().get();
67 String entity = response.readEntity(String.class);
68 Assert.assertEquals("ResponseFilter was probably not applied to response", HttpResponseCodes.SC_NOT_FOUND * 2, response.getStatus());
69 Assert.assertEquals("Wrong body of response", "", entity);
70 }
71
72 /**
73 * @tpTestDetails Check for injecting ResourceInfo object in end-point
74 * @tpSince RESTEasy 3.0.17
75 */
76 @Test
77 @Category({NotForForwardCompatibility.class})
78 public void testAsync() throws Exception {
79 WebTarget target = client.target(generateURL("/async"));
80 Response response = target.request().post(Entity.entity("hello", "text/plain"));
81 String val = response.readEntity(String.class);
82 Assert.assertEquals("OK status is expected", HttpResponseCodes.SC_OK, response.getStatus());
83 Assert.assertEquals("Wrong body of response", "async", val);
84 }
85 }
+0
-157
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/ResourceLocatorTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import javax.servlet.http.HttpServletResponse;
3 import javax.ws.rs.client.Client;
4 import javax.ws.rs.client.ClientBuilder;
5 import javax.ws.rs.client.Entity;
6 import javax.ws.rs.client.Invocation.Builder;
7 import javax.ws.rs.client.WebTarget;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Response;
10
11 import org.jboss.arquillian.container.test.api.Deployment;
12 import org.jboss.arquillian.container.test.api.RunAsClient;
13 import org.jboss.arquillian.junit.Arquillian;
14 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorAbstractAnnotationFreeResouce;
15 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorAnnotationFreeSubResource;
16 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorBaseResource;
17 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorCollectionResource;
18 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorDirectory;
19 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorQueueReceiver;
20 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorReceiver;
21 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorRootInterface;
22 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorSubInterface;
23 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorSubresource;
24 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorSubresource2;
25 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorSubresource3;
26 import org.jboss.resteasy.test.resource.basic.resource.ResourceLocatorSubresource3Interface;
27 import org.jboss.resteasy.utils.PortProviderUtil;
28 import org.jboss.resteasy.utils.TestUtil;
29 import org.jboss.shrinkwrap.api.Archive;
30 import org.jboss.shrinkwrap.api.spec.WebArchive;
31 import org.junit.AfterClass;
32 import org.junit.Assert;
33 import org.junit.BeforeClass;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36
37 /**
38 * @tpSubChapter Resource
39 * @tpChapter Integration tests
40 * @tpTestCaseDetails Tests path encoding
41 * @tpSince RESTEasy 3.0.20
42 */
43 @RunWith(Arquillian.class)
44 @RunAsClient
45 public class ResourceLocatorTest
46 {
47 static Client client;
48
49 @BeforeClass
50 public static void setup() {
51 client = ClientBuilder.newClient();
52 }
53
54 @AfterClass
55 public static void close() {
56 client.close();
57 }
58
59 @Deployment
60 public static Archive<?> deploy() {
61 WebArchive war = TestUtil.prepareArchive(ResourceLocatorTest.class.getSimpleName());
62 war.addClass(ResourceLocatorQueueReceiver.class)
63 .addClass(ResourceLocatorReceiver.class)
64 .addClass(ResourceLocatorRootInterface.class)
65 .addClass(ResourceLocatorSubInterface.class)
66 .addClass(ResourceLocatorSubresource3Interface.class)
67 ;
68 return TestUtil.finishContainerPrepare(war, null,
69 ResourceLocatorAbstractAnnotationFreeResouce.class,
70 ResourceLocatorAnnotationFreeSubResource.class,
71 ResourceLocatorBaseResource.class,
72 ResourceLocatorCollectionResource.class,
73 ResourceLocatorDirectory.class,
74 ResourceLocatorSubresource.class,
75 ResourceLocatorSubresource2.class,
76 ResourceLocatorSubresource3.class
77 );
78 }
79
80 private String generateURL(String path) {
81 return PortProviderUtil.generateURL(path, ResourceLocatorTest.class.getSimpleName());
82 }
83
84
85 /**
86 * @tpTestDetails Resource locator returns proxied resource.
87 * @tpSince RESTEasy 3.0.20
88 */
89 @Test
90 public void testProxiedSubresource() throws Exception
91 {
92 WebTarget target = client.target(generateURL("/proxy/3"));
93 Response res = target.queryParam("foo", "1.2").queryParam("foo", "1.3").request().get();
94 Assert.assertEquals(200, res.getStatus());
95 res.close();
96 }
97
98
99 /**
100 * @tpTestDetails 1) Resource locator returns resource; 2) Resource locator returns resource locator.
101 * @tpSince RESTEasy 3.0.20
102 */
103 @Test
104 public void testSubresource() throws Exception
105 {
106 {
107 Response response = client.target(generateURL("/base/1/resources")).request().get();
108 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
109 Assert.assertEquals(ResourceLocatorSubresource.class.getName(), response.readEntity(String.class));
110 }
111
112 {
113 Response response = client.target(generateURL("/base/1/resources/subresource2/stuff/2/bar")).request().get();
114 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
115 Assert.assertEquals(ResourceLocatorSubresource2.class.getName() + "-2", response.readEntity(String.class));
116 }
117 }
118
119
120 /**
121 * @tpTestDetails Two matching metods, one a resource locator, the other a resource method.
122 * @tpSince RESTEasy 3.0.20
123 */
124 @Test
125 public void testSameUri() throws Exception
126 {
127 Response response = client.target(generateURL("/directory/receivers/1")).request().delete();
128 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
129 Assert.assertEquals(ResourceLocatorDirectory.class.getName(), response.readEntity(String.class));
130 }
131
132
133 /**
134 * @tpTestDetails Locator returns resource which inherits annotations from an interface.
135 * @tpSince RESTEasy 3.0.20
136 */
137 @Test
138 public void testAnnotationFreeSubresource() throws Exception
139 {
140 {
141 Response response = client.target(generateURL("/collection/annotation_free_subresource")).request().get();
142 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
143 Assert.assertEquals("got", response.readEntity(String.class));
144 Assert.assertNotNull(response.getHeaderString("Content-Type"));
145 Assert.assertNotNull(response.getHeaderString("Content-Type"));
146 Assert.assertEquals(MediaType.TEXT_PLAIN_TYPE.withCharset("UTF-8").toString(), response.getHeaderString("Content-Type"));
147 }
148
149 {
150 Builder request = client.target(generateURL("/collection/annotation_free_subresource")).request();
151 Response response = request.post(Entity.entity("hello!".getBytes(), MediaType.TEXT_PLAIN));
152 Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
153 Assert.assertEquals("posted: hello!", response.readEntity(String.class));
154 }
155 }
156 }
+0
-83
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/ScanTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Old client test)
7 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
8 import org.jboss.resteasy.spi.ResteasyProviderFactory;
9 import org.jboss.resteasy.test.resource.basic.resource.ScanProxy;
10 import org.jboss.resteasy.test.resource.basic.resource.ScanResource;
11 import org.jboss.resteasy.test.resource.basic.resource.ScanSubresource;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.spec.WebArchive;
17 import org.junit.AfterClass;
18 import org.junit.Assert;
19 import org.junit.BeforeClass;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 import javax.ws.rs.client.Client;
24 import javax.ws.rs.client.ClientBuilder;
25 import javax.ws.rs.core.Response;
26 import java.util.HashMap;
27 import java.util.Map;
28
29 /**
30 * @tpSubChapter Resource
31 * @tpChapter Integration tests
32 * @tpTestCaseDetails Regression tests for RESTEASY-263 and RESTEASY-274
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class ScanTest {
38 private static Client client;
39
40 @BeforeClass
41 public static void before() throws Exception {
42 client = ClientBuilder.newClient();
43 }
44
45 @AfterClass
46 public static void after() throws Exception {
47 client.close();
48 }
49
50 @Deployment
51 public static Archive<?> deployUriInfoSimpleResource() {
52 WebArchive war = TestUtil.prepareArchive(ScanTest.class.getSimpleName());
53 war.addClass(ScanProxy.class);
54 Map<String, String> contextParams = new HashMap<>();
55 contextParams.put("resteasy.scan", "true");
56 return TestUtil.finishContainerPrepare(war, contextParams, ScanResource.class, ScanSubresource.class);
57 }
58
59 /**
60 * @tpTestDetails Test with old client
61 * @tpSince RESTEasy 3.0.16
62 */
63 @Test
64 public void testOldClient() throws Exception {
65 RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
66 ClientRequest request = new ClientRequest(PortProviderUtil.generateURL("/test/doit", ScanTest.class.getSimpleName()));
67 ClientResponse response = request.get();
68 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
69 Assert.assertEquals("Wrong content of response", "hello world", response.getEntity(String.class));
70 }
71
72 /**
73 * @tpTestDetails Test with new client
74 * @tpSince RESTEasy 3.0.16
75 */
76 @Test
77 public void testNewClient() throws Exception {
78 Response response = client.target(PortProviderUtil.generateURL("/test/doit", ScanTest.class.getSimpleName())).request().get();
79 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
80 Assert.assertEquals("Wrong content of response", "hello world", response.readEntity(String.class));
81 }
82 }
+0
-148
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/SpecialResourceTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.apache.http.HttpResponse;
3 import org.apache.http.client.HttpClient;
4 import org.apache.http.client.methods.HttpPut;
5 import org.apache.http.entity.ContentType;
6 import org.apache.http.entity.StringEntity;
7 import org.apache.http.impl.client.HttpClientBuilder;
8 import org.jboss.arquillian.container.test.api.Deployment;
9 import org.jboss.arquillian.container.test.api.RunAsClient;
10 import org.jboss.arquillian.junit.Arquillian;
11 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
12 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
13 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
14 import org.jboss.resteasy.test.resource.basic.resource.SpecialResourceApiResource;
15 import org.jboss.resteasy.test.resource.basic.resource.SpecialResourceDeleteResource;
16 import org.jboss.resteasy.test.resource.basic.resource.SpecialResourceStreamResource;
17 import org.jboss.resteasy.test.resource.basic.resource.SpecialResourceSubFactory;
18 import org.jboss.resteasy.util.HttpResponseCodes;
19 import org.jboss.resteasy.utils.PortProviderUtil;
20 import org.jboss.resteasy.utils.TestUtil;
21 import org.jboss.shrinkwrap.api.Archive;
22 import org.jboss.shrinkwrap.api.spec.WebArchive;
23 import org.junit.AfterClass;
24 import org.junit.Assert;
25 import org.junit.BeforeClass;
26 import org.junit.Test;
27 import org.junit.runner.RunWith;
28 import org.w3c.dom.Document;
29
30 import javax.ws.rs.client.Entity;
31 import javax.ws.rs.client.WebTarget;
32 import javax.ws.rs.core.MediaType;
33 import javax.ws.rs.core.Response;
34 import java.io.IOException;
35
36 import static org.hamcrest.Matchers.greaterThan;
37 import static org.jboss.resteasy.util.HttpClient4xUtils.consumeEntity;
38
39 /**
40 * @tpSubChapter Resources
41 * @tpChapter Integration tests
42 * @tpTestCaseDetails Regression test for RESTEasy issues about special resources
43 * @tpSince RESTEasy 3.0.16
44 */
45 @RunWith(Arquillian.class)
46 @RunAsClient
47 public class SpecialResourceTest {
48
49 static ResteasyClient client;
50
51 @Deployment
52 public static Archive<?> testReturnValuesDeploy() throws Exception {
53 WebArchive war = TestUtil.prepareArchive(SpecialResourceTest.class.getSimpleName());
54 return TestUtil.finishContainerPrepare(war, null, SpecialResourceStreamResource.class,
55 SpecialResourceApiResource.class, SpecialResourceDeleteResource.class);
56 }
57
58 @BeforeClass
59 public static void init() {
60 client = new ResteasyClientBuilder().build();
61 }
62
63 @AfterClass
64 public static void close() {
65 client.close();
66 client = null;
67 }
68
69 private String generateURL(String path) {
70 return PortProviderUtil.generateURL(path, SpecialResourceTest.class.getSimpleName());
71 }
72
73 /**
74 * @tpTestDetails Regression test for RESTEASY-631
75 * @tpSince RESTEasy 3.0.16
76 */
77 @Test
78 public void test631() throws Exception {
79 WebTarget base = client.target(generateURL("/delete"));
80 Response response = base.request().method("DELETE", Entity.entity("hello", "text/plain"));
81 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
82 response.close();
83 }
84
85 /**
86 * @tpTestDetails Regression test for RESTEASY-534
87 * @tpSince RESTEasy 3.0.16
88 */
89 @Test
90 public void test534() throws Exception {
91 WebTarget base = client.target(generateURL("/inputstream/test/json"));
92 Response response = base.request().post(Entity.entity("hello world".getBytes(), MediaType.APPLICATION_OCTET_STREAM));
93 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
94 response.close();
95 }
96
97 /**
98 * @tpTestDetails Regression test for RESTEASY-624
99 * @tpSince RESTEasy 3.0.16
100 */
101 @Test
102 public void test624() throws Exception {
103 WebTarget base = client.target(generateURL("/ApI/FuNc"));
104 Response response = base.request().get();
105 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
106 response.close();
107
108 }
109
110 /**
111 * @tpTestDetails Regression test for RESTEASY-583
112 * @tpSince RESTEasy 3.0.16
113 */
114 @Test
115 public void test583() throws Exception {
116 HttpClient client = HttpClientBuilder.create().build();
117 HttpPut method = new HttpPut(generateURL("/api"));
118 HttpResponse response = null;
119 try {
120 method.setEntity(new StringEntity("hello", ContentType.create("vnd.net.juniper.space.target-management.targets+xml;version=1;charset=UTF-8")));
121 response = client.execute(method);
122 Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpResponseCodes.SC_BAD_REQUEST);
123 } catch (IOException e) {
124 throw new RuntimeException(e);
125 } finally {
126 consumeEntity(response);
127 }
128 }
129
130 /**
131 * @tpTestDetails Regression test for RESTEASY-638
132 * @tpSince RESTEasy 3.0.16
133 */
134 @Test
135 public void test638() throws Exception {
136 SpecialResourceSubFactory factory = new SpecialResourceSubFactory();
137 RegisterBuiltin.register(factory);
138
139 for (int i = 0; i < 10; i++) {
140 MediaType type = MediaType.valueOf("text/xml; boundary=" + i);
141 Assert.assertThat("Wrong count of possible providers", factory.getMBRMap().getPossible(type, Document.class).size(), greaterThan(1));
142 }
143
144 Assert.assertEquals(1, factory.getMBRMap().getClassCache().size());
145
146 }
147 }
+0
-65
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/SubResourceLocatorTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.basic.resource.SubResourceLocatorBaseCrudService;
8 import org.jboss.resteasy.test.resource.basic.resource.SubResourceLocatorBaseService;
9 import org.jboss.resteasy.test.resource.basic.resource.SubResourceLocatorFoo;
10 import org.jboss.resteasy.test.resource.basic.resource.SubResourceLocatorImpFoo;
11 import org.jboss.resteasy.test.resource.basic.resource.SubResourceLocatorOhaUserModel;
12 import org.jboss.resteasy.test.resource.basic.resource.SubResourceLocatorPlatformServiceImpl;
13 import org.jboss.resteasy.test.resource.basic.resource.SubResourceLocatorPlatformServiceResource;
14 import org.jboss.resteasy.test.resource.basic.resource.SubResourceLocatorUserResource;
15 import org.jboss.resteasy.utils.PortProviderUtil;
16 import org.jboss.resteasy.utils.TestUtil;
17 import org.jboss.shrinkwrap.api.Archive;
18 import org.jboss.shrinkwrap.api.spec.WebArchive;
19 import org.junit.Assert;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22
23 import javax.ws.rs.client.WebTarget;
24 import javax.ws.rs.core.Response;
25
26 import static org.hamcrest.CoreMatchers.is;
27
28 /**
29 * @tpSubChapter Resources
30 * @tpChapter Integration tests
31 * @tpTestCaseDetails Regression test for RESTEASY-657
32 * @tpSince RESTEasy 3.0.16
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class SubResourceLocatorTest {
37
38 @Deployment
39 public static Archive<?> testReturnValuesDeploy() throws Exception {
40 WebArchive war = TestUtil.prepareArchive(SubResourceLocatorTest.class.getSimpleName());
41 war.addClasses(SubResourceLocatorBaseCrudService.class, SubResourceLocatorBaseService.class,
42 SubResourceLocatorFoo.class, SubResourceLocatorOhaUserModel.class,
43 SubResourceLocatorPlatformServiceResource.class, SubResourceLocatorUserResource.class);
44 return TestUtil.finishContainerPrepare(war, null, SubResourceLocatorImpFoo.class,
45 SubResourceLocatorPlatformServiceImpl.class);
46 }
47
48 /**
49 * @tpTestDetails Sub resource locator should not fail
50 * @tpSince RESTEasy 3.0.16
51 */
52 @Test
53 public void test657() throws Exception {
54 ResteasyClient client = new ResteasyClientBuilder().build();
55 WebTarget base = client.target(PortProviderUtil.generateURL("/platform/users/89080/data/ada/jsanchez110",
56 SubResourceLocatorTest.class.getSimpleName()));
57
58 Response response = base.request().get();
59 String s = response.readEntity(String.class);
60 Assert.assertThat("Wrong response content", s, is("bill"));
61 response.close();
62 client.close();
63 }
64 }
+0
-210
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/UriInfoTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.category.NotForForwardCompatibility;
8 import org.jboss.resteasy.test.resource.basic.resource.UriInfoEncodedQueryResource;
9 import org.jboss.resteasy.test.resource.basic.resource.UriInfoEncodedTemplateResource;
10 import org.jboss.resteasy.test.resource.basic.resource.UriInfoEscapedMatrParamResource;
11 import org.jboss.resteasy.test.resource.basic.resource.UriInfoQueryParamsResource;
12 import org.jboss.resteasy.test.resource.basic.resource.UriInfoRelativizeResource;
13 import org.jboss.resteasy.test.resource.basic.resource.UriInfoSimpleResource;
14 import org.jboss.resteasy.test.resource.basic.resource.UriInfoSimpleSingletonResource;
15 import org.jboss.resteasy.util.HttpResponseCodes;
16 import org.jboss.resteasy.utils.PortProviderUtil;
17 import org.jboss.resteasy.utils.TestUtil;
18 import org.jboss.shrinkwrap.api.Archive;
19 import org.jboss.shrinkwrap.api.spec.WebArchive;
20 import org.junit.AfterClass;
21 import org.junit.Assert;
22 import org.junit.BeforeClass;
23 import org.junit.Test;
24 import org.junit.experimental.categories.Category;
25 import org.junit.runner.RunWith;
26
27 import javax.ws.rs.client.Client;
28 import javax.ws.rs.client.ClientBuilder;
29 import javax.ws.rs.client.WebTarget;
30 import javax.ws.rs.core.Response;
31 import javax.ws.rs.core.UriBuilder;
32 import java.net.URI;
33 import java.util.ArrayList;
34 import java.util.List;
35
36 /**
37 * @tpSubChapter Resources
38 * @tpChapter Integration tests
39 * @tpTestCaseDetails Tests for java.net.URI class
40 * @tpSince RESTEasy 3.0.16
41 */
42 @RunWith(Arquillian.class)
43 @RunAsClient
44 public class UriInfoTest {
45
46 protected final Logger logger = LogManager.getLogger(UriInfoTest.class.getName());
47
48 private static Client client;
49
50 @BeforeClass
51 public static void before() throws Exception {
52 client = ClientBuilder.newClient();
53 }
54
55 @AfterClass
56 public static void after() throws Exception {
57 client.close();
58 client = null;
59 }
60
61 @SuppressWarnings(value = "unchecked")
62 @Deployment(name = "UriInfoSimpleResource")
63 public static Archive<?> deployUriInfoSimpleResource() {
64 WebArchive war = TestUtil.prepareArchive(UriInfoSimpleResource.class.getSimpleName());
65 war.addClass(PortProviderUtil.class);
66 return TestUtil.finishContainerPrepare(war, null, UriInfoSimpleResource.class);
67 }
68
69 /**
70 * @tpTestDetails Check uri from resource on server. Simple resource is used.
71 * @tpSince RESTEasy 3.0.16
72 */
73 @Test
74 public void testUriInfo() throws Exception {
75 basicTest("/simple", UriInfoSimpleResource.class.getSimpleName());
76 basicTest("/simple/fromField", UriInfoSimpleResource.class.getSimpleName());
77 }
78
79 @Deployment(name = "UriInfoSimpleSingletonResource")
80 public static Archive<?> deployUriInfoSimpleResourceAsSingleton() {
81 WebArchive war = TestUtil.prepareArchive(UriInfoSimpleSingletonResource.class.getSimpleName());
82 war.addClass(PortProviderUtil.class);
83 List<Class<?>> singletons = new ArrayList<>();
84 singletons.add(UriInfoSimpleSingletonResource.class);
85 return TestUtil.finishContainerPrepare(war, null, singletons, (Class<?>[]) null);
86 }
87
88 /**
89 * @tpTestDetails Check uri from resource on server. Resource is set as singleton to RESTEasy.
90 * @tpSince RESTEasy 3.0.16
91 */
92 @Test
93 public void testUriInfoWithSingleton() throws Exception {
94 basicTest("/simple/fromField", UriInfoSimpleSingletonResource.class.getSimpleName());
95 }
96
97 @Deployment(name = "UriInfoEscapedMatrParamResource")
98 public static Archive<?> deployUriInfoEscapedMatrParamResource() {
99 WebArchive war = TestUtil.prepareArchive(UriInfoEscapedMatrParamResource.class.getSimpleName());
100 war.addClass(PortProviderUtil.class);
101 return TestUtil.finishContainerPrepare(war, null, UriInfoEscapedMatrParamResource.class);
102 }
103
104 /**
105 * @tpTestDetails Check uri from resource on server. Test complex parameter.
106 * @tpSince RESTEasy 3.0.16
107 */
108 @Test
109 public void testEscapedMatrParam() throws Exception {
110 basicTest("/queryEscapedMatrParam;a=a%3Bb;b=x%2Fy;c=m%5Cn;d=k%3Dl", UriInfoEscapedMatrParamResource.class.getSimpleName());
111 }
112
113 @Deployment(name = "UriInfoEncodedTemplateResource")
114 public static Archive<?> deployUriInfoEncodedTemplateResource() {
115 WebArchive war = TestUtil.prepareArchive(UriInfoEncodedTemplateResource.class.getSimpleName());
116 war.addClass(PortProviderUtil.class);
117 return TestUtil.finishContainerPrepare(war, null, UriInfoEncodedTemplateResource.class);
118 }
119
120 /**
121 * @tpTestDetails Check uri from resource on server. Test space character in URI.
122 * @tpSince RESTEasy 3.0.16
123 */
124 @Test
125 public void testEncodedTemplateParams() throws Exception {
126 basicTest("/a%20b/x%20y", UriInfoEncodedTemplateResource.class.getSimpleName());
127 }
128
129
130 @Deployment(name = "UriInfoEncodedQueryResource")
131 public static Archive<?> deployUriInfoEncodedQueryResource() {
132 WebArchive war = TestUtil.prepareArchive(UriInfoEncodedQueryResource.class.getSimpleName());
133 war.addClass(PortProviderUtil.class);
134 return TestUtil.finishContainerPrepare(war, null, UriInfoEncodedQueryResource.class);
135 }
136
137 /**
138 * @tpTestDetails Check uri from resource on server. Test space character in URI attribute.
139 * @tpSince RESTEasy 3.0.16
140 */
141 @Test
142 public void testEncodedQueryParams() throws Exception {
143 basicTest("/query?a=a%20b", UriInfoEncodedQueryResource.class.getSimpleName());
144 }
145
146 @Deployment(name = "UriInfoRelativizeResource")
147 public static Archive<?> deployUriInfoRelativizeResource() {
148 WebArchive war = TestUtil.prepareArchive(UriInfoRelativizeResource.class.getSimpleName());
149 war.addClass(PortProviderUtil.class);
150 return TestUtil.finishContainerPrepare(war, null, UriInfoRelativizeResource.class);
151 }
152
153 /**
154 * @tpTestDetails Check uri from resource on server. Test return value from resource - same URI address.
155 * @tpSince RESTEasy 3.0.16
156 */
157 @Test
158 public void testRelativize() throws Exception {
159 String uri = PortProviderUtil.generateURL("/", UriInfoRelativizeResource.class.getSimpleName());
160 WebTarget target = client.target(uri);
161 String result;
162 result = target.path("a/b/c").queryParam("to", "a/d/e").request().get(String.class);
163 Assert.assertEquals("../../d/e", result);
164 result = target.path("a/b/c").queryParam("to", UriBuilder.fromUri(uri).path("a/d/e").build().toString()).request().get(String.class);
165 Assert.assertEquals("../../d/e", result);
166 result = target.path("a/b/c").queryParam("to", "http://foobar/a/d/e").request().get(String.class);
167 Assert.assertEquals("http://foobar/a/d/e", result);
168 }
169
170 /**
171 * @tpTestDetails Check uri on client. Base unit test.
172 * @tpSince RESTEasy 3.0.16
173 */
174 @Test
175 public void testResolve() throws Exception {
176 URI uri = new URI("http://localhost/base1/base2");
177 logger.info(String.format("Resolved foo: %s", uri.resolve("foo")));
178 logger.info(String.format("Resolved /foo: %s", uri.resolve("/foo")));
179 logger.info(String.format("Resolved ../foo: %s", uri.resolve("../foo")));
180 }
181
182
183 private void basicTest(String path, String testName) throws Exception {
184 Response response = client.target(PortProviderUtil.generateURL(path, testName)).request().get();
185 try {
186 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
187 } finally {
188 response.close();
189 }
190 }
191
192 @Deployment(name = "UriInfoQueryParamsResource")
193 public static Archive<?> deployUriInfoQueryParamsResource() {
194 WebArchive war = TestUtil.prepareArchive(UriInfoQueryParamsResource.class.getSimpleName());
195 war.addClass(PortProviderUtil.class);
196 return TestUtil.finishContainerPrepare(war, null, UriInfoQueryParamsResource.class);
197 }
198
199 /**
200 * @tpTestDetails Test that UriInfo.getQueryParameters() returns an immutable map. Test's logic is in end-point.
201 * @tpSince RESTEasy 3.0.17
202 */
203 @Test
204 @Category({NotForForwardCompatibility.class})
205 public void testQueryParamsMutability() throws Exception {
206 basicTest("/queryParams?a=a,b", "UriInfoQueryParamsResource");
207 }
208
209 }
+0
-74
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/WiderMappingNegativeTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.resource.basic.resource.WiderMappingDefaultOptions;
6 import org.jboss.resteasy.test.resource.basic.resource.WiderMappingResource;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.AfterClass;
13 import org.junit.Assert;
14 import org.junit.BeforeClass;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.core.Response;
21 import java.util.HashMap;
22 import java.util.Map;
23
24 /**
25 * @tpSubChapter Resources
26 * @tpChapter Integration tests
27 * @tpTestCaseDetails Test negative scenario for "resteasy.wider.request.matching" property
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class WiderMappingNegativeTest {
33
34 static Client client;
35
36 private String generateURL(String path) {
37 return PortProviderUtil.generateURL(path, WiderMappingNegativeTest.class.getSimpleName());
38 }
39
40 @Deployment
41 public static Archive<?> deployUriInfoSimpleResource() {
42 WebArchive war = TestUtil.prepareArchive(WiderMappingNegativeTest.class.getSimpleName());
43 war.addClass(PortProviderUtil.class);
44
45 Map<String, String> contextParam = new HashMap<>();
46 contextParam.put("resteasy.wider.request.matching", "false");
47 return TestUtil.finishContainerPrepare(war, contextParam, WiderMappingResource.class, WiderMappingDefaultOptions.class);
48 }
49
50
51 @BeforeClass
52 public static void setup() {
53 client = ClientBuilder.newClient();
54 }
55
56 @AfterClass
57 public static void cleanup() {
58 client.close();
59 }
60
61 /**
62 * @tpTestDetails Two resources used, more general resource should not be used
63 * @tpSince RESTEasy 3.0.16
64 */
65 @Test
66 public void testOptions() {
67 Response response = client.target(generateURL("/hello/int")).request().options();
68 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
69 Assert.assertNotEquals(response.readEntity(String.class), "hello");
70 response.close();
71 }
72
73 }
+0
-75
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/WiderMappingTest.java less more
0 package org.jboss.resteasy.test.resource.basic;
1
2
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.resteasy.test.resource.basic.resource.WiderMappingDefaultOptions;
7 import org.jboss.resteasy.test.resource.basic.resource.WiderMappingResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.Assert;
15 import org.junit.BeforeClass;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Client;
20 import javax.ws.rs.client.ClientBuilder;
21 import javax.ws.rs.core.Response;
22 import java.util.HashMap;
23 import java.util.Map;
24
25 /**
26 * @tpSubChapter Resources
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Test positive scenario for "resteasy.wider.request.matching" property
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class WiderMappingTest {
34
35 static Client client;
36
37 private String generateURL(String path) {
38 return PortProviderUtil.generateURL(path, WiderMappingNegativeTest.class.getSimpleName());
39 }
40
41 @Deployment
42 public static Archive<?> deployUriInfoSimpleResource() {
43 WebArchive war = TestUtil.prepareArchive(WiderMappingNegativeTest.class.getSimpleName());
44 war.addClass(PortProviderUtil.class);
45
46 Map<String, String> contextParam = new HashMap<>();
47 contextParam.put("resteasy.wider.request.matching", "true");
48 return TestUtil.finishContainerPrepare(war, contextParam, WiderMappingResource.class, WiderMappingDefaultOptions.class);
49 }
50
51
52 @BeforeClass
53 public static void setup() {
54 client = ClientBuilder.newClient();
55 }
56
57 @AfterClass
58 public static void cleanup() {
59 client.close();
60 }
61
62 /**
63 * @tpTestDetails Two resources used, more general resource should be used
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testOptions() {
68 Response response = client.target(generateURL("/hello/int")).request().options();
69 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
70 Assert.assertEquals(response.readEntity(String.class), "hello");
71 response.close();
72 }
73
74 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/CollectionDefaultValueResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.QueryParam;
8 import java.util.List;
9
10 @Path("/collection")
11 public class CollectionDefaultValueResource {
12 @GET
13 @Produces("text/plain")
14 public String get(@QueryParam("nada") List<String> params) {
15 Assert.assertNotNull("Empty list was sent like null", params);
16 Assert.assertEquals("Empty list was sent not empty", 0, params.size());
17 return "hello";
18 }
19
20 }
+0
-45
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ConstructedInjectionResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.test.TestPortProvider;
4 import org.junit.Assert;
5
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.QueryParam;
9 import javax.ws.rs.core.Context;
10 import javax.ws.rs.core.UriInfo;
11 import java.net.URI;
12
13 @Path("/")
14 public class ConstructedInjectionResource {
15 private static Logger logger = Logger.getLogger(ConstructedInjectionResource.class);
16
17 UriInfo myInfo;
18 String abs;
19
20 public ConstructedInjectionResource(@Context final UriInfo myInfo, @QueryParam("abs") final String abs) {
21 this.myInfo = myInfo;
22 this.abs = abs;
23 }
24
25 @Path("/simple")
26 @GET
27 public String get() {
28 logger.info("abs query: " + abs);
29 URI base = null;
30 if (abs == null) {
31 base = TestPortProvider.createURI("/");
32 } else {
33 base = TestPortProvider.createURI("/" + abs + "/");
34 }
35
36 logger.info("BASE URI: " + myInfo.getBaseUri());
37 logger.info("Request URI: " + myInfo.getRequestUri());
38 Assert.assertEquals("The injected base path doesn't match to the expected one",
39 base.getPath() + "ConstructedInjectionTest/", myInfo.getBaseUri().getPath());
40 Assert.assertEquals("The injected path doesn't match to the expected one", "/simple", myInfo.getPath());
41 return "CONTENT";
42 }
43
44 }
+0
-9
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/CovariantReturnSubresourceLocatorsRootProxy.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.PathParam;
4
5 public interface CovariantReturnSubresourceLocatorsRootProxy {
6 @Path("sub/{path}")
7 CovariantReturnSubresourceLocatorsSubProxy getSub(@PathParam("path") String path);
8 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/CovariantReturnSubresourceLocatorsSubProxy.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Produces;
4
5 public interface CovariantReturnSubresourceLocatorsSubProxy {
6 @GET
7 @Produces("text/plain")
8 String get();
9 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/CovariantReturnSubresourceLocatorsSubProxyRootImpl.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("/path")
5 public class CovariantReturnSubresourceLocatorsSubProxyRootImpl implements CovariantReturnSubresourceLocatorsRootProxy {
6 @Override
7 public CovariantReturnSubresourceLocatorsSubProxySubImpl getSub(String path) {
8 return new CovariantReturnSubresourceLocatorsSubProxySubImpl(path);
9 }
10 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/CovariantReturnSubresourceLocatorsSubProxySubImpl.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public class CovariantReturnSubresourceLocatorsSubProxySubImpl implements CovariantReturnSubresourceLocatorsSubProxy {
3 private final String path;
4
5 public CovariantReturnSubresourceLocatorsSubProxySubImpl(final String path) {
6 this.path = path;
7 }
8
9 public String get() {
10 return "Boo! - " + path;
11 }
12 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/DefaultMediaTypeCustomObject.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public class DefaultMediaTypeCustomObject {
3 public int a;
4 public int b;
5 public String toString() {
6 return String.format("%d,%d", a, b);
7 }
8 public DefaultMediaTypeCustomObject(final int a, final int b) {
9 this.a = a;
10 this.b = b;
11 }
12 }
+0
-108
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/DefaultMediaTypeResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.activation.DataSource;
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.Response;
11 import java.io.File;
12 import java.io.InputStream;
13 import java.util.Date;
14
15 @Path("/")
16 public class DefaultMediaTypeResource {
17
18 protected static final Logger logger = Logger.getLogger(DefaultMediaTypeResource.class.getName());
19
20 @Path("post")
21 @Consumes(MediaType.APPLICATION_OCTET_STREAM)
22 //@Produces(MediaType.TEXT_PLAIN)
23 @POST
24 public Response post(DataSource source) throws Exception {
25 InputStream is = source.getInputStream();
26 while (is.read() > -1) {
27 }
28 logger.info("Readed once, going to read second");
29 InputStream is2 = source.getInputStream();
30 is2.close();
31 // return Response.ok().entity(countTempFiles()).type(MediaType.WILDCARD_TYPE).build();
32 return Response.ok().entity(countTempFiles()).build();
33 }
34
35 private int countTempFiles() throws Exception {
36 String tmpdir = System.getProperty("java.io.tmpdir");
37 logger.info("tmpdir: " + tmpdir);
38 File dir = new File(tmpdir);
39 int counter = 0;
40 for (File file : dir.listFiles()) {
41 if (file.getName().startsWith("resteasy-provider-datasource")) {
42 counter++;
43 }
44 }
45 return counter;
46 }
47
48 @Path("postDateProduce")
49 @Consumes(MediaType.APPLICATION_OCTET_STREAM)
50 @Produces(MediaType.TEXT_PLAIN)
51 @POST
52 public Response postDateProduce(DataSource source) throws Exception {
53 return Response.ok().entity(new Date(10000)).build();
54 }
55 @Path("postDate")
56 @Consumes(MediaType.APPLICATION_OCTET_STREAM)
57 @POST
58 public Response postDate(DataSource source) throws Exception {
59 return Response.ok().entity(new Date(10000)).build();
60 }
61
62
63 @Path("postFooProduce")
64 @Consumes(MediaType.APPLICATION_OCTET_STREAM)
65 @Produces(MediaType.TEXT_PLAIN)
66 @POST
67 public Response postFooProduce(DataSource source) throws Exception {
68 return Response.ok().entity(new DefaultMediaTypeCustomObject(8, 9)).build();
69 }
70
71 @Path("postFoo")
72 @Consumes(MediaType.APPLICATION_OCTET_STREAM)
73 @POST
74 public Response postFoo(DataSource source) throws Exception {
75 return Response.ok().entity(new DefaultMediaTypeCustomObject(8, 9)).build();
76 }
77
78 @Path("postIntProduce")
79 @Consumes(MediaType.APPLICATION_OCTET_STREAM)
80 @Produces(MediaType.TEXT_PLAIN)
81 @POST
82 public Response postIntProduce(DataSource source) throws Exception {
83 return Response.ok().entity(new Integer(8)).build();
84 }
85
86 @Path("postInt")
87 @Consumes(MediaType.APPLICATION_OCTET_STREAM)
88 @POST
89 public Response postInt(DataSource source) throws Exception {
90 return Response.ok().entity(new Integer(8)).build();
91 }
92
93 @Path("postIntegerProduce")
94 @Consumes(MediaType.APPLICATION_OCTET_STREAM)
95 @Produces(MediaType.TEXT_PLAIN)
96 @POST
97 public Response postIntegerProduce(DataSource source) throws Exception {
98 return Response.ok().entity(5).build();
99 }
100
101 @Path("postInteger")
102 @Consumes(MediaType.APPLICATION_OCTET_STREAM)
103 @POST
104 public Response postInteger(DataSource source) throws Exception {
105 return Response.ok().entity(5).build();
106 }
107 }
+0
-52
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ExtensionResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.Context;
8 import javax.ws.rs.core.HttpHeaders;
9 import javax.ws.rs.core.MediaType;
10 import java.util.List;
11 import java.util.Locale;
12
13 @Path("/extension")
14 public class ExtensionResource {
15 @GET
16 @Produces("*/*")
17 public String getDefault() {
18 return "default";
19 }
20
21 @GET
22 @Produces("application/xml")
23 public String getXml(@Context HttpHeaders headers) {
24 @SuppressWarnings("unused")
25 List<Locale> languages = headers.getAcceptableLanguages();
26 @SuppressWarnings("unused")
27 List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
28 return "xml";
29 }
30
31 @GET
32 @Produces("text/html")
33 public String getXmlTwo(@Context HttpHeaders headers) {
34 List<Locale> languages = headers.getAcceptableLanguages();
35 Assert.assertEquals("Wrong number of accepted languages", 1, languages.size());
36 Assert.assertEquals("Wrong accepted language", new Locale("en", "us"), languages.get(0));
37 Assert.assertEquals("Wrong accepted language", MediaType.valueOf("text/html"), headers.getAcceptableMediaTypes().get(0));
38 return "html";
39 }
40
41 @GET
42 @Path("/stuff.old")
43 @Produces("text/plain")
44 public String getJson(@Context HttpHeaders headers) {
45 List<Locale> languages = headers.getAcceptableLanguages();
46 Assert.assertEquals("Wrong number of accepted languages", 1, languages.size());
47 Assert.assertEquals("Wrong accepted language", new Locale("en", "us"), languages.get(0));
48 Assert.assertEquals("Wrong accepted language", MediaType.valueOf("text/plain"), headers.getAcceptableMediaTypes().get(0));
49 return "plain";
50 }
51 }
+0
-54
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/GenericEntityDoubleWriter.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.Provider;
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.ParameterizedType;
14 import java.lang.reflect.Type;
15 import java.util.List;
16
17 @Provider
18 @Produces("*/*")
19 public class GenericEntityDoubleWriter implements MessageBodyWriter<List<Double>> {
20
21 private static Logger logger = Logger.getLogger(GenericEntityDoubleWriter.class);
22
23 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
24 logger.info("DoubleWriter type: " + type.getName());
25 if (!List.class.isAssignableFrom(type)) {
26 return false;
27 }
28 logger.info("DoubleWriter: " + genericType);
29 if (!(genericType instanceof ParameterizedType)) {
30 return false;
31 }
32 logger.info("DoubleWriter");
33 ParameterizedType pt = (ParameterizedType) genericType;
34 boolean result = pt.getActualTypeArguments()[0].equals(Double.class);
35 logger.info("Doublewriter result!!!: " + result);
36 return result;
37 }
38
39 public long getSize(List<Double> doubles, Class<?> type, Type genericType, Annotation[] annotations,
40 MediaType mediaType) {
41 return -1;
42 }
43
44 public void writeTo(List<Double> floats, Class<?> type, Type genericType, Annotation[] annotations,
45 MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
46 throws IOException, WebApplicationException {
47 StringBuffer buf = new StringBuffer();
48 for (Double f : floats) {
49 buf.append(f.toString()).append("D ");
50 }
51 entityStream.write(buf.toString().getBytes());
52 }
53 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/GenericEntityResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.GenericEntity;
5 import javax.ws.rs.core.Response;
6 import java.util.ArrayList;
7 import java.util.List;
8
9 @Path("/")
10 public class GenericEntityResource {
11 @Path("floats")
12 @GET
13 public Response getFloats() {
14 ArrayList<Float> list = new ArrayList<Float>();
15 list.add(45.0f);
16 list.add(50.0f);
17 GenericEntity<List<Float>> ge = new GenericEntity<List<Float>>(list) {
18 };
19 return Response.ok(ge).build();
20 }
21
22 @Path("doubles")
23 @GET
24 public Response getDoubles() {
25 ArrayList<Double> list = new ArrayList<Double>();
26 list.add(45.0);
27 list.add(50.0);
28 GenericEntity<List<Double>> ge = new GenericEntity<List<Double>>(list) {
29 };
30 return Response.ok(ge).build();
31 }
32 }
+0
-51
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/GenericEntitytFloatWriter.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.WebApplicationException;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.Provider;
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.ParameterizedType;
14 import java.lang.reflect.Type;
15 import java.util.List;
16
17 @Provider
18 @Produces("*/*")
19 public class GenericEntitytFloatWriter implements MessageBodyWriter<List<Float>> {
20
21 private static Logger logger = Logger.getLogger(GenericEntitytFloatWriter.class);
22
23 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
24 if (!List.class.isAssignableFrom(type)) {
25 return false;
26 }
27 if (!(genericType instanceof ParameterizedType)) {
28 return false;
29 }
30 ParameterizedType pt = (ParameterizedType) genericType;
31 boolean result = pt.getActualTypeArguments()[0].equals(Float.class);
32 logger.info("FloatWriter result!!!: " + result);
33 return result;
34 }
35
36 public long getSize(List<Float> floats, Class<?> type, Type genericType, Annotation[] annotations,
37 MediaType mediaType) {
38 return -1;
39 }
40
41 public void writeTo(List<Float> floats, Class<?> type, Type genericType, Annotation[] annotations,
42 MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
43 throws IOException, WebApplicationException {
44 StringBuffer buf = new StringBuffer();
45 for (Float f : floats) {
46 buf.append(f.toString()).append("F ");
47 }
48 entityStream.write(buf.toString().getBytes());
49 }
50 }
+0
-34
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/GenericResourceCrudResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.PUT;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.PathParam;
6
7 /**
8 * This is a sample of a CRUD resource template which can be reused for different entities.
9 *
10 * @param <ENTITY_TYPE> Type of the entity which CRUD operations are performed on.
11 * @param <ENTITY_IDENTIFIER_TYPE> Type of the entity identified i.e. java.lang.Long
12 * @author Jozef Hartinger
13 */
14 public abstract class GenericResourceCrudResource<ENTITY_TYPE, ENTITY_IDENTIFIER_TYPE>
15 {
16 abstract ENTITY_TYPE getEntity(ENTITY_IDENTIFIER_TYPE id);
17
18 abstract void setEntity(ENTITY_IDENTIFIER_TYPE id, ENTITY_TYPE entity);
19
20 @GET
21 @Path("/{id}")
22 public ENTITY_TYPE get(@PathParam("id") ENTITY_IDENTIFIER_TYPE id)
23 {
24 return getEntity(id);
25 }
26
27 @PUT
28 @Path("/{id}")
29 public void put(@PathParam("id") ENTITY_IDENTIFIER_TYPE id, ENTITY_TYPE entity)
30 {
31 setEntity(id, entity);
32 }
33 }
+0
-31
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/GenericResourceStudent.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public class GenericResourceStudent
3 {
4 private String name;
5
6 public GenericResourceStudent()
7 {
8 }
9
10 public GenericResourceStudent(String name)
11 {
12 this.name = name;
13 }
14
15 public String getName()
16 {
17 return name;
18 }
19
20 public void setName(String name)
21 {
22 this.name = name;
23 }
24
25 @Override
26 public String toString()
27 {
28 return "Student: " + name;
29 }
30 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/GenericResourceStudentCrudResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 /**
9 * RESTEasy should be able to use type parameter values (Student, Integer) for (de)marshalling parameters/entity body.
10 *
11 * @author Jozef Hartinger
12 */
13 @Path("/student")
14 @Produces("application/student")
15 @Consumes("application/student")
16 public class GenericResourceStudentCrudResource extends GenericResourceCrudResource<GenericResourceStudent, Integer>
17 {
18
19 private static Map<Integer, GenericResourceStudent> students = new HashMap<Integer, GenericResourceStudent>();
20
21 public GenericResourceStudentCrudResource()
22 {
23 students.put(1, new GenericResourceStudent("Jozef Hartinger"));
24 }
25
26 @Override
27 GenericResourceStudent getEntity(Integer id)
28 {
29 return students.get(id);
30 }
31
32 @Override
33 void setEntity(Integer id, GenericResourceStudent entity)
34 {
35 students.put(id, entity);
36 }
37 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/GenericResourceStudentInterface.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.PUT;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8
9 /**
10 * This interface is used on the client side only.
11 *
12 * @author Jozef Hartinger
13 */
14
15 @Path("/student/{id}")
16 @Produces("application/student")
17 @Consumes("application/student")
18 public interface GenericResourceStudentInterface
19 {
20 @GET
21 GenericResourceStudent get(@PathParam("id") Integer id);
22
23 @PUT
24 void put(@PathParam("id") Integer id, GenericResourceStudent entity);
25 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/GenericResourceStudentReader.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyReader;
7 import javax.ws.rs.ext.Provider;
8 import java.io.BufferedReader;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14
15 @Provider
16 @Consumes("application/student")
17 public class GenericResourceStudentReader implements MessageBodyReader<GenericResourceStudent>
18 {
19
20 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
21 {
22 return true;
23 }
24
25 public GenericResourceStudent readFrom(Class<GenericResourceStudent> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
26 {
27 BufferedReader br = null;
28 try
29 {
30 br = new BufferedReader(new InputStreamReader(entityStream));
31 return new GenericResourceStudent(br.readLine());
32 }
33 catch (Exception e)
34 {
35 throw new RuntimeException("Unable to parse student.", e);
36 }
37 }
38 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/GenericResourceStudentWriter.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Produces;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import javax.ws.rs.ext.Provider;
8 import java.io.IOException;
9 import java.io.OutputStream;
10 import java.io.OutputStreamWriter;
11 import java.lang.annotation.Annotation;
12 import java.lang.reflect.Type;
13
14 @Provider
15 @Produces("application/student")
16 public class GenericResourceStudentWriter implements MessageBodyWriter<GenericResourceStudent>
17 {
18
19 public long getSize(GenericResourceStudent t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
20 {
21 return t.getName().length();
22 }
23
24 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
25 {
26 return true;
27 }
28
29 public void writeTo(GenericResourceStudent t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
30 {
31 OutputStreamWriter writer = new OutputStreamWriter(entityStream);
32 writer.write(t.getName());
33 writer.flush();
34 }
35 }
+0
-174
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/HttpHeadersResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.PUT;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.core.Context;
8 import javax.ws.rs.core.Cookie;
9 import javax.ws.rs.core.HttpHeaders;
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.MultivaluedMap;
12 import java.io.PrintWriter;
13 import java.io.StringWriter;
14 import java.util.Arrays;
15 import java.util.List;
16 import java.util.Locale;
17 import java.util.Map;
18 import java.util.Set;
19
20 @Path(value = "/HeadersTest")
21 public class HttpHeadersResource {
22 private static Logger logger = Logger.getLogger(HttpHeadersResource.class);
23
24 @Context
25 HttpHeaders hs;
26 StringBuffer sb;
27
28 @GET
29 @Path("/headers")
30 public String headersGet() {
31 sb = new StringBuffer();
32 List<String> myHeaders = Arrays.asList("Accept", "Content-Type");
33
34 try {
35 MultivaluedMap<String, String> rqhdrs = hs.getRequestHeaders();
36 Set<String> keys = rqhdrs.keySet();
37 sb.append("getRequestHeaders= ");
38 for (String header : myHeaders) {
39 if (keys.contains(header)) {
40 sb.append("Found " + header + ": " +
41 hs.getRequestHeader(header) + "; ");
42 }
43 }
44 } catch (Throwable ex) {
45 sb.append("Unexpected exception thrown in getRequestHeaders: " +
46 ex.getMessage());
47 StringWriter errors = new StringWriter();
48 ex.printStackTrace(new PrintWriter(errors));
49 logger.error(errors.toString());
50 }
51 return sb.toString();
52 }
53
54 @GET
55 @Path("/acl")
56 public String aclGet() {
57 sb = new StringBuffer();
58 try {
59 sb.append("Accept-Language");
60
61 List<Locale> acl = hs.getAcceptableLanguages();
62 sb.append("getLanguage= ");
63 for (Locale tmp : acl) {
64 sb.append(tmp.toString() + "; ");
65 }
66 } catch (Throwable ex) {
67 sb.append("Unexpected exception thrown in getAcceptableLanguages: " +
68 ex.getMessage());
69 StringWriter errors = new StringWriter();
70 ex.printStackTrace(new PrintWriter(errors));
71 logger.error(errors.toString());
72 }
73 return sb.toString();
74 }
75
76 @GET
77 @Path("/amt")
78 public String amtGet() {
79 sb = new StringBuffer();
80 try {
81 sb.append("getAcceptableMediaTypes");
82 List<MediaType> acmts = hs.getAcceptableMediaTypes();
83
84 for (MediaType mt : acmts) {
85 sb.append(mt.getType());
86 sb.append("/");
87 sb.append(mt.getSubtype());
88 }
89 } catch (Throwable ex) {
90 sb.append("Unexpected exception thrown: " + ex.getMessage());
91 StringWriter errors = new StringWriter();
92 ex.printStackTrace(new PrintWriter(errors));
93 logger.error(errors.toString());
94 }
95 return sb.toString();
96 }
97
98 @GET
99 @Path("/mt")
100 public String mtGet() {
101 sb = new StringBuffer();
102
103 try {
104 sb.append("getMediaType");
105 MediaType mt = hs.getMediaType();
106 if (mt != null) {
107 sb.append(mt.getType());
108 sb.append("/");
109 sb.append(mt.getSubtype());
110 sb.append(" ");
111
112 Map<String, String> pmap =
113 mt.getParameters();
114
115 sb.append("MediaType size=" + pmap.size());
116
117 for (Map.Entry<String, String> entry : pmap.entrySet()) {
118 sb.append("Key " + entry.getKey() + "; Value " + entry.getValue());
119 }
120
121 sb.append(mt.toString());
122
123 sb.append("MediaType= " + mt.toString() + "; ");
124 } else {
125 sb.append("MediaType= null; ");
126 }
127 } catch (Throwable ex) {
128 sb.append("Unexpected exception thrown: " + ex.getMessage());
129 StringWriter errors = new StringWriter();
130 ex.printStackTrace(new PrintWriter(errors));
131 logger.error(errors.toString());
132 }
133 return sb.toString();
134 }
135
136 @GET
137 @Path("/cookie")
138 public String cookieGet() {
139 sb = new StringBuffer();
140
141 try {
142 sb.append("getCookies= ");
143 Map<String, Cookie> cookies = hs.getCookies();
144 sb.append("Cookie Size=" + cookies.size());
145
146 for (Map.Entry<String, Cookie> tmp : cookies.entrySet()) {
147 sb.append(tmp.getKey() + ": " + tmp.getValue() + "; ");
148 Cookie c = cookies.get("name1");
149 sb.append("Cookie Name=" + c.getName());
150 sb.append("Cookie Value=" + c.getValue());
151 sb.append("Cookie Path=" + c.getPath());
152 sb.append("Cookie Domain=" + c.getDomain());
153 sb.append("Cookie Version=" + c.getVersion());
154
155 }
156 } catch (Throwable ex) {
157 sb.append("Unexpected exception thrown: " + ex.getMessage());
158 StringWriter errors = new StringWriter();
159 ex.printStackTrace(new PrintWriter(errors));
160 logger.error(errors.toString());
161 }
162
163 return sb.toString();
164 }
165
166 @PUT
167 public String headersPlainPut() {
168 sb = new StringBuffer();
169 sb.append("Content-Language");
170 sb.append(hs.getLanguage());
171 return sb.toString();
172 }
173 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/InheritenceParentResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Produces;
4
5 public interface InheritenceParentResource {
6
7 @GET
8 @Produces("text/plain")
9 public String firstest();
10
11 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/InheritenceParentResourceImpl.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path(value = "/InheritanceTest")
5 public class InheritenceParentResourceImpl implements InheritenceParentResource {
6
7 public String firstest() {
8 return "First";
9 }
10 }
+0
-30
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/LogHandler.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import java.util.logging.Handler;
3 import java.util.logging.LogRecord;
4
5 public class LogHandler extends Handler {
6
7 public static final String MESSAGE_CODE = "RESTEASY002142";
8
9 private static int messagesLogged = 0;
10
11 @Override
12 public void publish(LogRecord record) {
13 if (record.getMessage().contains(MESSAGE_CODE)) {
14 messagesLogged++;
15 }
16 }
17
18 @Override
19 public void flush() {
20 }
21
22 @Override
23 public void close() throws SecurityException {
24 }
25
26 public int getMessagesLogged() {
27 return messagesLogged;
28 }
29 }
+0
-71
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/MatchedResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7
8 @Path("/")
9 public class MatchedResource {
10 @Path("/test1/{id}.xml.{lang}")
11 @GET
12 public String getComplex() {
13 return "complex";
14 }
15
16 @Path("/test1/{id}")
17 @GET
18 public String getSimple() {
19 return "simple";
20 }
21
22 @Path("/test2/{id}")
23 @GET
24 public String getSimple2() {
25 return "simple2";
26 }
27
28 @Path("/test2/{id}.xml.{lang}")
29 @GET
30 public String getComplex2() {
31 return "complex2";
32 }
33
34 @Path("match")
35 @Produces("*/*;qs=0.0")
36 @GET
37 public String getObj() {
38 return "*/*";
39 }
40
41 @Path("match")
42 @Produces("application/xml")
43 @GET
44 public String getObjXml() {
45 return "<xml/>";
46 }
47
48 @Path("match")
49 @Produces("application/json")
50 @GET
51 public String getObjJson() {
52 return "{ \"name\" : \"bill\" }";
53 }
54
55 @Path("start")
56 @POST
57 @Produces("text/plain")
58 public String start() {
59 return "started";
60 }
61
62 @Path("start")
63 @Consumes("application/xml")
64 @POST
65 @Produces("text/plain")
66 public String start(String xml) {
67 return xml;
68 }
69
70 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/MultiInterfaceResLocatorIntf1.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2
3 import javax.ws.rs.GET;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6
7 public interface MultiInterfaceResLocatorIntf1 {
8 @GET
9 @Produces("text/plain")
10 @Path("hello1")
11 String resourceMethod1();
12 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/MultiInterfaceResLocatorIntf2.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 public interface MultiInterfaceResLocatorIntf2 {
7 @GET
8 @Produces("text/plain")
9 @Path("hello2")
10 String resourceMethod2();
11 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/MultiInterfaceResLocatorResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.Produces;
4
5 @Path("/")
6 public class MultiInterfaceResLocatorResource {
7 @Produces("text/plain")
8 @Path("test")
9 public Object resourceLocator() {
10 return new MultiInterfaceResLocatorSubresource();
11 }
12 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/MultiInterfaceResLocatorSubresource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("")
5 public class MultiInterfaceResLocatorSubresource implements MultiInterfaceResLocatorIntf1, MultiInterfaceResLocatorIntf2 {
6 @Override
7 public String resourceMethod1() {
8 return "resourceMethod1";
9 }
10
11 @Override
12 public String resourceMethod2() {
13 return "resourceMethod2";
14 }
15 }
+0
-73
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/MultipleEndpointsWarningResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import java.util.logging.LogManager;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.PUT;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
11
12 @Path("/")
13 public class MultipleEndpointsWarningResource {
14
15 @SuppressWarnings("unused")
16 private static String MESSAGE_CODE = "RESTEASY002142";
17 private LogHandler logHandler = new LogHandler();
18
19 @Path("setup")
20 @GET
21 public void setup()
22 {
23 LogManager.getLogManager().getLogger(LogMessages.LOGGER.getClass().getPackage().getName()).addHandler(logHandler);
24 }
25
26 @Path("teardown")
27 @GET
28 public void teardown()
29 {
30 LogManager.getLogManager().getLogger(LogMessages.LOGGER.getClass().getPackage().getName()).removeHandler(logHandler);
31 }
32
33 @Path("unique")
34 @GET
35 @Produces("text/plain")
36 public int unique() throws Exception {
37 return logHandler.getMessagesLogged();
38 }
39
40 @Path("verbs")
41 @GET
42 @Produces("text/plain")
43 public int getVerb() throws Exception {
44 return logHandler.getMessagesLogged();
45 }
46
47 @Path("verbs")
48 @POST
49 @Produces("text/plain")
50 public int postVerb() throws Exception {
51 return logHandler.getMessagesLogged();
52 }
53
54 @Path("verbs")
55 @PUT
56 @Produces("text/plain")
57 public int putVerb() throws Exception {
58 return logHandler.getMessagesLogged();
59 }
60
61 @Path("duplicate")
62 @GET
63 public int duplicate1() throws Exception {
64 return logHandler.getMessagesLogged();
65 }
66
67 @Path("duplicate")
68 @GET
69 public int duplicate2() throws Exception {
70 return logHandler.getMessagesLogged();
71 }
72 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ParameterSubResConcreteSubImpl.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public class ParameterSubResConcreteSubImpl extends ParameterSubResSubImpl<Integer> {
3 public ParameterSubResConcreteSubImpl(final String path) {
4 super(path);
5 }
6 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ParameterSubResDoubleInterface.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public interface ParameterSubResDoubleInterface extends ParameterSubResGenericInterface<Double> {
3 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ParameterSubResGenericInterface.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.QueryParam;
4 import java.util.List;
5
6 public interface ParameterSubResGenericInterface<T> {
7 @GET
8 String get(@QueryParam("foo") List<T> params);
9 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ParameterSubResGenericSub.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Path;
3 import java.lang.reflect.InvocationHandler;
4 import java.lang.reflect.Method;
5 import java.lang.reflect.Proxy;
6 import java.util.List;
7
8 @Path("generic")
9 public class ParameterSubResGenericSub {
10 @SuppressWarnings(value = "unchecked")
11 @Path("sub")
12 public ParameterSubResDoubleInterface doit() {
13 InvocationHandler handler = new InvocationHandler() {
14 @Override
15 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
16 List<Double> list = (List<Double>) args[0];
17 return list.get(0).toString();
18 }
19 };
20 Class[] intfs = {ParameterSubResDoubleInterface.class};
21 return (ParameterSubResDoubleInterface) Proxy.newProxyInstance(ParameterSubResGenericSub.class.getClassLoader(), intfs, handler);
22 }
23 }
+0
-8
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ParameterSubResInternalInterface.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.PUT;
3
4 public interface ParameterSubResInternalInterface<T extends Number> {
5 @PUT
6 void foo(T value);
7 }
+0
-9
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ParameterSubResRoot.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.PathParam;
4
5 public interface ParameterSubResRoot {
6 @Path("sub/{path}")
7 ParameterSubResSub getSub(@PathParam("path") String path);
8 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ParameterSubResRootImpl.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2
3 import javax.ws.rs.Path;
4
5 @Path("/path")
6 public class ParameterSubResRootImpl implements ParameterSubResRoot {
7 @Override
8 public ParameterSubResSubImpl<Integer> getSub(String path) {
9 return new ParameterSubResSubImpl<Integer>(path) {
10 };
11 }
12
13 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ParameterSubResSub.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Produces;
4
5 public interface ParameterSubResSub {
6 @GET
7 @Produces("text/plain")
8 String get();
9 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ParameterSubResSubImpl.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3
4 public class ParameterSubResSubImpl<T extends Number> implements ParameterSubResSub, ParameterSubResInternalInterface<T> {
5 private static Logger logger = Logger.getLogger(ParameterSubResSubImpl.class);
6
7 private final String path;
8
9 public ParameterSubResSubImpl(final String path) {
10 this.path = path;
11 }
12
13 @Override
14 public String get() {
15 return "Boo! - " + path;
16 }
17
18 @Override
19 public void foo(T value) {
20 logger.info("foo: " + value);
21 }
22
23 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ReponseInfoResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.test.resource.basic.ReponseInfoTest;
4 import org.jboss.resteasy.util.HttpHeaderNames;
5 import org.jboss.resteasy.utils.PortProviderUtil;
6 import org.junit.Assert;
7
8 import javax.ws.rs.GET;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.QueryParam;
11 import javax.ws.rs.core.Response;
12 import java.net.URI;
13
14
15 @Path("/")
16 public class ReponseInfoResource {
17 private static Logger logger = Logger.getLogger(ReponseInfoResource.class);
18
19 @Path("/simple")
20 @GET
21 public String get(@QueryParam("abs") String abs) {
22 logger.info("abs query: " + abs);
23 URI base;
24 if (abs == null) {
25 base = PortProviderUtil.createURI("/new/one", ReponseInfoTest.class.getSimpleName());
26 } else {
27 base = PortProviderUtil.createURI("/" + abs + "/new/one", ReponseInfoTest.class.getSimpleName());
28 }
29 Response response = Response.temporaryRedirect(URI.create("new/one")).build();
30 URI uri = (URI) response.getMetadata().getFirst(HttpHeaderNames.LOCATION);
31 logger.info("Location uri: " + uri);
32 Assert.assertEquals("Wrong path from URI", base.getPath(), uri.getPath());
33 return "CONTENT";
34 }
35 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceInfoInjectionFilter.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.container.ContainerRequestContext;
3 import javax.ws.rs.container.ContainerResponseContext;
4 import javax.ws.rs.container.ContainerResponseFilter;
5 import javax.ws.rs.container.ResourceInfo;
6 import javax.ws.rs.core.Context;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.ext.Provider;
9 import java.io.IOException;
10 import java.lang.reflect.Method;
11
12 @Provider
13 public class ResourceInfoInjectionFilter implements ContainerResponseFilter {
14 @Context
15 private ResourceInfo resourceInfo;
16
17 @Override
18 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
19 Method method = resourceInfo.getResourceMethod();
20 if (method == null) {
21 responseContext.setStatus(responseContext.getStatus() * 2);
22 } else {
23 responseContext.setEntity(method.getName(), null, MediaType.TEXT_PLAIN_TYPE);
24 }
25 }
26 }
+0
-70
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceInfoInjectionResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2
3 import org.jboss.logging.Logger;
4 import javax.servlet.ReadListener;
5 import javax.servlet.ServletInputStream;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.ws.rs.GET;
8 import javax.ws.rs.POST;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.container.AsyncResponse;
11 import javax.ws.rs.container.Suspended;
12 import javax.ws.rs.core.Context;
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15
16 @Path("")
17 public class ResourceInfoInjectionResource {
18 protected static final Logger logger = Logger.getLogger(ResourceInfoInjectionResource.class.getName());
19
20 @Context
21 private HttpServletRequest request;
22
23 @GET
24 @Path("test")
25 public String test() {
26 return "abc";
27 }
28
29 @POST
30 @Path("async")
31 public void async(@Suspended final AsyncResponse async) throws IOException {
32 logger.info("Start async");
33 final ServletInputStream inputStream = request.getInputStream();
34 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
35
36 inputStream.setReadListener(new ReadListener() {
37 @Override
38 public void onDataAvailable() throws IOException {
39 logger.info("Start onDataAvailable");
40 // copy input stream
41 byte[] buffer = new byte[4096];
42 int n1;
43 while (inputStream.isReady()) {
44 n1 = inputStream.read(buffer);
45 outputStream.write(buffer, 0, n1);
46 }
47 logger.info("End onDataAvailable");
48 }
49
50 @Override
51 public void onAllDataRead() throws IOException {
52 logger.info("Start onAllDataRead");
53 inputStream.close();
54 outputStream.flush();
55 outputStream.close();
56 async.resume(outputStream.toString("UTF-8"));
57 logger.info("End onAllDataRead");
58 }
59
60 @Override
61 public void onError(Throwable t) {
62 logger.info("Start onError");
63 async.resume(t);
64 logger.info("End onError");
65 }
66 });
67 logger.info("End async");
68 }
69 }
+0
-8
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorAbstractAnnotationFreeResouce.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public abstract class ResourceLocatorAbstractAnnotationFreeResouce implements ResourceLocatorRootInterface {
3
4 public String get() {
5 return "got";
6 }
7 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorAnnotationFreeSubResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public class ResourceLocatorAnnotationFreeSubResource extends ResourceLocatorAbstractAnnotationFreeResouce implements ResourceLocatorSubInterface {
3
4 public String post(String s) {
5 return "posted: " + s;
6 }
7
8 public Object getSubSubResource(String id) {
9 return null;
10 }
11 }
+0
-46
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorBaseResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import java.lang.reflect.InvocationHandler;
3 import java.lang.reflect.Method;
4 import java.lang.reflect.Proxy;
5 import java.util.List;
6
7 import javax.ws.rs.Path;
8 import javax.ws.rs.PathParam;
9 import javax.ws.rs.core.Context;
10 import javax.ws.rs.core.UriInfo;
11
12 import org.junit.Assert;
13
14 @Path("/")
15 public class ResourceLocatorBaseResource {
16
17 @Path("base/{param}/resources")
18 public Object getSubresource(@PathParam("param") String param, @Context UriInfo uri) {
19 System.out.println("Here in BaseResource");
20 Assert.assertEquals("1", param);
21 List<String> matchedURIs = uri.getMatchedURIs();
22 Assert.assertEquals(2, matchedURIs.size());
23 Assert.assertEquals("base/1/resources", matchedURIs.get(0));
24 Assert.assertEquals("", matchedURIs.get(1));
25 for (String ancestor : matchedURIs) System.out.println(" " + ancestor);
26
27 System.out.println("Uri Ancesstors Object for Subresource.doGet():");
28 Assert.assertEquals(1, uri.getMatchedResources().size());
29 Assert.assertEquals(ResourceLocatorBaseResource.class, uri.getMatchedResources().get(0).getClass());
30 return new ResourceLocatorSubresource();
31 }
32
33 @Path("proxy")
34 public ResourceLocatorSubresource3Interface sub3() {
35 return (ResourceLocatorSubresource3Interface) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[]{ResourceLocatorSubresource3Interface.class}, new InvocationHandler()
36 {
37 @Override
38 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
39 {
40 return method.invoke(new ResourceLocatorSubresource3(), args);
41 }
42 });
43 }
44
45 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorCollectionResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("/collection")
5 public class ResourceLocatorCollectionResource {
6
7 @Path("annotation_free_subresource")
8 public Object getAnnotationFreeSubResource() {
9 return new ResourceLocatorAnnotationFreeSubResource();
10 }
11 }
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorDirectory.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.DELETE;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5
6 @Path("/directory")
7 public class ResourceLocatorDirectory {
8
9 @Path("/receivers/{id}")
10 public ResourceLocatorQueueReceiver getReceiver(@PathParam("id") String id) {
11 return new ResourceLocatorQueueReceiver();
12 }
13
14 @DELETE
15 @Path("/receivers/{id}")
16 public String closeReceiver(@PathParam("id") String id) throws Exception {
17 return ResourceLocatorDirectory.class.getName();
18 }
19 }
+0
-5
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorQueueReceiver.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public class ResourceLocatorQueueReceiver extends ResourceLocatorReceiver {
3
4 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorReceiver.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 public class ResourceLocatorReceiver {
6
7 @Path("/head")
8 @GET
9 public String get() {
10 return this.getClass().getName();
11 }
12 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorRootInterface.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.MediaType;
7
8 @Produces(MediaType.TEXT_PLAIN)
9 public interface ResourceLocatorRootInterface {
10
11 @GET
12 String get();
13
14 @Path("{id}")
15 Object getSubSubResource(@PathParam("id") String id);
16 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorSubInterface.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.MediaType;
6
7 @Produces(MediaType.TEXT_PLAIN)
8 public interface ResourceLocatorSubInterface extends ResourceLocatorRootInterface {
9
10 @POST
11 @Consumes(MediaType.TEXT_PLAIN)
12 String post(String s);
13 }
+0
-48
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorSubresource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import java.util.List;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.core.Context;
7 import javax.ws.rs.core.UriInfo;
8
9 import org.junit.Assert;
10
11 public class ResourceLocatorSubresource {
12
13 @GET
14 public String doGet(@Context UriInfo uri) {
15 System.out.println("Uri Ancesstors for Subresource.doGet():");
16 List<String> matchedURIs = uri.getMatchedURIs();
17 Assert.assertEquals(2, matchedURIs.size());
18 Assert.assertEquals("base/1/resources", matchedURIs.get(0));
19 Assert.assertEquals("", matchedURIs.get(1));
20 for (String ancestor : matchedURIs) System.out.println(" " + ancestor);
21
22 System.out.println("Uri Ancesstors Object for Subresource.doGet():");
23 Assert.assertEquals(2, uri.getMatchedResources().size());
24 Assert.assertEquals(ResourceLocatorSubresource.class, uri.getMatchedResources().get(0).getClass());
25 Assert.assertEquals(ResourceLocatorBaseResource.class, uri.getMatchedResources().get(1).getClass());
26 for (Object ancestor : uri.getMatchedResources()) System.out.println(" " + ancestor.getClass().getName());
27 return this.getClass().getName();
28 }
29
30 @Path("/subresource2")
31 public Object getSubresource2(@Context UriInfo uri) {
32 System.out.println("Uri Ancesstors for Subresource.getSubresource2():");
33 List<String> matchedURIs = uri.getMatchedURIs();
34 Assert.assertEquals(3, matchedURIs.size());
35 Assert.assertEquals("base/1/resources/subresource2", matchedURIs.get(0));
36 Assert.assertEquals("base/1/resources", matchedURIs.get(1));
37 Assert.assertEquals("", matchedURIs.get(2));
38 for (String ancestor : matchedURIs) System.out.println(" " + ancestor);
39
40 System.out.println("Uri Ancesstors Object for Subresource.getSubresource2():");
41 Assert.assertEquals(2, uri.getMatchedResources().size());
42 Assert.assertEquals(ResourceLocatorSubresource.class, uri.getMatchedResources().get(0).getClass());
43 Assert.assertEquals(ResourceLocatorBaseResource.class, uri.getMatchedResources().get(1).getClass());
44 for (Object ancestor : uri.getMatchedResources()) System.out.println(" " + ancestor.getClass().getName());
45 return new ResourceLocatorSubresource2();
46 }
47 }
+0
-34
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorSubresource2.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.core.Context;
6 import javax.ws.rs.core.UriInfo;
7
8 import org.junit.Assert;
9
10 public class ResourceLocatorSubresource2{
11
12 @GET
13 @Path("stuff/{param}/bar")
14 public String doGet(@PathParam("param") String param, @Context UriInfo uri) {
15 System.out.println("Uri Ancesstors for Subresource2.doGet():");
16 Assert.assertEquals(4, uri.getMatchedURIs().size());
17 Assert.assertEquals("base/1/resources/subresource2/stuff/2/bar", uri.getMatchedURIs().get(0));
18 Assert.assertEquals("base/1/resources/subresource2", uri.getMatchedURIs().get(1));
19 Assert.assertEquals("base/1/resources", uri.getMatchedURIs().get(2));
20 Assert.assertEquals("", uri.getMatchedURIs().get(3));
21 for (String ancestor : uri.getMatchedURIs()) System.out.println(" " + ancestor);
22
23
24 System.out.println("Uri Ancesstors Object for Subresource2.doGet():");
25 Assert.assertEquals(3, uri.getMatchedResources().size());
26 Assert.assertEquals(ResourceLocatorSubresource2.class, uri.getMatchedResources().get(0).getClass());
27 Assert.assertEquals(ResourceLocatorSubresource.class, uri.getMatchedResources().get(1).getClass());
28 Assert.assertEquals(ResourceLocatorBaseResource.class, uri.getMatchedResources().get(2).getClass());
29 for (Object ancestor : uri.getMatchedResources()) System.out.println(" " + ancestor.getClass().getName());
30 Assert.assertEquals("2", param);
31 return this.getClass().getName() + "-" + param;
32 }
33 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorSubresource3.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import java.util.List;
3
4 import org.junit.Assert;
5
6 public class ResourceLocatorSubresource3 implements ResourceLocatorSubresource3Interface {
7
8 @SuppressWarnings("unused")
9 @Override
10 public String get(List<Double> params)
11 {
12 Assert.assertNotNull(params);
13 Assert.assertEquals(2, params.size());
14 double p1 = params.get(0);
15 double p2 = params.get(1);
16 return "Subresource3";
17 }
18 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ResourceLocatorSubresource3Interface.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import java.util.List;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.QueryParam;
7
8 public interface ResourceLocatorSubresource3Interface {
9
10 @GET
11 @Path("3")
12 String get(@QueryParam("foo") List<Double> params);
13 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ScanProxy.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/test")
7 public interface ScanProxy {
8 @Path("/subrsource")
9 ScanSubresource doit();
10
11 @Path("/doit")
12 @GET
13 @Produces("text/plain")
14 String get();
15 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ScanResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public class ScanResource implements ScanProxy {
3 public ScanSubresource doit() {
4 return new ScanSubresource();
5 }
6
7 public String get() {
8 return "hello world";
9 }
10 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/ScanSubresource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 public class ScanSubresource {
7 @Path("doit")
8 @GET
9 @Produces("text/plain")
10 public String get() {
11 return "subresource-doit";
12 }
13 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SpecialResourceApiResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.PUT;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.core.Context;
10 import javax.ws.rs.core.HttpHeaders;
11
12 @Path("/{api:(?i:api)}")
13 public class SpecialResourceApiResource {
14 private static Logger logger = Logger.getLogger(SpecialResourceApiResource.class);
15
16 @Path("/{func:(?i:func)}")
17 @GET
18 @Produces("text/plain")
19 public String func() {
20 return "hello";
21 }
22
23 @PUT
24 public void put(@Context HttpHeaders headers, String val) {
25 logger.info(headers.getMediaType());
26 Assert.assertEquals("Wrong request content", val, "hello");
27 }
28 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SpecialResourceDeleteResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.DELETE;
6 import javax.ws.rs.Path;
7
8 @Path("/delete")
9 public class SpecialResourceDeleteResource {
10 @DELETE
11 @Consumes("text/plain")
12 public void delete(String msg) {
13 Assert.assertEquals("Wrong request content", "hello", msg);
14 }
15 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SpecialResourceStreamResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import java.io.IOException;
6 import java.io.InputStream;
7
8 @Path("/inputstream")
9 public class SpecialResourceStreamResource {
10 @POST
11 @Path("/test/{type}")
12 public void test(InputStream is, @PathParam("type") final String type) throws IOException {
13
14 }
15 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SpecialResourceSubFactory.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.resteasy.core.MediaTypeMap;
3 import org.jboss.resteasy.spi.ResteasyProviderFactory;
4
5 import javax.ws.rs.ext.MessageBodyReader;
6
7 public class SpecialResourceSubFactory extends ResteasyProviderFactory {
8 public MediaTypeMap<SortedKey<MessageBodyReader>> getMBRMap() {
9 return serverMessageBodyReaders;
10 }
11 }
+0
-46
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SubResourceLocatorBaseCrudService.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.DELETE;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.PUT;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.PathParam;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.core.MediaType;
11 import java.util.List;
12
13 public interface SubResourceLocatorBaseCrudService<T> {
14
15 @GET
16 @Path("/content/{id}")
17 @Produces(MediaType.APPLICATION_JSON)
18 T getContent(
19 @PathParam("id")
20 String id);
21
22 @POST
23 @Path("/add")
24 @Produces(MediaType.APPLICATION_JSON)
25 @Consumes(MediaType.APPLICATION_JSON)
26 T add(T object);
27
28 @GET
29 @Path("/all")
30 @Produces(MediaType.APPLICATION_JSON)
31 List<T> get();
32
33 @PUT
34 @Path("/update")
35 @Produces(MediaType.APPLICATION_JSON)
36 @Consumes(MediaType.APPLICATION_JSON)
37 T update(T object);
38
39 @DELETE
40 @Path("/delete/{id}")
41 @Produces(MediaType.TEXT_PLAIN)
42 Boolean delete(
43 @PathParam("id")
44 String id);
45 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SubResourceLocatorBaseService.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.Produces;
6
7 public interface SubResourceLocatorBaseService extends SubResourceLocatorBaseCrudService<SubResourceLocatorOhaUserModel> {
8
9
10 @GET
11 @Produces("text/plain")
12 @Path("data/ada/{user}")
13 SubResourceLocatorOhaUserModel getUserDataByAdaId(
14 @PathParam("user")
15 String adaId);
16 }
+0
-9
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SubResourceLocatorFoo.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.HeaderParam;
4
5 public interface SubResourceLocatorFoo<T> {
6 @GET
7 T getFoo(@HeaderParam("foo") String val);
8 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SubResourceLocatorImpFoo.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Path;
3
4 @Path("blah")
5 public class SubResourceLocatorImpFoo implements SubResourceLocatorFoo {
6 @Override
7 public Object getFoo(String val) {
8 return "hello";
9 }
10 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SubResourceLocatorOhaUserModel.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 public class SubResourceLocatorOhaUserModel {
3 private String username;
4
5 public SubResourceLocatorOhaUserModel(final String username) {
6 this.username = username;
7 }
8
9 @Override
10 public String toString() {
11 return username;
12 }
13 }
+0
-81
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SubResourceLocatorPlatformServiceImpl.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.PathParam;
3 import javax.ws.rs.QueryParam;
4 import java.util.List;
5
6 public class SubResourceLocatorPlatformServiceImpl implements SubResourceLocatorPlatformServiceResource {
7 @Override
8 public SubResourceLocatorUserResource getUserService(String entity, String ticket, String userId) {
9 return new SubResourceLocatorUserResource() {
10 @Override
11 public List<SubResourceLocatorOhaUserModel> getByNameSurname(@PathParam("name") String name, @PathParam("surname") String surname) {
12 return null;
13 }
14
15 @Override
16 public SubResourceLocatorOhaUserModel getUserByMail(@PathParam("mail") String mail) {
17 return null;
18 }
19
20 @Override
21 public Boolean update(@PathParam("id") String id, @QueryParam("adaId") String adaId, @QueryParam("name") String name, @QueryParam("surname") String surname, @QueryParam("address") String address, @QueryParam("city") String city, @QueryParam("country") String country, @QueryParam("zipcode") String zipcode, @QueryParam("email") String email, @QueryParam("phone") String phone, @QueryParam("phone") String timezone) {
22 return null;
23 }
24
25 @Override
26 public Boolean updatePassword(@PathParam("username") String username, List<String> passwords) {
27 return null;
28 }
29
30 @Override
31 public Boolean create(@QueryParam("email") String email, @QueryParam("password") String password, @QueryParam("username") String username) {
32 return null;
33 }
34
35 @Override
36 public Boolean showHelp(@PathParam("user") long userId) {
37 return null;
38 }
39
40 @Override
41 public Boolean setShowHelp(@PathParam("user") long userId, @PathParam("show") boolean showHelp) {
42 return null;
43 }
44
45 @Override
46 public void createJabberAccounts() {
47 }
48
49 @Override
50 public SubResourceLocatorOhaUserModel getContent(String id) {
51 return null;
52 }
53
54 @Override
55 public SubResourceLocatorOhaUserModel add(SubResourceLocatorOhaUserModel object) {
56 return null;
57 }
58
59 @Override
60 public List<SubResourceLocatorOhaUserModel> get() {
61 return null;
62 }
63
64 @Override
65 public SubResourceLocatorOhaUserModel update(SubResourceLocatorOhaUserModel object) {
66 return null;
67 }
68
69 @Override
70 public Boolean delete(String id) {
71 return null;
72 }
73
74 @Override
75 public SubResourceLocatorOhaUserModel getUserDataByAdaId(String adaId) {
76 return new SubResourceLocatorOhaUserModel("bill");
77 }
78 };
79 }
80 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SubResourceLocatorPlatformServiceResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.HeaderParam;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5
6 @Path("/platform")
7 public interface SubResourceLocatorPlatformServiceResource {
8
9 @Path("/users/{user}")
10 SubResourceLocatorUserResource getUserService(
11 @HeaderParam("entity")
12 String entity,
13 @HeaderParam("ticket")
14 String ticket,
15 @PathParam("user")
16 String userId
17 );
18 }
+0
-139
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/SubResourceLocatorUserResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.DELETE;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.PUT;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.PathParam;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.QueryParam;
11 import javax.ws.rs.core.MediaType;
12 import java.util.List;
13
14 @Path("/users")
15 public interface SubResourceLocatorUserResource extends SubResourceLocatorBaseService {
16
17 @GET
18 @Path("/content/{id}")
19 @Produces(MediaType.APPLICATION_JSON)
20 SubResourceLocatorOhaUserModel getContent(
21 @PathParam("id")
22 String id);
23
24 @POST
25 @Path("/add")
26 @Produces(MediaType.APPLICATION_JSON)
27 @Consumes(MediaType.APPLICATION_JSON)
28 SubResourceLocatorOhaUserModel add(SubResourceLocatorOhaUserModel object);
29
30 @GET
31 @Path("/all")
32 @Produces(MediaType.APPLICATION_JSON)
33 List<SubResourceLocatorOhaUserModel> get();
34
35 @PUT
36 @Path("/update")
37 @Produces(MediaType.APPLICATION_JSON)
38 @Consumes(MediaType.APPLICATION_JSON)
39 SubResourceLocatorOhaUserModel update(SubResourceLocatorOhaUserModel object);
40
41 @DELETE
42 @Path("/delete/{id}")
43 @Produces(MediaType.TEXT_PLAIN)
44 Boolean delete(
45 @PathParam("id")
46 String id);
47
48
49 @GET
50 @Path("/getbynamesurname/{name}/{surname}")
51 @Produces(MediaType.APPLICATION_JSON)
52 List<SubResourceLocatorOhaUserModel> getByNameSurname(
53 @PathParam("name")
54 String name,
55 @PathParam("surname")
56 String surname
57 );
58
59 @GET
60 @Path("/getuserbymail/{mail}")
61 @Produces(MediaType.APPLICATION_JSON)
62 SubResourceLocatorOhaUserModel getUserByMail(
63 @PathParam("mail")
64 String mail
65 );
66
67
68 @POST
69 @Path("/update/{id}")
70 @Produces(MediaType.TEXT_PLAIN)
71 Boolean update(
72 @PathParam("id")
73 String id,
74 @QueryParam("adaId")
75 String adaId,
76 @QueryParam("name")
77 String name,
78 @QueryParam("surname")
79 String surname,
80 @QueryParam("address")
81 String address,
82 @QueryParam("city")
83 String city,
84 @QueryParam("country")
85 String country,
86 @QueryParam("zipcode")
87 String zipcode,
88 @QueryParam("email")
89 String email,
90 @QueryParam("phone")
91 String phone,
92 @QueryParam("phone")
93 String timezone);
94
95 @POST
96 @Path("/updatepassword/{username}")
97 @Produces(MediaType.TEXT_PLAIN)
98 @Consumes(MediaType.APPLICATION_JSON)
99 Boolean updatePassword(
100 @PathParam("username")
101 String username,
102 List<String> passwords);
103
104
105 @POST
106 @Path("/createuser")
107 @Produces(MediaType.APPLICATION_JSON)
108 Boolean create(
109 @QueryParam("email")
110 String email,
111 @QueryParam("password")
112 String password,
113 @QueryParam("username")
114 String username);
115
116 @GET
117 @Path("/show-help/{user}")
118 @Produces(MediaType.TEXT_PLAIN)
119 Boolean showHelp(
120 @PathParam("user")
121 long userId);
122
123 @PUT
124 @Path("/show-help/{user}/{show}")
125 @Produces(MediaType.TEXT_PLAIN)
126 Boolean setShowHelp(
127 @PathParam("user")
128 long userId,
129 @PathParam("show")
130 boolean showHelp);
131
132
133 @GET
134 @Path("/create-jabber")
135 @Produces(MediaType.TEXT_PLAIN)
136 void createJabberAccounts();
137
138 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/UriInfoEncodedQueryResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.QueryParam;
7 import javax.ws.rs.core.Context;
8 import javax.ws.rs.core.UriInfo;
9
10 @Path("/query")
11 public class UriInfoEncodedQueryResource {
12 private static final String ERROR_MSG = "Wrong parameter";
13
14 @GET
15 public String doGet(@QueryParam("a") String a, @Context UriInfo info) {
16 Assert.assertEquals(ERROR_MSG, "a b", a);
17 Assert.assertEquals(ERROR_MSG, "a b", info.getQueryParameters().getFirst("a"));
18 Assert.assertEquals(ERROR_MSG, "a%20b", info.getQueryParameters(false).getFirst("a"));
19 return "content";
20 }
21 }
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/UriInfoEncodedTemplateResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.core.Context;
8 import javax.ws.rs.core.PathSegment;
9 import javax.ws.rs.core.UriInfo;
10 import java.util.List;
11
12 @Path("/{a}/{b}")
13 public class UriInfoEncodedTemplateResource {
14 private static final String ERROR_MSG = "Wrong parameter";
15
16 @GET
17 public String doGet(@PathParam("a") String a, @PathParam("b") String b, @Context UriInfo info) {
18 Assert.assertEquals(ERROR_MSG, "a b", a);
19 Assert.assertEquals(ERROR_MSG, "x y", b);
20 Assert.assertEquals(ERROR_MSG, "a b", info.getPathParameters().getFirst("a"));
21 Assert.assertEquals(ERROR_MSG, "x y", info.getPathParameters().getFirst("b"));
22 Assert.assertEquals(ERROR_MSG, "a%20b", info.getPathParameters(false).getFirst("a"));
23 Assert.assertEquals(ERROR_MSG, "x%20y", info.getPathParameters(false).getFirst("b"));
24
25 List<PathSegment> decoded = info.getPathSegments(true);
26 Assert.assertEquals(ERROR_MSG, decoded.size(), 2);
27 Assert.assertEquals(ERROR_MSG, "a b", decoded.get(0).getPath());
28 Assert.assertEquals(ERROR_MSG, "x y", decoded.get(1).getPath());
29
30 List<PathSegment> encoded = info.getPathSegments(false);
31 Assert.assertEquals(ERROR_MSG, encoded.size(), 2);
32 Assert.assertEquals(ERROR_MSG, "a%20b", encoded.get(0).getPath());
33 Assert.assertEquals(ERROR_MSG, "x%20y", encoded.get(1).getPath());
34 return "content";
35 }
36 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/UriInfoEscapedMatrParamResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.MatrixParam;
6 import javax.ws.rs.Path;
7
8 @Path("/queryEscapedMatrParam")
9 public class UriInfoEscapedMatrParamResource {
10 private static final String ERROR_MSG = "Wrong parameter";
11
12 @GET
13 public String doGet(@MatrixParam("a") String a, @MatrixParam("b") String b, @MatrixParam("c") String c, @MatrixParam("d") String d) {
14 Assert.assertEquals(ERROR_MSG, "a;b", a);
15 Assert.assertEquals(ERROR_MSG, "x/y", b);
16 Assert.assertEquals(ERROR_MSG, "m\\n", c);
17 Assert.assertEquals(ERROR_MSG, "k=l", d);
18 return "content";
19 }
20 }
+0
-139
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/UriInfoQueryParamsResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.QueryParam;
7 import javax.ws.rs.core.Context;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.core.UriInfo;
10 import java.util.Collections;
11 import java.util.List;
12 import java.util.Map;
13
14 @Path("/queryParams")
15 public class UriInfoQueryParamsResource {
16 @GET
17 public String doGet(@QueryParam("a") String a, @Context UriInfo info) {
18 Assert.assertNotNull(info);
19
20 Assert.assertNotNull(info.getQueryParameters());
21 assertNotMutable(info.getQueryParameters());
22
23 return "content";
24 }
25
26 private static void assertNotMutable(MultivaluedMap<String, String> params) {
27
28 final String param = "param";
29 final String key = params.keySet().iterator().next();
30
31 try {
32 params.put(param, Collections.singletonList(param));
33 Assert.fail("mutable UriInfo");
34 } catch (UnsupportedOperationException uoe) {
35 //OK
36 }
37
38 try {
39 params.add(param, param);
40 Assert.fail("mutable UriInfo");
41 } catch (UnsupportedOperationException uoe) {
42 //OK
43 }
44
45 try {
46 params.addAll(param, Collections.singletonList(param));
47 Assert.fail("mutable UriInfo");
48 } catch (UnsupportedOperationException uoe) {
49 //OK
50 }
51
52 try {
53 params.addAll(param, param);
54 Assert.fail("mutable UriInfo");
55 } catch (UnsupportedOperationException uoe) {
56 //OK
57 }
58
59 try {
60 params.addFirst(param, param);
61 Assert.fail("mutable UriInfo");
62 } catch (UnsupportedOperationException uoe) {
63 //OK
64 }
65
66 try {
67 params.putSingle(param, param);
68 Assert.fail("mutable UriInfo");
69 } catch (UnsupportedOperationException uoe) {
70 //OK
71 }
72
73 try {
74 params.entrySet().add(new Map.Entry<String, List<String>>() {
75 @Override
76 public String getKey() {
77 return param;
78 }
79
80 @Override
81 public List<String> getValue() {
82 return Collections.singletonList(param);
83 }
84
85 @Override
86 public List<String> setValue(List<String> value) {
87 return Collections.singletonList(param);
88 }
89 });
90 Assert.fail("mutable UriInfo");
91 } catch (UnsupportedOperationException uoe) {
92 //OK
93 }
94
95 try {
96 params.keySet().add(param);
97 Assert.fail("mutable UriInfo");
98 } catch (UnsupportedOperationException uoe) {
99 //OK
100 }
101
102 try {
103 params.clear();
104 Assert.fail("mutable UriInfo");
105 } catch (UnsupportedOperationException uoe) {
106 //OK
107 }
108
109 try {
110 params.putAll(params);
111 Assert.fail("mutable UriInfo");
112 } catch (UnsupportedOperationException uoe) {
113 //OK
114 }
115
116 try {
117 params.remove(key);
118 Assert.fail("mutable UriInfo");
119 } catch (UnsupportedOperationException uoe) {
120 //OK
121 }
122
123 try {
124 params.remove(null);
125 Assert.fail("mutable UriInfo");
126 } catch (UnsupportedOperationException uoe) {
127 //OK
128 }
129
130 try {
131 params.values().add(Collections.singletonList(param));
132 Assert.fail("mutable UriInfo");
133 } catch (UnsupportedOperationException uoe) {
134 //OK
135 }
136
137 }
138 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/UriInfoRelativizeResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.QueryParam;
6 import javax.ws.rs.core.Context;
7 import javax.ws.rs.core.UriInfo;
8 import java.net.URI;
9
10 @Path("/")
11 public class UriInfoRelativizeResource {
12 @Produces("text/plain")
13 @GET
14 @Path("{path : .*}")
15 public String relativize(@Context UriInfo info, @QueryParam("to") String to) {
16 return info.relativize(URI.create(to)).toString();
17 }
18 }
+0
-59
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/UriInfoSimpleResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.utils.PortProviderUtil;
4 import org.junit.Assert;
5
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.QueryParam;
9 import javax.ws.rs.core.Context;
10 import javax.ws.rs.core.UriInfo;
11 import java.net.URI;
12
13
14
15 @Path("/")
16 public class UriInfoSimpleResource {
17 private static Logger logger = Logger.getLogger(UriInfoSimpleResource.class);
18
19 @Context
20 UriInfo myInfo;
21
22 @Path("/simple")
23 @GET
24 public String get(@Context UriInfo info, @QueryParam("abs") String abs) {
25 logger.info("abs query: " + abs);
26 URI base = null;
27 if (abs == null) {
28 base = PortProviderUtil.createURI("/", UriInfoSimpleResource.class.getSimpleName());
29 } else {
30 base = PortProviderUtil.createURI("/" + abs + "/", UriInfoSimpleResource.class.getSimpleName());
31 }
32
33 logger.info("BASE URI: " + info.getBaseUri());
34 logger.info("Request URI: " + info.getRequestUri());
35 Assert.assertEquals(base.getPath(), info.getBaseUri().getPath());
36 Assert.assertEquals("/simple", info.getPath());
37 return "CONTENT";
38 }
39
40 @Path("/simple/fromField")
41 @GET
42 public String get(@QueryParam("abs") String abs) {
43 logger.info("abs query: " + abs);
44 URI base = null;
45 if (abs == null) {
46 base = PortProviderUtil.createURI("/", UriInfoSimpleResource.class.getSimpleName());
47 } else {
48 base = PortProviderUtil.createURI("/" + abs + "/", UriInfoSimpleResource.class.getSimpleName());
49 }
50
51 logger.info("BASE URI: " + myInfo.getBaseUri());
52 logger.info("Request URI: " + myInfo.getRequestUri());
53 Assert.assertEquals(base.getPath(), myInfo.getBaseUri().getPath());
54 Assert.assertEquals("/simple/fromField", myInfo.getPath());
55 return "CONTENT";
56 }
57
58 }
+0
-58
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/UriInfoSimpleSingletonResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.utils.PortProviderUtil;
4 import org.junit.Assert;
5
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.QueryParam;
9 import javax.ws.rs.core.Context;
10 import javax.ws.rs.core.UriInfo;
11 import java.net.URI;
12
13
14 @Path("/")
15 public class UriInfoSimpleSingletonResource {
16 private static Logger logger = Logger.getLogger(UriInfoSimpleSingletonResource.class);
17
18 @Context
19 UriInfo myInfo;
20
21 @Path("/simple")
22 @GET
23 public String get(@Context UriInfo info, @QueryParam("abs") String abs) {
24 logger.info("abs query: " + abs);
25 URI base = null;
26 if (abs == null) {
27 base = PortProviderUtil.createURI("/", UriInfoSimpleSingletonResource.class.getSimpleName());
28 } else {
29 base = PortProviderUtil.createURI("/" + abs + "/", UriInfoSimpleSingletonResource.class.getSimpleName());
30 }
31
32 logger.info("BASE URI: " + info.getBaseUri());
33 logger.info("Request URI: " + info.getRequestUri());
34 Assert.assertEquals(base.getPath(), info.getBaseUri().getPath());
35 Assert.assertEquals("/simple", info.getPath());
36 return "CONTENT";
37 }
38
39 @Path("/simple/fromField")
40 @GET
41 public String get(@QueryParam("abs") String abs) {
42 logger.info("abs query: " + abs);
43 URI base = null;
44 if (abs == null) {
45 base = PortProviderUtil.createURI("/", UriInfoSimpleSingletonResource.class.getSimpleName());
46 } else {
47 base = PortProviderUtil.createURI("/" + abs + "/", UriInfoSimpleSingletonResource.class.getSimpleName());
48 }
49
50 logger.info("BASE URI: " + myInfo.getBaseUri());
51 logger.info("Request URI: " + myInfo.getRequestUri());
52 Assert.assertEquals(base.getPath(), myInfo.getBaseUri().getPath());
53 Assert.assertEquals("/simple/fromField", myInfo.getPath());
54 return "CONTENT";
55 }
56
57 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/WiderMappingDefaultOptions.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.OPTIONS;
3 import javax.ws.rs.Path;
4
5 @Path("{x:.*}")
6 public class WiderMappingDefaultOptions {
7 @OPTIONS
8 public String options() {
9 return "hello";
10 }
11 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/basic/resource/WiderMappingResource.java less more
0 package org.jboss.resteasy.test.resource.basic.resource;
1
2 import javax.ws.rs.POST;
3 import javax.ws.rs.Path;
4
5 @Path("/hello")
6 public class WiderMappingResource {
7 @POST
8 @Path("int")
9 public int postInt(int val) {
10 return val;
11 }
12
13 @POST
14 @Path("boolean")
15 public boolean postInt(boolean val) {
16 return val;
17 }
18 }
+0
-77
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/ComplexPathParamTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.param.resource.ComplexPathParamExtensionResource;
8 import org.jboss.resteasy.test.resource.param.resource.ComplexPathParamRegressionResteasy145;
9 import org.jboss.resteasy.test.resource.param.resource.ComplexPathParamSubRes;
10 import org.jboss.resteasy.test.resource.param.resource.ComplexPathParamSubResSecond;
11 import org.jboss.resteasy.test.resource.param.resource.ComplexPathParamTrickyResource;
12 import org.jboss.resteasy.test.resource.param.resource.ComplexPathParamUnlimitedResource;
13 import org.jboss.resteasy.util.HttpResponseCodes;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Assert;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.core.Response;
23
24 /**
25 * @tpSubChapter Parameters
26 * @tpChapter Integration tests
27 * @tpTestCaseDetails Test for complex path parameters
28 * @tpSince RESTEasy 3.0.16
29 */
30 @RunWith(Arquillian.class)
31 @RunAsClient
32 public class ComplexPathParamTest {
33
34 public static final String WRONG_REQUEST_ERROR_MESSAGE = "Wrong content of request";
35
36 @Deployment
37 public static Archive<?> deploy() {
38 WebArchive war = TestUtil.prepareArchive(ComplexPathParamTest.class.getSimpleName());
39 war.addClass(ComplexPathParamTest.class);
40 war.addClass(PortProviderUtil.class);
41 war.addClass(TestUtil.class);
42 war.addClass(ComplexPathParamSubRes.class);
43 war.addClass(ComplexPathParamSubResSecond.class);
44 return TestUtil.finishContainerPrepare(war, null, ComplexPathParamExtensionResource.class,
45 ComplexPathParamRegressionResteasy145.class, ComplexPathParamTrickyResource.class,
46 ComplexPathParamUnlimitedResource.class);
47 }
48
49 private String generateURL(String path) {
50 return PortProviderUtil.generateURL(path, ComplexPathParamTest.class.getSimpleName());
51 }
52
53 private void basicTest(String path, String body) {
54 ResteasyClient client = new ResteasyClientBuilder().build();
55 Response response = client.target(generateURL(path)).request().get();
56 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
57 Assert.assertEquals("Wrong content of response, url may not be decoded correctly", body, response.readEntity(String.class));
58 response.close();
59 client.close();
60 }
61
62 /**
63 * @tpTestDetails Check special characters and various path combination
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testIt() throws Exception {
68 basicTest("/1,2/3/blah4-5ttt", "hello");
69 basicTest("/tricky/1,2", "2Groups");
70 basicTest("/tricky/h1", "prefixed");
71 basicTest("/tricky/1", "hello");
72 basicTest("/unlimited/1-on/and/on", "ok");
73 basicTest("/repository/workspaces/aaaaaaxvi/wdddd", "sub2");
74 }
75
76 }
+0
-166
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/CookieInjectionTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.logging.Logger;
6 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
7 import org.jboss.resteasy.test.resource.param.resource.CookieInjectionResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.Assert;
15 import org.junit.BeforeClass;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.CookieParam;
20 import javax.ws.rs.GET;
21 import javax.ws.rs.Path;
22 import javax.ws.rs.client.Client;
23 import javax.ws.rs.client.ClientBuilder;
24 import javax.ws.rs.client.WebTarget;
25 import javax.ws.rs.core.Cookie;
26 import javax.ws.rs.core.MultivaluedMap;
27 import javax.ws.rs.core.Response;
28
29 /**
30 * @tpSubChapter Parameters
31 * @tpChapter Integration tests
32 * @tpTestCaseDetails Tests cookie injection via @CookieParam and @Context header injection
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class CookieInjectionTest {
38
39 private final Logger logger = Logger.getLogger(CookieInjectionTest.class);
40 static Client client;
41
42 public interface CookieProxy {
43 @Path("/param")
44 @GET
45 int param(@CookieParam("meaning") int value);
46
47 @Path("/param")
48 @GET
49 int param(Cookie cookie);
50
51 @Path("/expire")
52 @GET
53 Response expire();
54
55 @Path("/expire1")
56 @GET
57 Response expire1();
58 }
59
60 @Deployment
61 public static Archive<?> deploy() throws Exception {
62 WebArchive war = TestUtil.prepareArchive(CookieInjectionTest.class.getSimpleName());
63 return TestUtil.finishContainerPrepare(war, null, CookieInjectionResource.class);
64 }
65
66 @BeforeClass
67 public static void init() {
68 client = ClientBuilder.newClient();
69 }
70
71 @AfterClass
72 public static void after() throws Exception {
73 client.close();
74 }
75
76 private String generateURL(String path) {
77 return PortProviderUtil.generateURL(path, CookieInjectionTest.class.getSimpleName());
78 }
79
80 private void _test(String path) {
81 WebTarget target = client.target(generateURL(path));
82 try {
83 Response response = target.request().get();
84 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
85 MultivaluedMap<String, String> headers = response.getStringHeaders();
86 for (Object key : headers.keySet()) {
87 logger.info(key + ": " + headers.get(key));
88 }
89 response.close();
90 } catch (Exception e) {
91 throw new RuntimeException(e);
92 }
93 }
94
95 /**
96 * @tpTestDetails Injection of the cookie into resource, request issued with client
97 * @tpSince RESTEasy 3.0.16
98 */
99 @Test
100 public void testIt() {
101 _test("/set");
102 _test("/headers");
103 _test("/headers/fromField");
104 _test("/cookieparam");
105 _test("/param");
106 _test("/default");
107 }
108
109 private void _testExpire(String path) {
110 WebTarget target = client.target(generateURL(path));
111 try {
112 Response response = target.request().get();
113 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
114 String res = response.readEntity(String.class);
115 MultivaluedMap<String, String> headers = response.getStringHeaders();
116 Assert.assertTrue("Unexpected cookie expires:" + res, headers.get("Set-Cookie").contains(res));
117 response.close();
118 } catch (Exception e) {
119 throw new RuntimeException(e);
120 }
121 }
122
123 /**
124 * @tpTestDetails Cookie in the response header contains correct "Expires" attribute. Tested for cookie version 0 and 1.
125 * See RESTEASY-1476 for details.
126 * @tpSince RESTEasy 3.1.0
127 */
128 @Test
129 public void testCookieExpire() {
130 _testExpire("/expire");
131 _testExpire("/expire1");
132 _testExpire("/expired");
133 }
134
135 /**
136 * @tpTestDetails Cookie in the response header contains correct "Expires" attribute. Tested for cookie version 0 and 1.
137 * Proxy is used. See RESTEASY-1476 for details.
138 * @tpSince RESTEasy 3.1.0
139 */
140 @Test
141 public void testProxyExpire() {
142 CookieProxy proxy = ProxyBuilder.builder(CookieProxy.class, client.target(generateURL("/"))).build();
143 Response response = proxy.expire();
144 String res = response.readEntity(String.class);
145 MultivaluedMap<String, String> headers = response.getStringHeaders();
146 Assert.assertTrue("Unexpected cookie expires:" + res, headers.get("Set-Cookie").contains(res));
147 response.close();
148 }
149 /**
150 * @tpTestDetails Injection of the cookie into resource, request issued with proxy
151 * @tpSince RESTEasy 3.0.16
152 */
153 @Test
154 public void testProxy() {
155 {
156 CookieProxy proxy = ProxyBuilder.builder(CookieProxy.class, client.target(generateURL("/"))).build();
157 proxy.param(42);
158 }
159 {
160 CookieProxy proxy = ProxyBuilder.builder(CookieProxy.class, client.target(generateURL("/"))).build();
161 Cookie cookie = new Cookie("meaning", "42");
162 proxy.param(cookie);
163 }
164 }
165 }
+0
-148
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/FormParamTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.resource.param.resource.FormParamBasicResource;
6 import org.jboss.resteasy.test.resource.param.resource.FormParamEntityPrototype;
7 import org.jboss.resteasy.test.resource.param.resource.FormParamEntityThrowsIllegaArgumentException;
8 import org.jboss.resteasy.test.resource.param.resource.FormParamEntityWithConstructor;
9 import org.jboss.resteasy.test.resource.param.resource.FormParamEntityWithFromString;
10 import org.jboss.resteasy.test.resource.param.resource.FormParamResource;
11 import org.jboss.resteasy.util.HttpResponseCodes;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.AfterClass;
17 import org.junit.Assert;
18 import org.junit.BeforeClass;
19 import org.junit.Test;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Client;
23 import javax.ws.rs.client.ClientBuilder;
24 import javax.ws.rs.client.Entity;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27
28 /**
29 * @tpSubChapter Parameters
30 * @tpChapter Integration tests
31 * @tpTestCaseDetails Test for form parameters
32 * @tpSince RESTEasy 3.0.16
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class FormParamTest {
37 static Client client;
38
39 private static final String ERROR_CODE = "Wrong response";
40 @BeforeClass
41 public static void setup() {
42 client = ClientBuilder.newClient();
43 }
44
45 @Deployment
46 public static Archive<?> deploy() {
47 WebArchive war = TestUtil.prepareArchive(FormParamTest.class.getSimpleName());
48 war.addClass(FormParamEntityPrototype.class);
49 war.addClass(FormParamEntityThrowsIllegaArgumentException.class);
50 war.addClass(FormParamEntityWithConstructor.class);
51 war.addClass(FormParamEntityWithFromString.class);
52 return TestUtil.finishContainerPrepare(war, null, FormParamResource.class,
53 FormParamBasicResource.class);
54 }
55
56 private static String generateURL(String path) {
57 return PortProviderUtil.generateURL(path, FormParamTest.class.getSimpleName());
58 }
59
60 @AfterClass
61 public static void cleanup() {
62 client.close();
63 }
64
65 private static final String SENT = "_`'$X Y@\"a a\"";
66 private static final String ENCODED = "_%60%27%24X+Y%40%22a+a%22";
67
68 /**
69 * @tpTestDetails Check form parameters with POST method
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test
73 public void postTest() {
74 Entity entity = Entity.entity("param=" + ENCODED, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
75 Response response = client.target(generateURL("/form")).request().post(entity);
76 Assert.assertEquals(response.getStatus(), HttpResponseCodes.SC_OK);
77 Assert.assertEquals(ERROR_CODE, response.readEntity(String.class), ENCODED);
78 response.close();
79 }
80
81 /**
82 * @tpTestDetails Check non default form parameters, accept special object
83 * @tpSince RESTEasy 3.0.16
84 */
85 @Test
86 public void nonDefaultFormParamFromStringTest() {
87 Entity entity = Entity.entity("default_argument=" + SENT, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
88 Response response = client.target(generateURL("/FormParamTest/ParamEntityWithFromString")).request().post(entity);
89 Assert.assertEquals(response.getStatus(), HttpResponseCodes.SC_OK);
90 Assert.assertEquals(ERROR_CODE, "CTS_FORMPARAM:" + ENCODED, response.readEntity(String.class));
91 response.close();
92 }
93
94 /**
95 * @tpTestDetails Check non default form parameters, accept String
96 * @tpSince RESTEasy 3.0.16
97 */
98 @Test
99 public void string() {
100 Entity entity = Entity.entity("default_argument=" + SENT, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
101 Response response = client.target(generateURL("/FormParamTest/string")).request().post(entity);
102 Assert.assertEquals(response.getStatus(), HttpResponseCodes.SC_OK);
103 Assert.assertEquals(ERROR_CODE, response.readEntity(String.class), "CTS_FORMPARAM:" + ENCODED);
104 response.close();
105 }
106
107 /**
108 * @tpTestDetails Check non default form parameters, accept sorted set
109 * @tpSince RESTEasy 3.0.16
110 */
111 @Test
112 public void defaultFormParamFromSortedSetFromStringTest() {
113 Response response = client.target(generateURL("/FormParamTest/SortedSetFromString")).request().
114 header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED).post(null);
115 Assert.assertEquals(response.getStatus(), HttpResponseCodes.SC_OK);
116 Assert.assertEquals(ERROR_CODE, "CTS_FORMPARAM:SortedSetFromString", response.readEntity(String.class));
117 response.close();
118 }
119
120 /**
121 * @tpTestDetails Check non default form parameters, accept list
122 * @tpSince RESTEasy 3.0.16
123 */
124 @Test
125 public void defaultListConstructor() {
126 Response response = client.target(generateURL("/FormParamTest/ListConstructor")).request().
127 header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED).post(null);
128 Assert.assertEquals(response.getStatus(), HttpResponseCodes.SC_OK);
129 Assert.assertEquals(ERROR_CODE, "CTS_FORMPARAM:ListConstructor", response.readEntity(String.class));
130 response.close();
131 }
132
133 /**
134 * @tpTestDetails Check wrong arguments, exception is excepted
135 * @tpSince RESTEasy 3.0.16
136 */
137 @Test
138 public void testIllegalArgumentException() {
139 Response response = client.target(generateURL("/FormParamTest/IllegalArgumentException")).request().
140 header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED).post(null);
141 Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
142 Assert.assertEquals(ERROR_CODE, "", response.readEntity(String.class));
143 response.close();
144 }
145
146
147 }
+0
-103
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/HeaderDelegateTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.junit.Arquillian;
4 import org.jboss.resteasy.logging.Logger;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
8 import org.jboss.resteasy.plugins.delegates.DateDelegate;
9 import org.jboss.resteasy.spi.ResteasyProviderFactory;
10 import org.jboss.resteasy.test.resource.param.resource.HeaderDelegateDate;
11 import org.jboss.resteasy.test.resource.param.resource.HeaderDelegateDelegate;
12 import org.jboss.resteasy.test.resource.param.resource.HeaderDelegateInterface1;
13 import org.jboss.resteasy.test.resource.param.resource.HeaderDelegateInterface2;
14 import org.jboss.resteasy.test.resource.param.resource.HeaderDelegateInterface3;
15 import org.jboss.resteasy.test.resource.param.resource.HeaderDelegateInterface4;
16 import org.jboss.resteasy.test.resource.param.resource.HeaderDelegateResource;
17 import org.jboss.resteasy.test.resource.param.resource.HeaderDelegateSubDelegate;
18 import org.jboss.resteasy.util.DateUtil;
19 import org.jboss.resteasy.util.HttpResponseCodes;
20 import org.jboss.resteasy.utils.PortProviderUtil;
21 import org.jboss.resteasy.utils.TestUtil;
22 import org.jboss.shrinkwrap.api.Archive;
23 import org.jboss.shrinkwrap.api.asset.StringAsset;
24 import org.jboss.shrinkwrap.api.spec.WebArchive;
25 import org.junit.Assert;
26 import org.junit.Test;
27 import org.junit.runner.RunWith;
28
29 import javax.ws.rs.client.Invocation;
30 import javax.ws.rs.core.Response;
31 import java.util.Date;
32
33 /**
34 * @tpSubChapter Parameters
35 * @tpChapter Integration tests
36 * @tpTestCaseDetails Regression test for RESTEASY-915
37 * @tpSince RESTEasy 3.0.16
38 */
39 @RunWith(Arquillian.class)
40 public class HeaderDelegateTest {
41 private static Logger logger = Logger.getLogger(HeaderDelegateTest.class);
42
43 public static final Date RIGHT_AFTER_BIG_BANG = new HeaderDelegateDate(3000);
44
45
46 @Deployment
47 public static Archive<?> deploySimpleResource() {
48 WebArchive war = TestUtil.prepareArchive(HeaderDelegateTest.class.getSimpleName());
49 war.addClass(HeaderDelegateDate.class);
50 war.addClass(HeaderDelegateDelegate.class);
51 war.addClass(HeaderDelegateInterface1.class);
52 war.addClass(HeaderDelegateInterface2.class);
53 war.addClass(HeaderDelegateInterface3.class);
54 war.addClass(HeaderDelegateInterface4.class);
55 war.addClass(HeaderDelegateSubDelegate.class);
56 war.addClass(PortProviderUtil.class);
57 war.addClass(HeaderDelegateTest.class);
58 return TestUtil.finishContainerPrepare(war, null, HeaderDelegateResource.class);
59 }
60
61 private String generateURL(String path) {
62 return PortProviderUtil.generateURL(path, HeaderDelegateTest.class.getSimpleName());
63 }
64
65 /**
66 * @tpTestDetails Test delegation by client
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void lastModifiedTest() throws Exception {
71 ResteasyClient client = new ResteasyClientBuilder().build();
72 ResteasyWebTarget target = client.target(generateURL("/last"));
73 Invocation.Builder request = target.request();
74 Response response = request.get();
75 logger.info("lastModified string: " + response.getHeaderString("last-modified"));
76 Date last = response.getLastModified();
77 Assert.assertEquals(response.getStatus(), HttpResponseCodes.SC_OK);
78 Assert.assertEquals("Wrong response", DateUtil.formatDate(RIGHT_AFTER_BIG_BANG), DateUtil.formatDate(last));
79 client.close();
80 }
81
82 /**
83 * @tpTestDetails Check delegation rules from ResteasyProviderFactory
84 * @tpSince RESTEasy 3.0.16
85 */
86 @Test
87 public void localTest() throws Exception {
88 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
89 Assert.assertEquals("Wrong delegation", DateDelegate.class, factory.getHeaderDelegate(HeaderDelegateDate.class).getClass());
90 Assert.assertEquals("Wrong delegation", DateDelegate.class, factory.createHeaderDelegate(HeaderDelegateDate.class).getClass());
91
92 @SuppressWarnings("rawtypes")
93 HeaderDelegateSubDelegate<?> delegate = new HeaderDelegateSubDelegate();
94 factory.addHeaderDelegate(HeaderDelegateInterface1.class, delegate);
95 Assert.assertEquals("Wrong delegation", delegate, factory.getHeaderDelegate(HeaderDelegateInterface1.class));
96 Assert.assertEquals("Wrong delegation", delegate, factory.getHeaderDelegate(HeaderDelegateInterface2.class));
97 Assert.assertEquals("Wrong delegation", delegate, factory.getHeaderDelegate(HeaderDelegateInterface3.class));
98 Assert.assertEquals("Wrong delegation", delegate, factory.getHeaderDelegate(HeaderDelegateInterface4.class));
99 Assert.assertEquals("Wrong delegation", delegate, factory.getHeaderDelegate(HeaderDelegateDelegate.class));
100 Assert.assertEquals("Wrong delegation", delegate, factory.getHeaderDelegate(HeaderDelegateSubDelegate.class));
101 }
102 }
+0
-689
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/HeaderParamsAsPrimitivesTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesArrayDefaultNullProxy;
8 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesArrayDefaultOverrideProxy;
9 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesArrayDefaultProxy;
10 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesArrayProxy;
11 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesDefaultNullProxy;
12 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesDefaultOverrideProxy;
13 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesDefaultProxy;
14 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesListDefaultNullProxy;
15 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesListDefaultOverrideProxy;
16 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesListDefaultProxy;
17 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesListProxy;
18 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesPrimitivesProxy;
19 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceArray;
20 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceArrayDefault;
21 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceArrayDefaultNull;
22 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceArrayDefaultOverride;
23 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceList;
24 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceListDefault;
25 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceListDefaultNull;
26 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceListDefaultOverride;
27 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceSet;
28 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceWrappers;
29 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceWrappersDefault;
30 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceWrappersDefaultNull;
31 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceWrappersDefaultOverride;
32 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourcePrimitives;
33 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceDefault;
34 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceDefaultNull;
35 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceDefaultOverride;
36 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesSetProxy;
37 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesSortedSetProxy;
38 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesWrappersDefaultNullProxy;
39 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesWrappersDefaultOverrideProxy;
40 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesWrappersDefaultProxy;
41 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesWrappersProxy;
42 import org.jboss.resteasy.test.resource.param.resource.HeaderParamsAsPrimitivesResourceSortedSet;
43 import org.jboss.resteasy.util.HttpHeaderNames;
44 import org.jboss.resteasy.util.HttpResponseCodes;
45 import org.jboss.resteasy.utils.PortProviderUtil;
46 import org.jboss.resteasy.utils.TestUtil;
47 import org.jboss.shrinkwrap.api.Archive;
48 import org.jboss.shrinkwrap.api.spec.WebArchive;
49 import org.junit.AfterClass;
50 import org.junit.Assert;
51 import org.junit.BeforeClass;
52 import org.junit.Test;
53 import org.junit.runner.RunWith;
54 import javax.ws.rs.core.Response;
55 import java.io.PrintWriter;
56 import java.io.StringWriter;
57 import java.util.ArrayList;
58 import java.util.HashSet;
59 import java.util.List;
60 import java.util.TreeSet;
61
62 import static org.junit.Assert.fail;
63
64 /**
65 * @tpSubChapter Parameters
66 * @tpChapter Integration tests
67 * @tpTestCaseDetails Test primitive header parameters
68 * @tpSince RESTEasy 3.0.16
69 */
70 @RunWith(Arquillian.class)
71 @RunAsClient
72 public class HeaderParamsAsPrimitivesTest {
73
74 public static final String ERROR_MESSAGE = "Wrong content of header parameter";
75
76 private static HeaderParamsAsPrimitivesPrimitivesProxy resourceHeaderPrimitives;
77 private static HeaderParamsAsPrimitivesDefaultProxy resourceHeaderPrimitivesDefault;
78 private static HeaderParamsAsPrimitivesDefaultOverrideProxy resourceHeaderPrimitivesDefaultOverride;
79 private static HeaderParamsAsPrimitivesDefaultNullProxy resourceHeaderPrimitivesDefaultNull;
80 private static HeaderParamsAsPrimitivesWrappersProxy resourceHeaderPrimitiveWrappers;
81 private static HeaderParamsAsPrimitivesWrappersDefaultProxy resourceHeaderPrimitiveWrappersDefault;
82 private static HeaderParamsAsPrimitivesWrappersDefaultOverrideProxy resourceHeaderPrimitiveWrappersDefaultOverride;
83 private static HeaderParamsAsPrimitivesWrappersDefaultNullProxy resourceHeaderPrimitiveWrappersDefaultNull;
84 private static HeaderParamsAsPrimitivesListProxy resourceHeaderPrimitiveList;
85 private static HeaderParamsAsPrimitivesListDefaultProxy resourceHeaderPrimitiveListDefault;
86 private static HeaderParamsAsPrimitivesListDefaultOverrideProxy resourceHeaderPrimitiveListDefaultOverride;
87 private static HeaderParamsAsPrimitivesListDefaultNullProxy resourceHeaderPrimitiveListDefaultNull;
88 private static HeaderParamsAsPrimitivesArrayProxy resourceHeaderPrimitiveArray;
89 private static HeaderParamsAsPrimitivesArrayDefaultProxy resourceHeaderPrimitiveArrayDefault;
90 private static HeaderParamsAsPrimitivesArrayDefaultOverrideProxy resourceHeaderPrimitiveArrayDefaultOverride;
91 private static HeaderParamsAsPrimitivesArrayDefaultNullProxy resourceHeaderPrimitiveArrayDefaultNull;
92
93 private ResteasyClient client;
94 private static ResteasyClient proxyClient;
95
96 @Deployment
97 public static Archive<?> deploy() {
98 WebArchive war = TestUtil.prepareArchive(HeaderParamsAsPrimitivesTest.class.getSimpleName());
99 war.addClasses(HeaderParamsAsPrimitivesPrimitivesProxy.class,
100 HeaderParamsAsPrimitivesDefaultProxy.class,
101 HeaderParamsAsPrimitivesDefaultOverrideProxy.class,
102 HeaderParamsAsPrimitivesDefaultNullProxy.class,
103 HeaderParamsAsPrimitivesWrappersProxy.class,
104 HeaderParamsAsPrimitivesWrappersDefaultProxy.class,
105 HeaderParamsAsPrimitivesWrappersDefaultNullProxy.class,
106 HeaderParamsAsPrimitivesWrappersDefaultOverrideProxy.class,
107 HeaderParamsAsPrimitivesListProxy.class,
108 HeaderParamsAsPrimitivesSetProxy.class,
109 HeaderParamsAsPrimitivesSortedSetProxy.class,
110 HeaderParamsAsPrimitivesListDefaultProxy.class,
111 HeaderParamsAsPrimitivesListDefaultNullProxy.class,
112 HeaderParamsAsPrimitivesListDefaultOverrideProxy.class,
113 HeaderParamsAsPrimitivesArrayProxy.class,
114 HeaderParamsAsPrimitivesArrayDefaultProxy.class,
115 HeaderParamsAsPrimitivesArrayDefaultNullProxy.class,
116 HeaderParamsAsPrimitivesArrayDefaultOverrideProxy.class);
117 return TestUtil.finishContainerPrepare(war, null,
118 HeaderParamsAsPrimitivesResourcePrimitives.class,
119 HeaderParamsAsPrimitivesResourceDefault.class,
120 HeaderParamsAsPrimitivesResourceDefaultOverride.class,
121 HeaderParamsAsPrimitivesResourceDefaultNull.class,
122 HeaderParamsAsPrimitivesResourceWrappers.class,
123 HeaderParamsAsPrimitivesResourceWrappersDefault.class,
124 HeaderParamsAsPrimitivesResourceWrappersDefaultNull.class,
125 HeaderParamsAsPrimitivesResourceWrappersDefaultOverride.class,
126 HeaderParamsAsPrimitivesResourceList.class,
127 HeaderParamsAsPrimitivesResourceSet.class,
128 HeaderParamsAsPrimitivesResourceSortedSet.class,
129 HeaderParamsAsPrimitivesResourceListDefault.class,
130 HeaderParamsAsPrimitivesResourceListDefaultNull.class,
131 HeaderParamsAsPrimitivesResourceListDefaultOverride.class,
132 HeaderParamsAsPrimitivesResourceArray.class,
133 HeaderParamsAsPrimitivesResourceArrayDefault.class,
134 HeaderParamsAsPrimitivesResourceArrayDefaultNull.class,
135 HeaderParamsAsPrimitivesResourceArrayDefaultOverride.class);
136 }
137
138 private static String generateBaseUrl() {
139 return PortProviderUtil.generateBaseUrl(HeaderParamsAsPrimitivesTest.class.getSimpleName());
140 }
141
142 private String generateURL(String path) {
143 return PortProviderUtil.generateURL(path, HeaderParamsAsPrimitivesTest.class.getSimpleName());
144 }
145
146 @BeforeClass
147 public static void before() throws Exception {
148 proxyClient = new ResteasyClientBuilder().build();
149 resourceHeaderPrimitives = proxyClient.target(generateBaseUrl())
150 .proxyBuilder(HeaderParamsAsPrimitivesPrimitivesProxy.class).build();
151 resourceHeaderPrimitivesDefault = proxyClient.target(generateBaseUrl())
152 .proxyBuilder(HeaderParamsAsPrimitivesDefaultProxy.class).build();
153 resourceHeaderPrimitivesDefaultOverride = proxyClient.target(generateBaseUrl())
154 .proxyBuilder(HeaderParamsAsPrimitivesDefaultOverrideProxy.class).build();
155 resourceHeaderPrimitivesDefaultNull = proxyClient.target(generateBaseUrl())
156 .proxyBuilder(HeaderParamsAsPrimitivesDefaultNullProxy.class).build();
157 resourceHeaderPrimitiveWrappers = proxyClient.target(generateBaseUrl())
158 .proxyBuilder(HeaderParamsAsPrimitivesWrappersProxy.class).build();
159 resourceHeaderPrimitiveWrappersDefault = proxyClient.target(generateBaseUrl())
160 .proxyBuilder(HeaderParamsAsPrimitivesWrappersDefaultProxy.class).build();
161 resourceHeaderPrimitiveWrappersDefaultOverride = proxyClient.target(generateBaseUrl())
162 .proxyBuilder(HeaderParamsAsPrimitivesWrappersDefaultOverrideProxy.class).build();
163 resourceHeaderPrimitiveWrappersDefaultNull = proxyClient.target(generateBaseUrl())
164 .proxyBuilder(HeaderParamsAsPrimitivesWrappersDefaultNullProxy.class).build();
165 resourceHeaderPrimitiveList = proxyClient.target(generateBaseUrl())
166 .proxyBuilder(HeaderParamsAsPrimitivesListProxy.class).build();
167 resourceHeaderPrimitiveListDefault = proxyClient.target(generateBaseUrl())
168 .proxyBuilder(HeaderParamsAsPrimitivesListDefaultProxy.class).build();
169 resourceHeaderPrimitiveListDefaultOverride = proxyClient.target(generateBaseUrl())
170 .proxyBuilder(HeaderParamsAsPrimitivesListDefaultOverrideProxy.class).build();
171 resourceHeaderPrimitiveListDefaultNull = proxyClient.target(generateBaseUrl())
172 .proxyBuilder(HeaderParamsAsPrimitivesListDefaultNullProxy.class).build();
173 resourceHeaderPrimitiveArray = proxyClient.target(generateBaseUrl())
174 .proxyBuilder(HeaderParamsAsPrimitivesArrayProxy.class).build();
175 resourceHeaderPrimitiveArrayDefault = proxyClient.target(generateBaseUrl())
176 .proxyBuilder(HeaderParamsAsPrimitivesArrayDefaultProxy.class).build();
177 resourceHeaderPrimitiveArrayDefaultOverride = proxyClient.target(generateBaseUrl())
178 .proxyBuilder(HeaderParamsAsPrimitivesArrayDefaultOverrideProxy.class).build();
179 resourceHeaderPrimitiveArrayDefaultNull = proxyClient.target(generateBaseUrl())
180 .proxyBuilder(HeaderParamsAsPrimitivesArrayDefaultNullProxy.class).build();
181 }
182
183 @AfterClass
184 public static void after() throws Exception {
185 proxyClient.close();
186 }
187
188 public void basicTest(String type, String value) {
189 {
190 client = new ResteasyClientBuilder().build();
191 Response response = client.target(generateURL("/")).request()
192 .header(HttpHeaderNames.ACCEPT, "application/" + type)
193 .header(type, value)
194 .get();
195 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
196 response.close();
197 client.close();
198 }
199
200 {
201 client = new ResteasyClientBuilder().build();
202 Response response = client.target(generateURL("/wrappers")).request()
203 .header(HttpHeaderNames.ACCEPT, "application/" + type)
204 .header(type, value)
205 .get();
206 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
207 response.close();
208 client.close();
209 }
210
211 {
212 client = new ResteasyClientBuilder().build();
213 Response response = client.target(generateURL("/list")).request()
214 .header(HttpHeaderNames.ACCEPT, "application/" + type)
215 .header(type, value)
216 .header(type, value)
217 .header(type, value)
218 .get();
219 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
220 response.close();
221 client.close();
222 }
223 }
224
225 public void testDefault(String base, String type, String value) {
226 {
227 client = new ResteasyClientBuilder().build();
228 Response response = client.target(generateURL(base + "default/null")).request()
229 .header(HttpHeaderNames.ACCEPT, "application/" + type)
230 .get();
231 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
232 response.close();
233 client.close();
234 }
235
236 {
237 client = new ResteasyClientBuilder().build();
238 Response response = client.target(generateURL(base + "default")).request()
239 .header(HttpHeaderNames.ACCEPT, "application/" + type)
240 .get();
241 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
242 response.close();
243 client.close();
244 }
245
246 {
247 client = new ResteasyClientBuilder().build();
248 Response response = client.target(generateURL(base + "default/override")).request()
249 .header(HttpHeaderNames.ACCEPT, "application/" + type)
250 .header(type, value)
251 .get();
252 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
253 response.close();
254 client.close();
255 }
256 }
257
258 public void testDefault(String type, String value) {
259 testDefault("/", type, value);
260 }
261
262 public void testWrappersDefault(String type, String value) {
263 testDefault("/wrappers/", type, value);
264 }
265
266 public void testListDefault(String type, String value) {
267 testDefault("/list/", type, value);
268 }
269
270 /**
271 * @tpTestDetails Test set of boolean
272 * @tpSince RESTEasy 3.0.16
273 */
274 @Test
275 public void testSet() {
276 {
277 client = new ResteasyClientBuilder().build();
278 Response response = client.target(generateURL("/set")).request()
279 .header(HttpHeaderNames.ACCEPT, "application/boolean")
280 .header("header", "one")
281 .header("header", "one")
282 .header("header", "one")
283 .header("header", "two")
284 .get();
285 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
286 response.close();
287 client.close();
288
289 client = new ResteasyClientBuilder().build();
290 HeaderParamsAsPrimitivesSetProxy setClient = client.target(generateBaseUrl())
291 .proxyBuilder(HeaderParamsAsPrimitivesSetProxy.class).build();
292 HashSet<String> set = new HashSet<>();
293 set.add("one");
294 set.add("two");
295 setClient.doGetBoolean(set);
296 client.close();
297 }
298
299 {
300 client = new ResteasyClientBuilder().build();
301 Response response = client.target(generateURL("/sortedset")).request()
302 .header(HttpHeaderNames.ACCEPT, "application/boolean")
303 .header("header", "one")
304 .header("header", "one")
305 .header("header", "one")
306 .header("header", "two")
307 .get();
308
309 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
310 response.close();
311 client.close();
312
313
314 client = new ResteasyClientBuilder().build();
315 HeaderParamsAsPrimitivesSortedSetProxy setClient = client.target(generateBaseUrl())
316 .proxyBuilder(HeaderParamsAsPrimitivesSortedSetProxy.class).build();
317 TreeSet<String> set = new TreeSet<String>();
318 set.add("one");
319 set.add("two");
320 setClient.doGetBoolean(set);
321 client.close();
322 }
323 }
324
325 /**
326 * @tpTestDetails Test list of boolean with GET method
327 * @tpSince RESTEasy 3.0.16
328 */
329 @Test
330 public void testGetBoolean() {
331 basicTest("boolean", "true");
332 resourceHeaderPrimitives.doGet(true);
333 resourceHeaderPrimitiveWrappers.doGet(Boolean.TRUE);
334 ArrayList<Boolean> list = new ArrayList<>();
335 list.add(Boolean.TRUE);
336 list.add(Boolean.TRUE);
337 list.add(Boolean.TRUE);
338 resourceHeaderPrimitiveList.doGetBoolean(list);
339 boolean[] array =
340 {true, true, true};
341 resourceHeaderPrimitiveArray.doGetBoolean(array);
342 }
343
344 /**
345 * @tpTestDetails Basic test for boolean
346 * @tpSince RESTEasy 3.0.16
347 */
348 @Test
349 public void testGetBooleanPrimitivesDefault() {
350 testDefault("boolean", "true");
351 resourceHeaderPrimitivesDefault.doGetBoolean();
352 resourceHeaderPrimitivesDefaultNull.doGetBoolean();
353 resourceHeaderPrimitivesDefaultOverride.doGet(true);
354 }
355
356 /**
357 * @tpTestDetails Boolean test by proxy
358 * @tpSince RESTEasy 3.0.16
359 */
360 @Test
361 public void testGetBooleanPrimitiveWrapperDefault() {
362 testWrappersDefault("boolean", "true");
363 resourceHeaderPrimitiveWrappersDefault.doGetBoolean();
364 resourceHeaderPrimitiveWrappersDefaultNull.doGetBoolean();
365 resourceHeaderPrimitiveWrappersDefaultOverride.doGet(Boolean.TRUE);
366 }
367
368 /**
369 * @tpTestDetails Proxy test for list of boolean
370 * @tpSince RESTEasy 3.0.16
371 */
372 @Test
373 public void testGetBooleanPrimitiveListDefault() {
374 testListDefault("boolean", "true");
375 resourceHeaderPrimitiveListDefault.doGetBoolean();
376 resourceHeaderPrimitiveListDefaultNull.doGetBoolean();
377 List<Boolean> list = new ArrayList<>();
378 list.add(Boolean.TRUE);
379 resourceHeaderPrimitiveListDefaultOverride.doGetBoolean(list);
380 resourceHeaderPrimitiveArrayDefault.doGetBoolean();
381 resourceHeaderPrimitiveArrayDefaultNull.doGetBoolean();
382 boolean[] array = {true};
383 resourceHeaderPrimitiveArrayDefaultOverride.doGetBoolean(array);
384 }
385
386 /**
387 * @tpTestDetails Basic test for byte
388 * @tpSince RESTEasy 3.0.16
389 */
390 @Test
391 public void testGetByte() {
392 basicTest("byte", "127");
393 try {
394 resourceHeaderPrimitives.doGet((byte) 127);
395 } catch (Exception e) {
396 StringWriter errors = new StringWriter();
397 e.printStackTrace(new PrintWriter(errors));
398 fail("resourceHeaderPrimitives.doGet() failed:\n" + errors.toString());
399 }
400 resourceHeaderPrimitiveWrappers.doGet(new Byte((byte) 127));
401 ArrayList<Byte> list = new ArrayList<Byte>();
402 list.add(new Byte((byte) 127));
403 list.add(new Byte((byte) 127));
404 list.add(new Byte((byte) 127));
405 try {
406 resourceHeaderPrimitiveList.doGetByte(list);
407 } catch (Exception e) {
408 StringWriter errors = new StringWriter();
409 e.printStackTrace(new PrintWriter(errors));
410 fail("resourceHeaderPrimitiveList.doGetByte() failed:\n" + errors.toString());
411 }
412 }
413
414 /**
415 * @tpTestDetails Proxy test for byte
416 * @tpSince RESTEasy 3.0.16
417 */
418 @Test
419 public void testGetBytePrimitivesDefault() {
420 testDefault("byte", "127");
421 resourceHeaderPrimitivesDefault.doGetByte();
422 resourceHeaderPrimitivesDefaultNull.doGetByte();
423 resourceHeaderPrimitivesDefaultOverride.doGet((byte) 127);
424 }
425
426 /**
427 * @tpTestDetails Proxy test for byte with wrapper
428 * @tpSince RESTEasy 3.0.16
429 */
430 @Test
431 public void testGetBytePrimitiveWrappersDefault() {
432 testWrappersDefault("byte", "127");
433 resourceHeaderPrimitiveWrappersDefault.doGetByte();
434 resourceHeaderPrimitiveWrappersDefaultNull.doGetByte();
435 resourceHeaderPrimitiveWrappersDefaultOverride.doGet(new Byte((byte) 127));
436 }
437
438 /**
439 * @tpTestDetails Basic test for byte list
440 * @tpSince RESTEasy 3.0.16
441 */
442 @Test
443 public void testGetBytePrimitiveListDefault() {
444 testListDefault("byte", "127");
445 resourceHeaderPrimitiveListDefault.doGetByte();
446 resourceHeaderPrimitiveListDefaultNull.doGetByte();
447 List<Byte> list = new ArrayList<Byte>();
448 list.add(new Byte((byte) 127));
449 resourceHeaderPrimitiveListDefaultOverride.doGetByte(list);
450 }
451
452 /**
453 * @tpTestDetails Basic test for short, use proxy
454 * @tpSince RESTEasy 3.0.16
455 */
456 @Test
457 public void testGetShort() {
458 basicTest("short", "32767");
459 resourceHeaderPrimitives.doGet((short) 32767);
460 resourceHeaderPrimitiveWrappers.doGet(new Short((short) 32767));
461 ArrayList<Short> list = new ArrayList<Short>();
462 list.add(new Short((short) 32767));
463 list.add(new Short((short) 32767));
464 list.add(new Short((short) 32767));
465 resourceHeaderPrimitiveList.doGetShort(list);
466 }
467
468 /**
469 * @tpTestDetails Basic test for short, test default value
470 * @tpSince RESTEasy 3.0.16
471 */
472 @Test
473 public void testGetShortPrimtivesDefault() {
474 testDefault("short", "32767");
475 }
476
477 /**
478 * @tpTestDetails Short type test, use wrapper
479 * @tpSince RESTEasy 3.0.16
480 */
481 @Test
482 public void testGetShortPrimtiveWrappersDefault() {
483 testWrappersDefault("short", "32767");
484 }
485
486 /**
487 * @tpTestDetails Short test, test default value
488 * @tpSince RESTEasy 3.0.16
489 */
490 @Test
491 public void testGetShortPrimtiveListDefault() {
492 testListDefault("short", "32767");
493 }
494
495 /**
496 * @tpTestDetails Basic test for int
497 * @tpSince RESTEasy 3.0.16
498 */
499 @Test
500 public void testGetInt() {
501 basicTest("int", "2147483647");
502 }
503
504 /**
505 * @tpTestDetails Check default value for int
506 * @tpSince RESTEasy 3.0.16
507 */
508 @Test
509 public void testGetIntPrimitivesDefault() {
510 testDefault("int", "2147483647");
511 }
512
513 /**
514 * @tpTestDetails Test int with wrapper
515 * @tpSince RESTEasy 3.0.16
516 */
517 @Test
518 public void testGetIntPrimitiveWrappersDefault() {
519 testWrappersDefault("int", "2147483647");
520 }
521
522 /**
523 * @tpTestDetails Test list of int
524 * @tpSince RESTEasy 3.0.16
525 */
526 @Test
527 public void testGetIntPrimitiveListDefault() {
528 testListDefault("int", "2147483647");
529 }
530
531 /**
532 * @tpTestDetails Basic test for long
533 * @tpSince RESTEasy 3.0.16
534 */
535 @Test
536 public void testGetLong() {
537 basicTest("long", "9223372036854775807");
538 }
539
540 /**
541 * @tpTestDetails Test default value for long
542 * @tpSince RESTEasy 3.0.16
543 */
544 @Test
545 public void testGetLongPrimitivesDefault() {
546 testDefault("long", "9223372036854775807");
547 }
548
549 /**
550 * @tpTestDetails Test default value for long, use wrapper
551 * @tpSince RESTEasy 3.0.16
552 */
553 @Test
554 public void testGetLongPrimitiveWrappersDefault() {
555 testWrappersDefault("long", "9223372036854775807");
556 }
557
558 /**
559 * @tpTestDetails Test default value for list of long, do not use wrapper
560 * @tpSince RESTEasy 3.0.16
561 */
562 @Test
563 public void testGetLongPrimitiveListDefault() {
564 testListDefault("long", "9223372036854775807");
565 }
566
567 /**
568 * @tpTestDetails Basic test for float
569 * @tpSince RESTEasy 3.0.16
570 */
571 @Test
572 public void testGetFloat() {
573 basicTest("float", "3.14159265");
574 }
575
576 /**
577 * @tpTestDetails Test default value for float
578 * @tpSince RESTEasy 3.0.16
579 */
580 @Test
581 public void testGetFloatPrimitivesDefault() {
582 testDefault("float", "3.14159265");
583 }
584
585 /**
586 * @tpTestDetails Test default value for float, use wrapper
587 * @tpSince RESTEasy 3.0.16
588 */
589 @Test
590 public void testGetFloatPrimitiveWrappersDefault() {
591 testWrappersDefault("float", "3.14159265");
592 }
593
594 /**
595 * @tpTestDetails Test default value for list of float, use wrapper
596 * @tpSince RESTEasy 3.0.16
597 */
598 @Test
599 public void testGetFloatPrimitiveListDefault() {
600 testListDefault("float", "3.14159265");
601 }
602
603 /**
604 * @tpTestDetails Basic test for double
605 * @tpSince RESTEasy 3.0.16
606 */
607 @Test
608 public void testGetDouble() {
609 basicTest("double", "3.14159265358979");
610 }
611
612 /**
613 * @tpTestDetails Basic test for double, test default value
614 * @tpSince RESTEasy 3.0.16
615 */
616 @Test
617 public void testGetDoublePrimitivesDefault() {
618 testDefault("double", "3.14159265358979");
619 }
620
621 /**
622 * @tpTestDetails Basic test for double, use wrapper
623 * @tpSince RESTEasy 3.0.16
624 */
625 @Test
626 public void testGetDoublePrimitiveWrappersDefault() {
627 testWrappersDefault("double", "3.14159265358979");
628 }
629
630 /**
631 * @tpTestDetails Basic test for list of double, do not use wrapper
632 * @tpSince RESTEasy 3.0.16
633 */
634 @Test
635 public void testGetDoublePrimitiveListDefault() {
636 testListDefault("double", "3.14159265358979");
637 }
638
639 /**
640 * @tpTestDetails Negative test for int
641 * @tpSince RESTEasy 3.0.16
642 */
643 @Test
644 public void testBadPrimitiveValue() {
645 client = new ResteasyClientBuilder().build();
646 Response response = client.target(generateURL("/")).request()
647 .header(HttpHeaderNames.ACCEPT, "application/int")
648 .header("int", "abcdef")
649 .get();
650 Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus());
651 response.close();
652 client.close();
653 }
654
655 /**
656 * @tpTestDetails Negative test for int, use wrapper
657 * @tpSince RESTEasy 3.0.16
658 */
659 @Test
660 public void testBadPrimitiveWrapperValue() {
661 client = new ResteasyClientBuilder().build();
662 Response response = client.target(generateURL("/wrappers")).request()
663 .header(HttpHeaderNames.ACCEPT, "application/int")
664 .header("int", "abcdef")
665 .get();
666 Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus());
667 response.close();
668 client.close();
669 }
670
671 /**
672 * @tpTestDetails Negative test for list of int
673 * @tpSince RESTEasy 3.0.16
674 */
675 @Test
676 public void testBadPrimitiveListValue() {
677 client = new ResteasyClientBuilder().build();
678 Response response = client.target(generateURL("/list")).request()
679 .header(HttpHeaderNames.ACCEPT, "application/int")
680 .header("int", "abcdef")
681 .header("int", "abcdef")
682 .header("int", "abcdef")
683 .get();
684 Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus());
685 response.close();
686 client.close();
687 }
688 }
+0
-478
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/MatrixParamAsPrimitiveTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveArray;
8 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveArrayDefault;
9 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveArrayDefaultNull;
10 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveArrayDefaultOverride;
11 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveDefault;
12 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveDefaultNull;
13 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveDefaultOverride;
14 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveList;
15 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveListDefault;
16 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveListDefaultNull;
17 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveListDefaultOverride;
18 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitivePrimitives;
19 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveWrappers;
20 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveWrappersDefault;
21 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveWrappersDefaultNull;
22 import org.jboss.resteasy.test.resource.param.resource.MatrixParamAsPrimitiveWrappersDefaultOverride;
23 import org.jboss.resteasy.util.HttpHeaderNames;
24 import org.jboss.resteasy.util.HttpResponseCodes;
25 import org.jboss.resteasy.utils.PortProviderUtil;
26 import org.jboss.resteasy.utils.TestUtil;
27 import org.jboss.shrinkwrap.api.Archive;
28 import org.jboss.shrinkwrap.api.spec.WebArchive;
29 import org.junit.Assert;
30 import org.junit.Test;
31 import org.junit.runner.RunWith;
32
33 import javax.ws.rs.core.Response;
34
35 /**
36 * @tpSubChapter Parameters
37 * @tpChapter Integration tests
38 * @tpTestCaseDetails Test all variants of primitive matrix parameters (boolean, int, long, float, etc.)
39 * @tpSince RESTEasy 3.0.16
40 */
41 @RunWith(Arquillian.class)
42 @RunAsClient
43 public class MatrixParamAsPrimitiveTest {
44
45 public static final String ERROR_MESSAGE = "Wrong content of matrix parameter";
46
47 ResteasyClient client;
48
49 @Deployment
50 public static Archive<?> deploy() {
51 WebArchive war = TestUtil.prepareArchive(MatrixParamAsPrimitiveTest.class.getSimpleName());
52 war.addClass(MatrixParamAsPrimitiveTest.class);
53 return TestUtil.finishContainerPrepare(war, null,
54 MatrixParamAsPrimitivePrimitives.class,
55 MatrixParamAsPrimitiveDefault.class,
56 MatrixParamAsPrimitiveDefaultOverride.class,
57 MatrixParamAsPrimitiveDefaultNull.class,
58 MatrixParamAsPrimitiveWrappers.class,
59 MatrixParamAsPrimitiveWrappersDefault.class,
60 MatrixParamAsPrimitiveWrappersDefaultNull.class,
61 MatrixParamAsPrimitiveWrappersDefaultOverride.class,
62 MatrixParamAsPrimitiveList.class,
63 MatrixParamAsPrimitiveListDefault.class,
64 MatrixParamAsPrimitiveListDefaultNull.class,
65 MatrixParamAsPrimitiveListDefaultOverride.class,
66 MatrixParamAsPrimitiveArray.class,
67 MatrixParamAsPrimitiveArrayDefault.class,
68 MatrixParamAsPrimitiveArrayDefaultNull.class,
69 MatrixParamAsPrimitiveArrayDefaultOverride.class);
70 }
71
72 private String generateURL(String path) {
73 return PortProviderUtil.generateURL(path, MatrixParamAsPrimitiveTest.class.getSimpleName());
74 }
75
76 public void basicTest(String type, String value) {
77 String param = ";" + type + "=" + value;
78 {
79 client = new ResteasyClientBuilder().build();
80 Response response = client.target(generateURL("/" + param)).request()
81 .header(HttpHeaderNames.ACCEPT, "application/" + type)
82 .get();
83 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
84 response.close();
85 client.close();
86 }
87
88 {
89 client = new ResteasyClientBuilder().build();
90 Response response = client.target(generateURL("/wrappers" + param)).request()
91 .header(HttpHeaderNames.ACCEPT, "application/" + type)
92 .get();
93 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
94 response.close();
95 client.close();
96 }
97
98 {
99 client = new ResteasyClientBuilder().build();
100 Response response = client.target(generateURL("/list" + param + param + param)).request()
101 .header(HttpHeaderNames.ACCEPT, "application/" + type)
102 .get();
103 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
104 response.close();
105 client.close();
106 }
107
108 {
109 client = new ResteasyClientBuilder().build();
110 Response response = client.target(generateURL("/array" + param + param + param)).request()
111 .header(HttpHeaderNames.ACCEPT, "application/" + type)
112 .get();
113 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
114 response.close();
115 client.close();
116 }
117 }
118
119 public void testDefault(String base, String type, String value) {
120 {
121 client = new ResteasyClientBuilder().build();
122 Response response = client.target(generateURL(base + "default/null")).request()
123 .header(HttpHeaderNames.ACCEPT, "application/" + type)
124 .get();
125 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
126 response.close();
127 client.close();
128 }
129
130 {
131 client = new ResteasyClientBuilder().build();
132 Response response = client.target(generateURL(base + "default")).request()
133 .header(HttpHeaderNames.ACCEPT, "application/" + type)
134 .get();
135 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
136 response.close();
137 client.close();
138 }
139
140 String param = ";" + type + "=" + value;
141 {
142 client = new ResteasyClientBuilder().build();
143 Response response = client.target(generateURL(base + "default/override" + param)).request()
144 .header(HttpHeaderNames.ACCEPT, "application/" + type)
145 .get();
146 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
147 response.close();
148 client.close();
149 }
150 }
151
152 public void testDefault(String type, String value) {
153 testDefault("/", type, value);
154 }
155
156 public void testWrappersDefault(String type, String value) {
157 testDefault("/wrappers/", type, value);
158 }
159
160 public void testListDefault(String type, String value) {
161 testDefault("/list/", type, value);
162 }
163
164 public void testArrayDefault(String type, String value) {
165 testDefault("/array/", type, value);
166 }
167
168 /**
169 * @tpTestDetails Basic test for boolean
170 * @tpSince RESTEasy 3.0.16
171 */
172 @Test
173 public void testGetBoolean() {
174 basicTest("boolean", "true");
175 }
176
177 /**
178 * @tpTestDetails Test default value for boolean
179 * @tpSince RESTEasy 3.0.16
180 */
181 @Test
182 public void testGetBooleanPrimitivesDefault() {
183 testDefault("boolean", "true");
184 }
185
186 /**
187 * @tpTestDetails Test default value of boolean with wrapper
188 * @tpSince RESTEasy 3.0.16
189 */
190 @Test
191 public void testGetBooleanPrimitiveWrapperDefault() {
192 testWrappersDefault("boolean", "true");
193 }
194
195 /**
196 * @tpTestDetails Test default values of list of boolean
197 * @tpSince RESTEasy 3.0.16
198 */
199 @Test
200 public void testGetBooleanPrimitiveListDefault() {
201 testListDefault("boolean", "true");
202 testArrayDefault("boolean", "true");
203 }
204
205 /**
206 * @tpTestDetails Basic test for byte
207 * @tpSince RESTEasy 3.0.16
208 */
209 @Test
210 public void testGetByte() {
211 basicTest("byte", "127");
212 }
213
214 /**
215 * @tpTestDetails Test default value of byte
216 * @tpSince RESTEasy 3.0.16
217 */
218 @Test
219 public void testGetBytePrimitivesDefault() {
220 testDefault("byte", "127");
221 }
222
223 /**
224 * @tpTestDetails Test default value of byte with wrapper
225 * @tpSince RESTEasy 3.0.16
226 */
227 @Test
228 public void testGetBytePrimitiveWrappersDefault() {
229 testWrappersDefault("byte", "127");
230 }
231
232 /**
233 * @tpTestDetails Test default value of list and array of byte
234 * @tpSince RESTEasy 3.0.16
235 */
236 @Test
237 public void testGetBytePrimitiveListDefault() {
238 testListDefault("byte", "127");
239 testArrayDefault("byte", "127");
240 }
241
242 /**
243 * @tpTestDetails Basic test for short
244 * @tpSince RESTEasy 3.0.16
245 */
246 @Test
247 public void testGetShort() {
248 basicTest("short", "32767");
249 }
250
251 /**
252 * @tpTestDetails Test default values of short
253 * @tpSince RESTEasy 3.0.16
254 */
255 @Test
256 public void testGetShortPrimtivesDefault() {
257 testDefault("short", "32767");
258 }
259
260 /**
261 * @tpTestDetails Test default values of short with wrapper
262 * @tpSince RESTEasy 3.0.16
263 */
264 @Test
265 public void testGetShortPrimtiveWrappersDefault() {
266 testWrappersDefault("short", "32767");
267 }
268
269 /**
270 * @tpTestDetails Test default values of list and array of short
271 * @tpSince RESTEasy 3.0.16
272 */
273 @Test
274 public void testGetShortPrimtiveListDefault() {
275 testListDefault("short", "32767");
276 testArrayDefault("short", "32767");
277 }
278
279 /**
280 * @tpTestDetails Basic test for int
281 * @tpSince RESTEasy 3.0.16
282 */
283 @Test
284 public void testGetInt() {
285 basicTest("int", "2147483647");
286 }
287
288 /**
289 * @tpTestDetails Test default value of int
290 * @tpSince RESTEasy 3.0.16
291 */
292 @Test
293 public void testGetIntPrimitivesDefault() {
294 testDefault("int", "2147483647");
295 }
296
297 /**
298 * @tpTestDetails Test default value of int with wrapper
299 * @tpSince RESTEasy 3.0.16
300 */
301 @Test
302 public void testGetIntPrimitiveWrappersDefault() {
303 testWrappersDefault("int", "2147483647");
304 }
305
306 /**
307 * @tpTestDetails Test default value of list and array of integer
308 * @tpSince RESTEasy 3.0.16
309 */
310 @Test
311 public void testGetIntPrimitiveListDefault() {
312 testListDefault("int", "2147483647");
313 testArrayDefault("int", "2147483647");
314 }
315
316 /**
317 * @tpTestDetails Basic test for long
318 * @tpSince RESTEasy 3.0.16
319 */
320 @Test
321 public void testGetLong() {
322 basicTest("long", "9223372036854775807");
323 }
324
325 /**
326 * @tpTestDetails Test default value of long
327 * @tpSince RESTEasy 3.0.16
328 */
329 @Test
330 public void testGetLongPrimitivesDefault() {
331 testDefault("long", "9223372036854775807");
332 }
333
334 /**
335 * @tpTestDetails Test default value of long with wrapper
336 * @tpSince RESTEasy 3.0.16
337 */
338 @Test
339 public void testGetLongPrimitiveWrappersDefault() {
340 testWrappersDefault("long", "9223372036854775807");
341 }
342
343 /**
344 * @tpTestDetails Test default value of list and array of long
345 * @tpSince RESTEasy 3.0.16
346 */
347 @Test
348 public void testGetLongPrimitiveListDefault() {
349 testListDefault("long", "9223372036854775807");
350 testArrayDefault("long", "9223372036854775807");
351 }
352
353 /**
354 * @tpTestDetails Basic test for float
355 * @tpSince RESTEasy 3.0.16
356 */
357 @Test
358 public void testGetFloat() {
359 basicTest("float", "3.14159265");
360 }
361
362 /**
363 * @tpTestDetails Test default value of float
364 * @tpSince RESTEasy 3.0.16
365 */
366 @Test
367 public void testGetFloatPrimitivesDefault() {
368 testDefault("float", "3.14159265");
369 }
370
371 /**
372 * @tpTestDetails Test default value of float with wrapper
373 * @tpSince RESTEasy 3.0.16
374 */
375 @Test
376 public void testGetFloatPrimitiveWrappersDefault() {
377 testWrappersDefault("float", "3.14159265");
378 }
379
380 /**
381 * @tpTestDetails Test default value of array and list of float
382 * @tpSince RESTEasy 3.0.16
383 */
384 @Test
385 public void testGetFloatPrimitiveListDefault() {
386 testListDefault("float", "3.14159265");
387 testArrayDefault("float", "3.14159265");
388 }
389
390 /**
391 * @tpTestDetails Basic test for double
392 * @tpSince RESTEasy 3.0.16
393 */
394 @Test
395 public void testGetDouble() {
396 basicTest("double", "3.14159265358979");
397 }
398
399 /**
400 * @tpTestDetails Test default value of double
401 * @tpSince RESTEasy 3.0.16
402 */
403 @Test
404 public void testGetDoublePrimitivesDefault() {
405 testDefault("double", "3.14159265358979");
406 }
407
408 /**
409 * @tpTestDetails Test default value of double with wrapper
410 * @tpSince RESTEasy 3.0.16
411 */
412 @Test
413 public void testGetDoublePrimitiveWrappersDefault() {
414 testWrappersDefault("double", "3.14159265358979");
415 }
416
417 /**
418 * @tpTestDetails Test default value of list and array of double
419 * @tpSince RESTEasy 3.0.16
420 */
421 @Test
422 public void testGetDoublePrimitiveListDefault() {
423 testListDefault("double", "3.14159265358979");
424 testArrayDefault("double", "3.14159265358979");
425 }
426
427 /**
428 * @tpTestDetails Test wrong data stored in int format
429 * @tpSince RESTEasy 3.0.16
430 */
431 @Test
432 public void testBadPrimitiveValue() {
433 {
434 client = new ResteasyClientBuilder().build();
435 Response response = client.target(generateURL("/;int=abcdef")).request()
436 .header(HttpHeaderNames.ACCEPT, "application/int")
437 .get();
438 Assert.assertEquals(HttpResponseCodes.SC_NOT_FOUND, response.getStatus());
439 response.close();
440 client.close();
441 }
442 }
443
444 /**
445 * @tpTestDetails Test wrong data stored in int format, wrapper is used
446 * @tpSince RESTEasy 3.0.16
447 */
448 @Test
449 public void testBadPrimitiveWrapperValue() {
450 {
451 client = new ResteasyClientBuilder().build();
452 Response response = client.target(generateURL("/wrappers;int=abcdef")).request()
453 .header(HttpHeaderNames.ACCEPT, "application/int")
454 .get();
455 Assert.assertEquals(HttpResponseCodes.SC_NOT_FOUND, response.getStatus());
456 response.close();
457 client.close();
458 }
459 }
460
461 /**
462 * @tpTestDetails Test wrong data stored in list of int
463 * @tpSince RESTEasy 3.0.16
464 */
465 @Test
466 public void testBadPrimitiveListValue() {
467 {
468 client = new ResteasyClientBuilder().build();
469 Response response = client.target(generateURL("/list;int=abcdef;int=abcdef")).request()
470 .header(HttpHeaderNames.ACCEPT, "application/int")
471 .get();
472 Assert.assertEquals(HttpResponseCodes.SC_NOT_FOUND, response.getStatus());
473 response.close();
474 client.close();
475 }
476 }
477 }
+0
-86
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/MatrixPathParamTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.MatrixParam;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.client.ClientBuilder;
6
7 import org.jboss.arquillian.container.test.api.Deployment;
8 import org.jboss.arquillian.container.test.api.RunAsClient;
9 import org.jboss.arquillian.junit.Arquillian;
10 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 @RunWith(Arquillian.class)
20 @RunAsClient
21 public class MatrixPathParamTest
22 {
23
24 @Deployment
25 public static Archive<?> deploy() throws Exception {
26 WebArchive war = TestUtil.prepareArchive(MatrixPathParamTest.class.getSimpleName());
27 return TestUtil.finishContainerPrepare(war, null, TestResourceServer.class, TestSubResourceServer.class);
28 }
29
30 private String generateBaseUrl() {
31 return PortProviderUtil.generateBaseUrl(MatrixPathParamTest.class.getSimpleName());
32 }
33
34 @Path("/")
35 static public class TestResourceServer
36 {
37 @Path("matrix1")
38 public TestSubResourceServer getM1(@MatrixParam("m1") String m1)
39 {
40 return new TestSubResourceServer(m1);
41 }
42 }
43
44 static public class TestSubResourceServer
45 {
46 protected String m1;
47
48 TestSubResourceServer(String m1)
49 {
50 this.m1 = m1;
51 }
52
53 @GET
54 @Path("matrix2")
55 public String getM2(@MatrixParam("m2") String m2)
56 {
57 return m1 + m2;
58 }
59 }
60
61 @Path("/")
62 public interface TestInterfaceClient
63 {
64 @Path("matrix1")
65 public TestSubInterfaceClient getM1(@MatrixParam("m1") String m1);
66 }
67
68 public interface TestSubInterfaceClient
69 {
70 @GET
71 @Path("matrix2")
72 public String getM2(@MatrixParam("m2") String m2);
73 }
74
75 @Test
76 public void testSingleAcceptHeader() throws Exception
77 {
78 ResteasyWebTarget target = (ResteasyWebTarget) ClientBuilder.newClient().target(generateBaseUrl());
79 TestInterfaceClient proxy = target.proxy(TestInterfaceClient.class);
80
81 String result = proxy.getM1("a").getM2("b");
82 Assert.assertEquals("ab", result);
83 }
84
85 }
+0
-70
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/ParamConverterTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.param.resource.ParamConverterClient;
8 import org.jboss.resteasy.test.resource.param.resource.ParamConverterDefaultClient;
9 import org.jboss.resteasy.test.resource.param.resource.ParamConverterDefaultResource;
10 import org.jboss.resteasy.test.resource.param.resource.ParamConverterPOJO;
11 import org.jboss.resteasy.test.resource.param.resource.ParamConverterPOJOConverter;
12 import org.jboss.resteasy.test.resource.param.resource.ParamConverterPOJOConverterProvider;
13 import org.jboss.resteasy.test.resource.param.resource.ParamConverterResource;
14 import org.jboss.resteasy.utils.PortProviderUtil;
15 import org.jboss.resteasy.utils.TestUtil;
16 import org.jboss.shrinkwrap.api.Archive;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Test;
19 import org.junit.runner.RunWith;
20
21 /**
22 * @tpSubChapter Parameters
23 * @tpChapter Integration tests
24 * @tpTestCaseDetails Test for ParamConverter
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class ParamConverterTest {
30
31 @Deployment
32 public static Archive<?> deploy() {
33 WebArchive war = TestUtil.prepareArchive(ParamConverterTest.class.getSimpleName());
34 war.addClass(ParamConverterPOJOConverter.class);
35 war.addClass(ParamConverterPOJO.class);
36 war.addClass(ParamConverterDefaultClient.class);
37 war.addClass(ParamConverterClient.class);
38 return TestUtil.finishContainerPrepare(war, null, ParamConverterPOJOConverterProvider.class,
39 ParamConverterResource.class, ParamConverterDefaultResource.class);
40 }
41
42 private String generateBaseUrl() {
43 return PortProviderUtil.generateBaseUrl(ParamConverterTest.class.getSimpleName());
44 }
45
46 /**
47 * @tpTestDetails Set specific values
48 * @tpSince RESTEasy 3.0.16
49 */
50 @Test
51 public void testIt() throws Exception {
52 ResteasyClient client = new ResteasyClientBuilder().build();
53 ParamConverterClient proxy = client.target(generateBaseUrl()).proxy(ParamConverterClient.class);
54 proxy.put("pojo", "pojo", "pojo", "pojo");
55 client.close();
56 }
57
58 /**
59 * @tpTestDetails Check default values
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void testDefault() throws Exception {
64 ResteasyClient client = new ResteasyClientBuilder().build();
65 ParamConverterDefaultClient proxy = client.target(generateBaseUrl()).proxy(ParamConverterDefaultClient.class);
66 proxy.put();
67 client.close();
68 }
69 }
+0
-74
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/ParamTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ProxyFactory;
6 import org.jboss.resteasy.test.resource.param.resource.ParamInterfaceResource;
7 import org.jboss.resteasy.test.resource.param.resource.ParamResource;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.Assert;
13 import org.junit.Test;
14 import org.junit.runner.RunWith;
15
16 /**
17 * @tpSubChapter Parameters
18 * @tpChapter Integration tests
19 * @tpTestCaseDetails Regression test for RESTEASY-423 and RESTEASY-522
20 * @tpSince RESTEasy 3.0.16
21 */
22 @RunWith(Arquillian.class)
23 @RunAsClient
24 public class ParamTest {
25
26 @Deployment
27 public static Archive<?> deploy() throws Exception {
28 WebArchive war = TestUtil.prepareArchive(ParamTest.class.getSimpleName());
29 war.addClass(ParamInterfaceResource.class);
30 return TestUtil.finishContainerPrepare(war, null, ParamResource.class);
31 }
32
33 private String generateBaseUrl() {
34 return PortProviderUtil.generateBaseUrl(ParamTest.class.getSimpleName());
35 }
36
37
38 /**
39 * @tpTestDetails Null matrix parameters should be accepted by the reasteasy client library (RESTEASY-423)
40 * @tpSince RESTEasy 3.0.16
41 */
42 @Test
43 public void testNullMatrixParam() throws Exception {
44 ParamInterfaceResource proxy = ProxyFactory.create(ParamInterfaceResource.class, generateBaseUrl());
45 String rtn = proxy.getMatrix(null);
46 Assert.assertEquals("null", rtn);
47 }
48
49 /**
50 * @tpTestDetails RestEasy Client Framework should not throw null point exception when
51 * the @CookieParam() is null (RESTEASY-522)
52 * @tpSince RESTEasy 3.0.16
53 */
54 @Test
55 public void testNullCookieParam() throws Exception {
56 ParamInterfaceResource proxy = ProxyFactory.create(ParamInterfaceResource.class, generateBaseUrl());
57 String rtn = proxy.getCookie(null);
58 Assert.assertEquals("null", rtn);
59 }
60
61 /**
62 * @tpTestDetails RestEasy Client Framework should not throw null point exception when
63 * the @HeaderParam() is null (RESTEASY-522)
64 * @tpSince RESTEasy 3.0.16
65 */
66 @Test
67 public void testNullHeaderParam() throws Exception {
68 ParamInterfaceResource proxy = ProxyFactory.create(ParamInterfaceResource.class, generateBaseUrl());
69 String rtn = proxy.getHeader(null);
70 Assert.assertEquals("null", rtn);
71 }
72
73 }
+0
-582
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/QueryParamAsPrimitiveTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResource;
9 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceArray;
10 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceArrayDefault;
11 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceArrayDefaultNull;
12 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceArrayDefaultOverride;
13 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceDefault;
14 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceDefaultNull;
15 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceDefaultOverride;
16 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceList;
17 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceListDefault;
18 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceListDefaultNull;
19 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceListDefaultOverride;
20 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceQueryPrimitivesInterface;
21 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceResourceArray;
22 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceResourceListInterface;
23 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceResourceWrappersInterface;
24 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceWrappers;
25 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceWrappersDefault;
26 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceWrappersDefaultNull;
27 import org.jboss.resteasy.test.resource.param.resource.QueryParamAsPrimitiveResourceWrappersDefaultOverride;
28 import org.jboss.resteasy.util.HttpHeaderNames;
29 import org.jboss.resteasy.util.HttpResponseCodes;
30 import org.jboss.resteasy.utils.PortProviderUtil;
31 import org.jboss.resteasy.utils.TestUtil;
32 import org.jboss.shrinkwrap.api.Archive;
33 import org.jboss.shrinkwrap.api.spec.WebArchive;
34 import org.junit.AfterClass;
35 import org.junit.Assert;
36 import org.junit.BeforeClass;
37 import org.junit.Test;
38 import org.junit.runner.RunWith;
39
40 import javax.ws.rs.client.Invocation;
41 import javax.ws.rs.core.Response;
42 import java.util.ArrayList;
43 import java.util.List;
44
45 import static org.jboss.resteasy.util.HttpClient4xUtils.updateQuery;
46
47 /**
48 * @tpSubChapter Parameters
49 * @tpChapter Integration tests
50 * @tpTestCaseDetails Test all variants of primitive query parameters (boolean, int, long, float, etc.)
51 * @tpSince RESTEasy 3.0.16
52 */
53 @RunWith(Arquillian.class)
54 @RunAsClient
55 public class QueryParamAsPrimitiveTest {
56
57 public static final String ERROR_MESSAGE = "Wrong object received";
58
59 private static QueryParamAsPrimitiveResourceQueryPrimitivesInterface resourceQueryPrimitives;
60
61 private static QueryParamAsPrimitiveResourceResourceWrappersInterface resourceQueryPrimitiveWrappers;
62
63 private static QueryParamAsPrimitiveResourceResourceListInterface resourceQueryPrimitiveList;
64
65 private static QueryParamAsPrimitiveResourceResourceArray resourceQueryPrimitiveArray;
66 private static ResteasyClient client;
67
68 @Deployment
69 public static Archive<?> deploy() throws Exception {
70 WebArchive war = TestUtil.prepareArchive(QueryParamAsPrimitiveTest.class.getSimpleName());
71 war.addClass(QueryParamAsPrimitiveResourceQueryPrimitivesInterface.class);
72 war.addClass(QueryParamAsPrimitiveResourceResourceArray.class);
73 war.addClass(QueryParamAsPrimitiveResourceResourceListInterface.class);
74 war.addClass(QueryParamAsPrimitiveResourceResourceWrappersInterface.class);
75 war.addClass(QueryParamAsPrimitiveTest.class);
76 return TestUtil.finishContainerPrepare(war, null,
77 QueryParamAsPrimitiveResource.class,
78 QueryParamAsPrimitiveResourceDefault.class,
79 QueryParamAsPrimitiveResourceDefaultOverride.class,
80 QueryParamAsPrimitiveResourceDefaultNull.class,
81 QueryParamAsPrimitiveResourceWrappers.class,
82 QueryParamAsPrimitiveResourceWrappersDefault.class,
83 QueryParamAsPrimitiveResourceWrappersDefaultNull.class,
84 QueryParamAsPrimitiveResourceWrappersDefaultOverride.class,
85 QueryParamAsPrimitiveResourceList.class,
86 QueryParamAsPrimitiveResourceListDefault.class,
87 QueryParamAsPrimitiveResourceListDefaultNull.class,
88 QueryParamAsPrimitiveResourceListDefaultOverride.class,
89 QueryParamAsPrimitiveResourceArray.class,
90 QueryParamAsPrimitiveResourceArrayDefault.class,
91 QueryParamAsPrimitiveResourceArrayDefaultNull.class,
92 QueryParamAsPrimitiveResourceArrayDefaultOverride.class);
93 }
94
95 @BeforeClass
96 public static void before() throws Exception {
97 client = new ResteasyClientBuilder().build();
98 resourceQueryPrimitives = ProxyBuilder.builder(QueryParamAsPrimitiveResourceQueryPrimitivesInterface.class, client.target(generateBaseUrl())).build();
99 resourceQueryPrimitiveWrappers = ProxyBuilder.builder(QueryParamAsPrimitiveResourceResourceWrappersInterface.class, client.target(generateBaseUrl())).build();
100 resourceQueryPrimitiveList = ProxyBuilder.builder(QueryParamAsPrimitiveResourceResourceListInterface.class, client.target(generateBaseUrl())).build();
101 resourceQueryPrimitiveArray = ProxyBuilder.builder(QueryParamAsPrimitiveResourceResourceArray.class, client.target(generateBaseUrl())).build();
102 }
103
104 @AfterClass
105 public static void after() throws Exception {
106 client.close();
107 }
108
109 private static String generateURL(String path) {
110 return PortProviderUtil.generateURL(path, QueryParamAsPrimitiveTest.class.getSimpleName());
111 }
112
113 private static String generateBaseUrl() {
114 return PortProviderUtil.generateBaseUrl(QueryParamAsPrimitiveTest.class.getSimpleName());
115 }
116
117 public void basicTest(String type, String value) {
118 String param = type + "=" + value;
119
120 {
121 String uri = updateQuery(generateURL("/"), param);
122 Invocation.Builder request = client.target(uri).request();
123 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
124 try {
125 Response response = request.get();
126 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
127 response.close();
128 } catch (Exception e) {
129 throw new RuntimeException(e);
130 }
131 }
132
133 {
134 String uri = updateQuery(generateURL("/wrappers"), param);
135 Invocation.Builder request = client.target(uri).request();
136 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
137 try {
138 Response response = request.get();
139 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
140 response.close();
141 } catch (Exception e) {
142 throw new RuntimeException(e);
143 }
144 }
145
146 {
147 String uri = updateQuery(generateURL("/list"), param + "&" + param + "&" + param);
148 Invocation.Builder request = client.target(uri).request();
149 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
150 try {
151 Response response = request.get();
152 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
153 response.close();
154 } catch (Exception e) {
155 throw new RuntimeException(e);
156 }
157 }
158
159 {
160 String uri = updateQuery(generateURL("/array"), param + "&" + param + "&" + param);
161 Invocation.Builder request = client.target(uri).request();
162 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
163 try {
164 Response response = request.get();
165 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
166 response.close();
167 } catch (Exception e) {
168 throw new RuntimeException(e);
169 }
170 }
171 }
172
173 public void testDefault(String base, String type, String value) {
174 {
175 Invocation.Builder request = client.target(generateURL("" + base + "default/null")).request();
176 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
177 try {
178 Response response = request.get();
179 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
180 response.close();
181 } catch (Exception e) {
182 throw new RuntimeException(e);
183 }
184 }
185
186 {
187 Invocation.Builder request = client.target(generateURL("" + base + "default")).request();
188 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
189 try {
190 Response response = request.get();
191 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
192 response.close();
193 } catch (Exception e) {
194 throw new RuntimeException(e);
195 }
196 }
197
198 String param = type + "=" + value;
199 {
200 String uri = updateQuery(generateURL("" + base + "default/override"), param);
201 Invocation.Builder request = client.target(uri).request();
202 request.header(HttpHeaderNames.ACCEPT, "application/" + type);
203 try {
204 Response response = request.get();
205 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
206 response.close();
207 } catch (Exception e) {
208 throw new RuntimeException(e);
209 }
210 }
211 }
212
213 public void testDefault(String type, String value) {
214 testDefault("/", type, value);
215 }
216
217 public void testWrappersDefault(String type, String value) {
218 testDefault("/wrappers/", type, value);
219 }
220
221 public void testListDefault(String type, String value) {
222 testDefault("/list/", type, value);
223 }
224
225 public void testArrayDefault(String type, String value) {
226 testDefault("/array/", type, value);
227 }
228
229 /**
230 * @tpTestDetails Test boolean primitive object for get request
231 * @tpSince RESTEasy 3.0.16
232 */
233 @Test
234 public void testGetBoolean() {
235 basicTest("boolean", "true");
236 resourceQueryPrimitives.doGet(true);
237 resourceQueryPrimitiveWrappers.doGet(true);
238 List<Boolean> list = new ArrayList<Boolean>();
239 list.add(Boolean.TRUE);
240 list.add(Boolean.TRUE);
241 list.add(Boolean.TRUE);
242 resourceQueryPrimitiveList.doGetBoolean(list);
243 boolean[] array =
244 {true, true, true};
245 resourceQueryPrimitiveArray.doGetBoolean(array);
246 }
247
248 /**
249 * @tpTestDetails Test boolean primitive object
250 * @tpSince RESTEasy 3.0.16
251 */
252 @Test
253 public void testGetBooleanPrimitivesDefault() {
254 testDefault("boolean", "true");
255 }
256
257 /**
258 * @tpTestDetails Test boolean primitive object with proxy
259 * @tpSince RESTEasy 3.0.16
260 */
261 @Test
262 public void testGetBooleanPrimitiveWrapperDefault() {
263 testWrappersDefault("boolean", "true");
264 }
265
266 /**
267 * @tpTestDetails Test boolean primitive objects in list
268 * @tpSince RESTEasy 3.0.16
269 */
270 @Test
271 public void testGetBooleanPrimitiveListDefault() {
272 testListDefault("boolean", "true");
273 }
274
275 /**
276 * @tpTestDetails Test boolean primitive objects in array
277 * @tpSince RESTEasy 3.0.16
278 */
279 @Test
280 public void testGetBooleanPrimitiveArrayDefault() {
281 testArrayDefault("boolean", "true");
282 }
283
284 /**
285 * @tpTestDetails Test byte primitive object for get method
286 * @tpSince RESTEasy 3.0.16
287 */
288 @Test
289 public void testGetByte() {
290 basicTest("byte", "127");
291 resourceQueryPrimitives.doGet((byte) 127);
292 resourceQueryPrimitiveWrappers.doGet((byte) 127);
293 List<Byte> list = new ArrayList<Byte>();
294 list.add(new Byte((byte) 127));
295 list.add(new Byte((byte) 127));
296 list.add(new Byte((byte) 127));
297 resourceQueryPrimitiveList.doGetByte(list);
298 byte[] array =
299 {(byte) 127, (byte) 127, (byte) 127};
300 resourceQueryPrimitiveArray.doGetByte(array);
301 }
302
303 /**
304 * @tpTestDetails Test byte primitive object
305 * @tpSince RESTEasy 3.0.16
306 */
307 @Test
308 public void testGetBytePrimitivesDefault() {
309 testDefault("byte", "127");
310 }
311
312 /**
313 * @tpTestDetails Test byte primitive object with proxy
314 * @tpSince RESTEasy 3.0.16
315 */
316 @Test
317 public void testGetBytePrimitiveWrappersDefault() {
318 testWrappersDefault("byte", "127");
319 }
320
321 /**
322 * @tpTestDetails Test byte primitive objects in list
323 * @tpSince RESTEasy 3.0.16
324 */
325 @Test
326 public void testGetBytePrimitiveListDefault() {
327 testListDefault("byte", "127");
328 }
329
330 /**
331 * @tpTestDetails Test byte primitive objects in array
332 * @tpSince RESTEasy 3.0.16
333 */
334 @Test
335 public void testGetBytePrimitiveArrayDefault() {
336 testArrayDefault("byte", "127");
337 }
338
339 /**
340 * @tpTestDetails Test short primitive object for get method
341 * @tpSince RESTEasy 3.0.16
342 */
343 @Test
344 public void testGetShort() {
345 basicTest("short", "32767");
346 }
347
348 /**
349 * @tpTestDetails Test short primitive object
350 * @tpSince RESTEasy 3.0.16
351 */
352 @Test
353 public void testGetShortPrimtivesDefault() {
354 testDefault("short", "32767");
355 }
356
357 /**
358 * @tpTestDetails Test short primitive object with proxy
359 * @tpSince RESTEasy 3.0.16
360 */
361 @Test
362 public void testGetShortPrimtiveWrappersDefault() {
363 testWrappersDefault("short", "32767");
364 }
365
366 /**
367 * @tpTestDetails Test short primitive objects in list
368 * @tpSince RESTEasy 3.0.16
369 */
370 @Test
371 public void testGetShortPrimtiveListDefault() {
372 testListDefault("short", "32767");
373 }
374
375 /**
376 * @tpTestDetails Test int primitive object for get method
377 * @tpSince RESTEasy 3.0.16
378 */
379 @Test
380 public void testGetInt() {
381 basicTest("int", "2147483647");
382 }
383
384 /**
385 * @tpTestDetails Test int primitive object
386 * @tpSince RESTEasy 3.0.16
387 */
388 @Test
389 public void testGetIntPrimitivesDefault() {
390 testDefault("int", "2147483647");
391 }
392
393 /**
394 * @tpTestDetails Test int primitive object with proxy
395 * @tpSince RESTEasy 3.0.16
396 */
397 @Test
398 public void testGetIntPrimitiveWrappersDefault() {
399 testWrappersDefault("int", "2147483647");
400 }
401
402 /**
403 * @tpTestDetails Test int primitive objects in list
404 * @tpSince RESTEasy 3.0.16
405 */
406 @Test
407 public void testGetIntPrimitiveListDefault() {
408 testListDefault("int", "2147483647");
409 }
410
411 /**
412 * @tpTestDetails Test long primitive object with get method
413 * @tpSince RESTEasy 3.0.16
414 */
415 @Test
416 public void testGetLong() {
417 basicTest("long", "9223372036854775807");
418 }
419
420 /**
421 * @tpTestDetails Test long primitive object
422 * @tpSince RESTEasy 3.0.16
423 */
424 @Test
425 public void testGetLongPrimitivesDefault() {
426 testDefault("long", "9223372036854775807");
427 }
428
429 /**
430 * @tpTestDetails Test long primitive object with proxy
431 * @tpSince RESTEasy 3.0.16
432 */
433 @Test
434 public void testGetLongPrimitiveWrappersDefault() {
435 testWrappersDefault("long", "9223372036854775807");
436 }
437
438 /**
439 * @tpTestDetails Test long primitive objects in list
440 * @tpSince RESTEasy 3.0.16
441 */
442 @Test
443 public void testGetLongPrimitiveListDefault() {
444 testListDefault("long", "9223372036854775807");
445 }
446
447 /**
448 * @tpTestDetails Test float primitive object with get method
449 * @tpSince RESTEasy 3.0.16
450 */
451 @Test
452 public void testGetFloat() {
453 basicTest("float", "3.14159265");
454 }
455
456 /**
457 * @tpTestDetails Test float primitive object
458 * @tpSince RESTEasy 3.0.16
459 */
460 @Test
461 public void testGetFloatPrimitivesDefault() {
462 testDefault("float", "3.14159265");
463 }
464
465 /**
466 * @tpTestDetails Test float primitive object with proxy
467 * @tpSince RESTEasy 3.0.16
468 */
469 @Test
470 public void testGetFloatPrimitiveWrappersDefault() {
471 testWrappersDefault("float", "3.14159265");
472 }
473
474 /**
475 * @tpTestDetails Test float primitive objects in list
476 * @tpSince RESTEasy 3.0.16
477 */
478 @Test
479 public void testGetFloatPrimitiveListDefault() {
480 testListDefault("float", "3.14159265");
481 }
482
483 /**
484 * @tpTestDetails Test double primitive object with get method
485 * @tpSince RESTEasy 3.0.16
486 */
487 @Test
488 public void testGetDouble() {
489 basicTest("double", "3.14159265358979");
490 }
491
492 /**
493 * @tpTestDetails Test double primitive object
494 * @tpSince RESTEasy 3.0.16
495 */
496 @Test
497 public void testGetDoublePrimitivesDefault() {
498 testDefault("double", "3.14159265358979");
499 }
500
501 /**
502 * @tpTestDetails Test double primitive object with proxy
503 * @tpSince RESTEasy 3.0.16
504 */
505 @Test
506 public void testGetDoublePrimitiveWrappersDefault() {
507 testWrappersDefault("double", "3.14159265358979");
508 }
509
510 /**
511 * @tpTestDetails Test double primitive objects in list
512 * @tpSince RESTEasy 3.0.16
513 */
514 @Test
515 public void testGetDoublePrimitiveListDefault() {
516 testListDefault("double", "3.14159265358979");
517 }
518
519 /**
520 * @tpTestDetails Negative testing: accept only int, but string is provided. Error is excepted.
521 * @tpSince RESTEasy 3.0.16
522 */
523 @Test
524 public void testBadPrimitiveValue() {
525 {
526 String uri = updateQuery(generateURL("/"), "int=abcdef");
527 Invocation.Builder request = client.target(uri).request();
528 request.header(HttpHeaderNames.ACCEPT, "application/int");
529 try {
530 Response response = request.get();
531 Assert.assertEquals(404, response.getStatus());
532 response.close();
533 } catch (Exception e) {
534 throw new RuntimeException(e);
535 }
536 }
537 }
538
539 /**
540 * @tpTestDetails Negative testing: accept only int, but string is provided. Error is excepted.
541 * Proxy is used.
542 * @tpSince RESTEasy 3.0.16
543 */
544 @Test
545 public void testBadPrimitiveWrapperValue() {
546 {
547 String uri = updateQuery(generateURL("/wrappers"), "int=abcdef");
548 Invocation.Builder request = client.target(uri).request();
549 request.header(HttpHeaderNames.ACCEPT, "application/int");
550 try {
551 Response response = request.get();
552 Assert.assertEquals(404, response.getStatus());
553 response.close();
554 } catch (Exception e) {
555 throw new RuntimeException(e);
556 }
557 }
558 }
559
560 /**
561 * @tpTestDetails Negative testing: accept only int, but string is provided. Error is excepted.
562 * List is tested
563 * @tpSince RESTEasy 3.0.16
564 */
565 @Test
566 public void testBadPrimitiveListValue() {
567 {
568 String uri = updateQuery(generateURL("/list"), "int=abcdef&int=abcdef");
569 Invocation.Builder request = client.target(uri).request();
570 request.header(HttpHeaderNames.ACCEPT, "application/int");
571 try {
572 Response response = request.get();
573 Assert.assertEquals(404, response.getStatus());
574 response.close();
575 } catch (Exception e) {
576 throw new RuntimeException(e);
577 }
578 }
579 }
580
581 }
+0
-55
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/QueryParamWithMultipleEqualsTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.param.resource.QueryParamWithMultipleEqualsResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16 import javax.ws.rs.core.Response;
17
18 /**
19 * @tpSubChapter Resource
20 * @tpChapter Integration tests
21 * @tpSince RESTEasy 3.0.16
22 * @tpTestCaseDetails Test query params with multiple equals
23 */
24 @RunWith(Arquillian.class)
25 @RunAsClient
26 public class QueryParamWithMultipleEqualsTest {
27
28 @Deployment
29 public static Archive<?> deploy() {
30 WebArchive war = TestUtil.prepareArchive(QueryParamWithMultipleEqualsTest.class.getSimpleName());
31 return TestUtil.finishContainerPrepare(war, null, QueryParamWithMultipleEqualsResource.class);
32 }
33
34 private String generateURL(String path) {
35 return PortProviderUtil.generateURL(path, QueryParamWithMultipleEqualsTest.class.getSimpleName());
36 }
37
38 /**
39 * @tpTestDetails Test query parameter "foo=weird=but=valid"
40 * @tpSince RESTEasy 3.0.16
41 */
42 @Test
43 public void testQueryParam() throws Exception {
44 ResteasyClient client = new ResteasyClientBuilder().build();
45 Response response = client.target(generateURL("/test?foo=weird=but=valid")).request().get();
46
47 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
48 String entity = response.readEntity(String.class);
49 Assert.assertEquals("Wrong content of response", "weird=but=valid", entity);
50
51 response.close();
52 client.close();
53 }
54 }
+0
-69
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/QueryTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.resource.param.resource.QueryResource;
6 import org.jboss.resteasy.test.resource.param.resource.QuerySearchQuery;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.AfterClass;
13 import org.junit.Assert;
14 import org.junit.BeforeClass;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.client.WebTarget;
21 import javax.ws.rs.core.Response;
22
23 /**
24 * @tpSubChapter Parameters
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Test for @Query param of the resource, RESTEASY-715
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class QueryTest {
32
33 static Client client;
34
35 @Deployment
36 public static Archive<?> deploy() {
37 WebArchive war = TestUtil.prepareArchive(QueryTest.class.getSimpleName());
38 return TestUtil.finishContainerPrepare(war, null, QueryResource.class, QuerySearchQuery.class);
39 }
40
41 @BeforeClass
42 public static void setup() {
43 client = ClientBuilder.newClient();
44 }
45
46 @AfterClass
47 public static void cleanup() {
48 client.close();
49 }
50
51 private String generateURL(String path) {
52 return PortProviderUtil.generateURL(path, QueryTest.class.getSimpleName());
53 }
54
55 /**
56 * @tpTestDetails Use resource with @Query annotation with the parameter of custom type which consist of @QueryParam fields.
57 * Resteasy correctly parses the uri to get all specified parameters
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testQueryParamPrefix() throws Exception {
62 WebTarget target = client.target(generateURL("/search?term=t1&order=ASC"));
63 Response response = target.request().get();
64
65 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
66 Assert.assertEquals("term: 't1', order: 'ASC', limit: 'null'", response.readEntity(String.class));
67 }
68 }
+0
-58
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/SerializableWithParametersTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.resource.param.resource.SerializableWithParametersObject;
8 import org.jboss.resteasy.test.resource.param.resource.SerializableWithParametersResource;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.Invocation;
18
19 /**
20 * @tpSubChapter Resource
21 * @tpChapter Integration tests
22 * @tpSince RESTEasy 3.0.16
23 * @tpTestCaseDetails Regression test for RESTEASY-839
24 */
25 @RunWith(Arquillian.class)
26 @RunAsClient
27 public class SerializableWithParametersTest {
28
29 @Deployment
30 public static Archive<?> deploy() {
31 WebArchive war = TestUtil.prepareArchive(SerializableWithParametersTest.class.getSimpleName());
32 war.addClass(SerializableWithParametersObject.class);
33 war.addAsResource(SerializableWithParametersTest.class.getPackage(), "javax.ws.rs.ext.Providers", "META-INF/services/javax.ws.rs.ext.Providers");
34 return TestUtil.finishContainerPrepare(war, null, SerializableWithParametersResource.class);
35 }
36
37 private String generateURL(String path) {
38 return PortProviderUtil.generateURL(path, SerializableWithParametersTest.class.getSimpleName());
39 }
40
41 /**
42 * @tpTestDetails Get serializable object.
43 * Test was updated by RESTEASY-1269 in this
44 * commit: https://github.com/resteasy/Resteasy/commit/bb8657c9808763d4c4b9227f6a2fcf47b9146636
45 * Serializable provider was deprecated in RESTEASY-1461
46 * @tpSince RESTEasy 3.0.16
47 */
48 @SuppressWarnings("deprecation")
49 @Test
50 public void testSerialize() throws Exception {
51 ResteasyClient client = new ResteasyClientBuilder().register(org.jboss.resteasy.plugins.providers.SerializableProvider.class).build();
52 Invocation.Builder request = client.target(generateURL("/test")).request();
53 SerializableWithParametersObject foo = request.get(SerializableWithParametersObject.class);
54 Assert.assertEquals("Wrong response", new SerializableWithParametersObject("abc"), foo);
55 client.close();
56 }
57 }
+0
-72
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/SpecialCharsInUrlTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.resource.param.resource.SpecialCharsInUrlResource;
6 import org.jboss.resteasy.util.HttpResponseCodes;
7 import org.jboss.resteasy.utils.PortProviderUtil;
8 import org.jboss.resteasy.utils.TestUtil;
9 import org.jboss.shrinkwrap.api.Archive;
10 import org.jboss.shrinkwrap.api.spec.WebArchive;
11 import org.junit.AfterClass;
12 import org.junit.Assert;
13 import org.junit.BeforeClass;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.client.WebTarget;
20 import javax.ws.rs.core.Response;
21
22
23 /**
24 * @tpSubChapter Parameters
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Test for special characters in url
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class SpecialCharsInUrlTest {
32
33 static Client client;
34
35 @Deployment
36 public static Archive<?> deploy() {
37 WebArchive war = TestUtil.prepareArchive(SpecialCharsInUrlTest.class.getSimpleName());
38 return TestUtil.finishContainerPrepare(war, null, SpecialCharsInUrlResource.class);
39 }
40
41 @BeforeClass
42 public static void setup() {
43 client = ClientBuilder.newClient();
44 }
45
46 @AfterClass
47 public static void cleanup() {
48 client.close();
49 }
50
51 private String generateURL(String path) {
52 return PortProviderUtil.generateURL(path, SpecialCharsInUrlTest.class.getSimpleName());
53 }
54
55 private static final String encodedPart = "foo+bar%20gee@foo.com";
56 private static final String decodedPart = "foo+bar gee@foo.com";
57
58 /**
59 * @tpTestDetails Test for '+' and '@' characters in url, RESTEASY-137
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void testGet() throws Exception {
64 WebTarget target = client.target(String.format("%s%s?foo=%s", generateURL("/simple/"), encodedPart, encodedPart));
65 Response response = target.request().get();
66 Assert.assertEquals("The result is not correctly decoded", HttpResponseCodes.SC_OK, response.getStatus());
67 String result = response.readEntity(String.class);
68 Assert.assertEquals("The result is not correctly decoded", decodedPart, result);
69 }
70
71 }
+0
-72
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/StringParamUnmarshallerTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.annotations.StringParameterUnmarshallerBinder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.resource.param.resource.StringParamUnmarshallerDateFormatter;
9 import org.jboss.resteasy.test.resource.param.resource.StringParamUnmarshallerFruit;
10 import org.jboss.resteasy.test.resource.param.resource.StringParamUnmarshallerService;
11 import org.jboss.resteasy.test.resource.param.resource.StringParamUnmarshallerSport;
12 import org.jboss.resteasy.utils.PortProviderUtil;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.Assert;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 import javax.ws.rs.client.Invocation;
21 import java.lang.annotation.Retention;
22 import java.lang.annotation.RetentionPolicy;
23
24
25 /**
26 * @tpSubChapter Resource
27 * @tpChapter Integration tests
28 * @tpSince RESTEasy 3.0.16
29 * @tpTestCaseDetails Test for unmarshalling with string parameter. StringParameterUnmarshallerBinder annotation is used
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class StringParamUnmarshallerTest {
34 @Retention(RetentionPolicy.RUNTIME)
35 @StringParameterUnmarshallerBinder(StringParamUnmarshallerDateFormatter.class)
36 public @interface StringParamUnmarshallerDateFormat {
37 String value();
38 }
39 @Deployment
40 public static Archive<?> deploy() {
41 WebArchive war = TestUtil.prepareArchive(StringParamUnmarshallerTest.class.getSimpleName());
42 war.addClass(StringParamUnmarshallerDateFormatter.class);
43 war.addClass(StringParamUnmarshallerFruit.class);
44 war.addClass(StringParamUnmarshallerSport.class);
45 war.addClass(StringParamUnmarshallerDateFormat.class);
46 return TestUtil.finishContainerPrepare(war, null, StringParamUnmarshallerService.class);
47 }
48
49 private String generateURL(String path) {
50 return PortProviderUtil.generateURL(path, StringParamUnmarshallerTest.class.getSimpleName());
51 }
52
53
54 @Test
55 public void testDate() throws Exception {
56 ResteasyClient client = new ResteasyClientBuilder().build();
57 Invocation.Builder request = client.target(generateURL("/datetest/04-23-1977")).request();
58 String date = request.get(String.class);
59 Assert.assertTrue("Received wrong date", date.contains("Sat Apr 23 00:00:00"));
60 Assert.assertTrue("Received wrong date", date.contains("1977"));
61 client.close();
62 }
63
64 @Test
65 public void testFruitAndSport() throws Exception {
66 ResteasyClient client = new ResteasyClientBuilder().build();
67 Invocation.Builder request = client.target(generateURL("/fromstring/ORANGE/football")).request();
68 Assert.assertEquals("Received wrong response", "footballORANGE", request.get(String.class));
69 client.close();
70 }
71 }
+0
-85
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/SuperStringConverterTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
8 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterCompany;
9 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterCompanyConverter;
10
11 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterMyClient;
12 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterObjectConverter;
13 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterPerson;
14 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterPersonConverter;
15 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterResource;
16 import org.jboss.resteasy.test.resource.param.resource.SuperStringConverterSuperPersonConverter;
17 import org.jboss.resteasy.utils.PortProviderUtil;
18 import org.jboss.resteasy.utils.TestUtil;
19 import org.jboss.shrinkwrap.api.Archive;
20 import org.jboss.shrinkwrap.api.spec.WebArchive;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23
24
25 /**
26 * @tpSubChapter Resource
27 * @tpChapter Integration tests
28 * @tpSince RESTEasy 3.0.16
29 * @tpTestCaseDetails Test for org.jboss.resteasy.spi.StringConverter class
30 * StringConverter is deprecated.
31 * See javax.ws.rs.ext.ParamConverter
32 * See org.jboss.resteasy.test.resource.param.ParamConverterTest
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class SuperStringConverterTest {
37 @Deployment
38 public static Archive<?> deploy() {
39 WebArchive war = TestUtil.prepareArchive(SuperStringConverterTest.class.getSimpleName());
40 war.addClass(SuperStringConverterPerson.class);
41 war.addClass(SuperStringConverterObjectConverter.class);
42 war.addClass(SuperStringConverterSuperPersonConverter.class);
43 war.addClass(SuperStringConverterMyClient.class);
44 war.addClass(SuperStringConverterCompany.class);
45 return TestUtil.finishContainerPrepare(war, null, SuperStringConverterPersonConverter.class,
46 SuperStringConverterCompanyConverter.class,
47 SuperStringConverterResource.class);
48 }
49
50 private String generateBaseUrl() {
51 return PortProviderUtil.generateBaseUrl(SuperStringConverterTest.class.getSimpleName());
52 }
53
54 /**
55 * @tpTestDetails Test converter on basic object
56 * @tpSince RESTEasy 3.0.16
57 */
58 @Test
59 public void testPerson() throws Exception {
60 ResteasyClient client = new ResteasyClientBuilder().build();
61 client.register(SuperStringConverterPersonConverter.class);
62 client.register(SuperStringConverterCompanyConverter.class);
63
64 SuperStringConverterMyClient proxy = ProxyBuilder.builder(SuperStringConverterMyClient.class, client.target(generateBaseUrl())).build();
65 SuperStringConverterPerson person = new SuperStringConverterPerson("name");
66 proxy.put(person);
67 client.close();
68 }
69
70 /**
71 * @tpTestDetails Test converter on object with override on "toString" method
72 * @tpSince RESTEasy 3.0.16
73 */
74 @Test
75 public void testCompany() throws Exception {
76 ResteasyClient client = new ResteasyClientBuilder().build();
77 client.register(SuperStringConverterPersonConverter.class);
78 client.register(SuperStringConverterCompanyConverter.class);
79 SuperStringConverterMyClient proxy = ProxyBuilder.builder(SuperStringConverterMyClient.class, client.target(generateBaseUrl())).build();
80 SuperStringConverterCompany company = new SuperStringConverterCompany("name");
81 proxy.putCompany(company);
82 client.close();
83 }
84 }
+0
-187
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/UriParamAsPrimitiveTest.java less more
0 package org.jboss.resteasy.test.resource.param;
1
2
3 import org.jboss.arquillian.container.test.api.Deployment;
4 import org.jboss.arquillian.container.test.api.RunAsClient;
5 import org.jboss.arquillian.junit.Arquillian;
6 import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriBoolean;
10 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriBooleanInterface;
11 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriBooleanWrapper;
12 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriByte;
13 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriByteInterface;
14 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriByteWrapper;
15 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriDouble;
16 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriDoubleWrapper;
17 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriFloat;
18 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriFloatWrapper;
19 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriInt;
20 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriIntWrapper;
21 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriLong;
22 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriLongWrapper;
23 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriShort;
24 import org.jboss.resteasy.test.resource.param.resource.UriParamAsPrimitiveResourceUriShortWrapper;
25 import org.jboss.resteasy.util.HttpResponseCodes;
26 import org.jboss.resteasy.utils.PortProviderUtil;
27 import org.jboss.resteasy.utils.TestUtil;
28 import org.jboss.shrinkwrap.api.Archive;
29 import org.jboss.shrinkwrap.api.spec.WebArchive;
30 import org.junit.AfterClass;
31 import org.junit.Assert;
32 import org.junit.BeforeClass;
33 import org.junit.Test;
34 import org.junit.runner.RunWith;
35
36 import javax.ws.rs.client.Invocation;
37 import javax.ws.rs.core.Response;
38
39 /**
40 * @tpSubChapter Parameters
41 * @tpChapter Integration tests
42 * @tpTestCaseDetails Test all variants of primitive URI parameters (boolean, int, long, float, etc.)
43 * @tpSince RESTEasy 3.0.16
44 */
45 @RunWith(Arquillian.class)
46 @RunAsClient
47 public class UriParamAsPrimitiveTest {
48 public static final String ERROR_CODE = "Wrong parameter";
49
50 private static UriParamAsPrimitiveResourceUriBooleanInterface resourceUriBoolean;
51 private static UriParamAsPrimitiveResourceUriByteInterface resourceUriByte;
52 private static ResteasyClient client;
53
54 @BeforeClass
55 public static void before() throws Exception {
56 client = new ResteasyClientBuilder().build();
57 resourceUriBoolean = ProxyBuilder.builder(UriParamAsPrimitiveResourceUriBooleanInterface.class, client.target(generateBaseUrl())).build();
58 resourceUriByte = ProxyBuilder.builder(UriParamAsPrimitiveResourceUriByteInterface.class, client.target(generateBaseUrl())).build();
59 }
60
61 @Deployment
62 public static Archive<?> deploy() throws Exception {
63 WebArchive war = TestUtil.prepareArchive(UriParamAsPrimitiveTest.class.getSimpleName());
64 war.addClass(UriParamAsPrimitiveResourceUriBooleanInterface.class);
65 war.addClass(UriParamAsPrimitiveResourceUriByteInterface.class);
66 war.addClass(UriParamAsPrimitiveTest.class);
67 return TestUtil.finishContainerPrepare(war, null,
68 UriParamAsPrimitiveResourceUriBoolean.class,
69 UriParamAsPrimitiveResourceUriByte.class,
70 UriParamAsPrimitiveResourceUriShort.class,
71 UriParamAsPrimitiveResourceUriInt.class,
72 UriParamAsPrimitiveResourceUriLong.class,
73 UriParamAsPrimitiveResourceUriFloat.class,
74 UriParamAsPrimitiveResourceUriDouble.class,
75 UriParamAsPrimitiveResourceUriBooleanWrapper.class,
76 UriParamAsPrimitiveResourceUriByteWrapper.class,
77 UriParamAsPrimitiveResourceUriShortWrapper.class,
78 UriParamAsPrimitiveResourceUriIntWrapper.class,
79 UriParamAsPrimitiveResourceUriLongWrapper.class,
80 UriParamAsPrimitiveResourceUriFloatWrapper.class,
81 UriParamAsPrimitiveResourceUriDoubleWrapper.class);
82 }
83
84 private static String generateURL(String path) {
85 return PortProviderUtil.generateURL(path, UriParamAsPrimitiveTest.class.getSimpleName());
86 }
87
88 private static String generateBaseUrl() {
89 return PortProviderUtil.generateBaseUrl(UriParamAsPrimitiveTest.class.getSimpleName());
90 }
91
92
93 @AfterClass
94 public static void after() throws Exception {
95 client.close();
96 }
97
98 void basicTest(String type, String value) {
99 {
100 Invocation.Builder request = client.target(generateURL("/" + type + "/" + value)).request();
101 try {
102 Response response = request.get();
103 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
104 response.close();
105 } catch (Exception e) {
106 throw new RuntimeException(e);
107 }
108 }
109
110 {
111 Invocation.Builder request = client.target(generateURL("/" + type + "/wrapper/" + value)).request();
112 try {
113 Response response = request.get();
114 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
115 response.close();
116 } catch (Exception e) {
117 throw new RuntimeException(e);
118 }
119 }
120 }
121
122 /**
123 * @tpTestDetails Test boolean primitive object
124 * @tpSince RESTEasy 3.0.16
125 */
126 @Test
127 public void testGetBoolean() {
128 basicTest("boolean", "true");
129 resourceUriBoolean.doGet(true);
130 }
131
132 /**
133 * @tpTestDetails Test byte primitive object
134 * @tpSince RESTEasy 3.0.16
135 */
136 @Test
137 public void testGetByte() {
138 basicTest("byte", "127");
139 resourceUriByte.doGet((byte) 127);
140 }
141
142 /**
143 * @tpTestDetails Test short primitive object
144 * @tpSince RESTEasy 3.0.16
145 */
146 @Test
147 public void testGetShort() {
148 basicTest("short", "32767");
149 }
150
151 /**
152 * @tpTestDetails Test int primitive object
153 * @tpSince RESTEasy 3.0.16
154 */
155 @Test
156 public void testGetInt() {
157 basicTest("int", "2147483647");
158 }
159
160 /**
161 * @tpTestDetails Test long primitive object
162 * @tpSince RESTEasy 3.0.16
163 */
164 @Test
165 public void testGetLong() {
166 basicTest("long", "9223372036854775807");
167 }
168
169 /**
170 * @tpTestDetails Test float primitive object
171 * @tpSince RESTEasy 3.0.16
172 */
173 @Test
174 public void testGetFloat() {
175 basicTest("float", "3.14159265");
176 }
177
178 /**
179 * @tpTestDetails Test double primitive object
180 * @tpSince RESTEasy 3.0.16
181 */
182 @Test
183 public void testGetDouble() {
184 basicTest("double", "3.14159265358979");
185 }
186 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ComplexPathParamExtensionResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.ComplexPathParamTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/")
10 public class ComplexPathParamExtensionResource {
11 @GET
12 @Path("/{1},{2}/{3}/blah{4}-{5}ttt")
13 public String get(@PathParam("1") int one, @PathParam("2") int two, @PathParam("3") int three,
14 @PathParam("4") int four, @PathParam("5") int five) {
15 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, one, 1);
16 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, two, 2);
17 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, three, 3);
18 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, four, 4);
19 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, five, 5);
20 return "hello";
21 }
22
23 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ComplexPathParamRegressionResteasy145.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.Path;
3 import javax.ws.rs.PathParam;
4
5 @Path("/repository/workspaces")
6 public class ComplexPathParamRegressionResteasy145 {
7 @Path("{service: x.*}")
8 public ComplexPathParamSubRes getService(@PathParam("service") String serviceName) {
9 return new ComplexPathParamSubRes();
10 }
11
12 @Path("{path:.*}")
13 public ComplexPathParamSubResSecond getChild(@PathParam("path") String path) {
14 return new ComplexPathParamSubResSecond();
15 }
16 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ComplexPathParamSubRes.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3
4 public class ComplexPathParamSubRes {
5 @GET
6 public String get() {
7 return "sub1";
8 }
9 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ComplexPathParamSubResSecond.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3
4 public class ComplexPathParamSubResSecond {
5 @GET
6 public String get() {
7 return "sub2";
8 }
9 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ComplexPathParamTrickyResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.ComplexPathParamTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/tricky")
10 public class ComplexPathParamTrickyResource {
11 @GET
12 @Path("{hello}")
13 public String getHello(@PathParam("hello") int one) {
14 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, one, 1);
15 return "hello";
16 }
17
18 @GET
19 @Path("{1},{2}")
20 public String get2Groups(@PathParam("1") int one, @PathParam("2") int two) {
21 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, 1, one);
22 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, 2, two);
23 return "2Groups";
24 }
25
26 @GET
27 @Path("h{1}")
28 public String getPrefixed(@PathParam("1") int one) {
29 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, 1, one);
30 return "prefixed";
31 }
32 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ComplexPathParamUnlimitedResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.ComplexPathParamTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/unlimited")
10 public class ComplexPathParamUnlimitedResource {
11 @Path("{1}-{rest:.*}")
12 @GET
13 public String get(@PathParam("1") int one, @PathParam("rest") String rest) {
14 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, 1, one);
15 Assert.assertEquals(ComplexPathParamTest.WRONG_REQUEST_ERROR_MESSAGE, "on/and/on", rest);
16 return "ok";
17 }
18 }
+0
-95
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/CookieInjectionResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.util.Calendar;
3 import java.util.Date;
4
5 import org.junit.Assert;
6
7 import javax.ws.rs.CookieParam;
8 import javax.ws.rs.GET;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.Produces;
11 import javax.ws.rs.DefaultValue;
12 import javax.ws.rs.core.Context;
13 import javax.ws.rs.core.HttpHeaders;
14 import javax.ws.rs.core.NewCookie;
15 import javax.ws.rs.core.Response;
16 import javax.ws.rs.core.Cookie;
17
18
19 @Path("/")
20 public class CookieInjectionResource {
21 @Path("/set")
22 @GET
23 public Response set() {
24 return Response.ok("content").cookie(new NewCookie("meaning", "42")).build();
25 }
26
27 @Path("/expire")
28 @GET
29 public Response expire() {
30 NewCookie cookie = new NewCookie("Name", "Value", "/", "*", 0, "comment", 3600, new Date(),
31 true, true);
32 return Response.ok().cookie(cookie).entity(cookie.toString()).build();
33 }
34
35 @Path("/expire1")
36 @GET
37 public Response expire1() {
38 NewCookie cookie = new NewCookie("Name", "Value", "/", "*", 1, "comment", 3600, new Date(),
39 true, true);
40 return Response.ok().cookie(cookie).entity(cookie.toString()).build();
41 }
42
43 @Path("/expired")
44 @GET
45 public Response expired() {
46 Calendar cal = Calendar.getInstance();
47 cal.add(Calendar.DATE, -1);
48 NewCookie cookie = new NewCookie("Name", "Value", "/", "*", 1, "comment", 1800, cal.getTime(),
49 true, true);
50 return Response.ok().cookie(cookie).entity(cookie.toString()).build();
51 }
52
53 @Context
54 HttpHeaders myHeaders;
55
56 @Path("/headers")
57 @GET
58 public String headers(@Context HttpHeaders headers) {
59 String value = headers.getCookies().get("meaning").getValue();
60 Assert.assertEquals("Unexpected value in the cookie", value, "42");
61 return value;
62 }
63
64 @Path("/headers/fromField")
65 @GET
66 public String headersFromField(@Context HttpHeaders headers) {
67 String value = myHeaders.getCookies().get("meaning").getValue();
68 Assert.assertEquals("Unexpected value in the cookie", value, "42");
69 return value;
70 }
71
72 @Path("/param")
73 @GET
74 @Produces("text/plain")
75 public int param(@CookieParam("meaning") int value) {
76 Assert.assertEquals("Unexpected value in the cookie", value, 42);
77 return value;
78 }
79
80 @Path("/cookieparam")
81 @GET
82 public String param(@CookieParam("meaning") Cookie value) {
83 Assert.assertEquals("Unexpected value in the cookie", value.getValue(), "42");
84 return value.getValue();
85 }
86
87 @Path("/default")
88 @GET
89 @Produces("text/plain")
90 public int defaultValue(@CookieParam("defaulted") @DefaultValue("24") int value) {
91 Assert.assertEquals("Unexpected value in the cookie", value, 24);
92 return value;
93 }
94 }
+0
-64
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/FormParamBasicResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.DefaultValue;
4 import javax.ws.rs.Encoded;
5 import javax.ws.rs.FormParam;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.core.Response;
9 import java.util.List;
10 import java.util.SortedSet;
11
12 @Path(value = "/FormParamTest/")
13 public class FormParamBasicResource {
14 @Path(value = "/ParamEntityWithFromString")
15 @POST
16 @Consumes("application/x-www-form-urlencoded")
17 public Response fromString(
18 @Encoded @DefaultValue("FromString") @FormParam("default_argument") FormParamEntityWithFromString defaultArgument) {
19 return Response.ok(response(defaultArgument.getValue())).build();
20 }
21
22 public static final String response(String argument) {
23 return new StringBuilder().append("CTS_FORMPARAM:").append(argument)
24 .toString();
25 }
26
27 @Path(value = "/string")
28 @POST
29 @Consumes("application/x-www-form-urlencoded")
30 public Response string(
31 @Encoded @DefaultValue("FromString") @FormParam("default_argument") String defaultArgument) {
32 return Response.ok(response(defaultArgument)).build();
33 }
34
35 @Path(value = "/SortedSetFromString")
36 @POST
37 @Consumes("application/x-www-form-urlencoded")
38 public Response sortedSetFromString(
39 @Encoded @DefaultValue("SortedSetFromString") @FormParam("default_argument") SortedSet<FormParamEntityWithFromString> defaultArgument) {
40 return Response.ok(response(defaultArgument.first().getValue()))
41 .build();
42 }
43
44 @Path(value = "/ListConstructor")
45 @POST
46 @Consumes("application/x-www-form-urlencoded")
47 public Response defaultListConstructor(
48 @DefaultValue("ListConstructor") @FormParam("default_argument") List<FormParamEntityWithConstructor> defaultArgument) {
49 return Response.ok(
50 response(defaultArgument.listIterator().next().getValue()))
51 .build();
52 }
53
54 @Path(value = "/IllegalArgumentException")
55 @POST
56 @Consumes("application/x-www-form-urlencoded")
57 public Response throwWebApplicationException(
58 @DefaultValue("SortedSetFromString") @FormParam("default_argument") FormParamEntityThrowsIllegaArgumentException defaultArgument) {
59 return Response.ok().build();
60 }
61
62
63 }
+0
-9
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/FormParamEntityPrototype.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public abstract class FormParamEntityPrototype {
3 protected String value;
4
5 public String getValue() {
6 return value;
7 }
8 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/FormParamEntityThrowsIllegaArgumentException.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public class FormParamEntityThrowsIllegaArgumentException extends FormParamEntityPrototype {
3 public static FormParamEntityThrowsIllegaArgumentException fromString(String arg) {
4 throw new IllegalArgumentException("failed to parse");
5 }
6 }
+0
-7
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/FormParamEntityWithConstructor.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public class FormParamEntityWithConstructor extends FormParamEntityPrototype {
3 public FormParamEntityWithConstructor(final String arg) {
4 value = arg;
5 }
6 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/FormParamEntityWithFromString.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public class FormParamEntityWithFromString extends FormParamEntityPrototype implements
3 Comparable<FormParamEntityWithFromString> {
4
5 public static FormParamEntityWithFromString fromString(String arg) {
6 FormParamEntityWithFromString newEntity = new FormParamEntityWithFromString();
7 newEntity.value = arg;
8 return newEntity;
9 }
10
11 @Override
12 public int compareTo(FormParamEntityWithFromString o) {
13 return this.value.compareTo(o.value);
14 }
15
16 @Override
17 public boolean equals(Object obj) {
18 return this.value.equals(obj);
19 }
20
21 @Override
22 public int hashCode() {
23 return this.value.hashCode();
24 }
25 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/FormParamResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.Encoded;
4 import javax.ws.rs.FormParam;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7
8 @Path("/")
9 public class FormParamResource {
10 @POST
11 @Path("form")
12 @Consumes("application/x-www-form-urlencoded")
13 public String post(@Encoded @FormParam("param") String param) {
14 return param;
15 }
16 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderDelegateDate.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.util.Date;
3
4 public class HeaderDelegateDate extends Date {
5 private static final long serialVersionUID = 1L;
6
7 public HeaderDelegateDate(final long date) {
8 super(date);
9 }
10 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderDelegateDelegate.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.ext.RuntimeDelegate;
3
4 public class HeaderDelegateDelegate<T> implements HeaderDelegateInterface4, RuntimeDelegate.HeaderDelegate<T> {
5 @Override
6 public T fromString(String value) {
7 return null;
8 }
9
10 @Override
11 public String toString(T value) {
12 return null;
13 }
14 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderDelegateInterface1.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public interface HeaderDelegateInterface1 {
3 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderDelegateInterface2.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public interface HeaderDelegateInterface2 extends HeaderDelegateInterface1 {
3 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderDelegateInterface3.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public interface HeaderDelegateInterface3 extends HeaderDelegateInterface1 {
3 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderDelegateInterface4.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public interface HeaderDelegateInterface4 extends HeaderDelegateInterface3 {
3 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderDelegateResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderDelegateTest;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.Response;
8
9
10 @Path("/last")
11 public class HeaderDelegateResource {
12 @GET
13 @Produces("text/plain")
14 public Response last() {
15 return Response.ok().lastModified(HeaderDelegateTest.RIGHT_AFTER_BIG_BANG).build();
16 }
17 }
+0
-4
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderDelegateSubDelegate.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public class HeaderDelegateSubDelegate<T> extends HeaderDelegateDelegate<T> {
3 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesArrayDefaultNullProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/array/default/null")
7 public interface HeaderParamsAsPrimitivesArrayDefaultNullProxy {
8 @GET
9 @Produces("application/boolean")
10 String doGetBoolean();
11
12 @GET
13 @Produces("application/short")
14 String doGetShort();
15 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesArrayDefaultOverrideProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.DefaultValue;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.HeaderParam;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7
8 @Path("/array/default/override")
9 public interface HeaderParamsAsPrimitivesArrayDefaultOverrideProxy {
10 @GET
11 @Produces("application/boolean")
12 String doGetBoolean(@HeaderParam("boolean") @DefaultValue("false") boolean[] v);
13
14 @GET
15 @Produces("application/short")
16 String doGetShort(@HeaderParam("int") @DefaultValue("0") short[] v);
17 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesArrayDefaultProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/array/default")
7 public interface HeaderParamsAsPrimitivesArrayDefaultProxy {
8 @GET
9 @Produces("application/boolean")
10 String doGetBoolean();
11
12 @GET
13 @Produces("application/short")
14 String doGetShort();
15 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesArrayProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.HeaderParam;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6
7 @Path("/array")
8 public interface HeaderParamsAsPrimitivesArrayProxy {
9 @GET
10 @Produces("application/boolean")
11 String doGetBoolean(@HeaderParam("boolean") boolean[] v);
12
13 @GET
14 @Produces("application/short")
15 String doGetShort(@HeaderParam("short") short[] v);
16 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesDefaultNullProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/default/null")
7 public interface HeaderParamsAsPrimitivesDefaultNullProxy {
8 @GET
9 @Produces("application/boolean")
10 String doGetBoolean();
11
12 @GET
13 @Produces("application/byte")
14 String doGetByte();
15
16 @GET
17 @Produces("application/short")
18 String doGetShort();
19
20 @GET
21 @Produces("application/int")
22 String doGetInt();
23
24 @GET
25 @Produces("application/long")
26 String doGetLong();
27
28 @GET
29 @Produces("application/float")
30 String doGetFloat();
31
32 @GET
33 @Produces("application/double")
34 String doGet();
35 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesDefaultOverrideProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.DefaultValue;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.HeaderParam;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7
8 @Path("/default/override")
9 public interface HeaderParamsAsPrimitivesDefaultOverrideProxy {
10 @GET
11 @Produces("application/boolean")
12 String doGet(@HeaderParam("boolean") @DefaultValue("false") boolean v);
13
14 @GET
15 @Produces("application/byte")
16 String doGet(@HeaderParam("byte") @DefaultValue("1") byte v);
17
18 @GET
19 @Produces("application/short")
20 String doGet(@HeaderParam("short") @DefaultValue("1") short v);
21
22 @GET
23 @Produces("application/int")
24 String doGet(@HeaderParam("int") @DefaultValue("1") int v);
25
26 @GET
27 @Produces("application/long")
28 String doGet(@HeaderParam("long") @DefaultValue("1") long v);
29
30 @GET
31 @Produces("application/float")
32 String doGet(@HeaderParam("float") @DefaultValue("0.0") float v);
33
34 @GET
35 @Produces("application/double")
36 String doGet(@HeaderParam("double") @DefaultValue("0.0") double v);
37 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesDefaultProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/default")
7 public interface HeaderParamsAsPrimitivesDefaultProxy {
8 @GET
9 @Produces("application/boolean")
10 String doGetBoolean();
11
12 @GET
13 @Produces("application/byte")
14 String doGetByte();
15
16 @GET
17 @Produces("application/short")
18 String doGetShort();
19
20 @GET
21 @Produces("application/int")
22 String doGetInt();
23
24 @GET
25 @Produces("application/long")
26 String doGetLong();
27
28 @GET
29 @Produces("application/float")
30 String doGetFloat();
31
32 @GET
33 @Produces("application/double")
34 String doGetDouble();
35 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesListDefaultNullProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/list/default/null")
7 public interface HeaderParamsAsPrimitivesListDefaultNullProxy {
8 @GET
9 @Produces("application/boolean")
10 String doGetBoolean();
11
12 @GET
13 @Produces("application/byte")
14 String doGetByte();
15
16 @GET
17 @Produces("application/short")
18 String doGetShort();
19
20 @GET
21 @Produces("application/int")
22 String doGetInteger();
23
24 @GET
25 @Produces("application/long")
26 String doGetLong();
27
28 @GET
29 @Produces("application/float")
30 String doGetFloat();
31
32 @GET
33 @Produces("application/double")
34 String doGetDouble();
35 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesListDefaultOverrideProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.DefaultValue;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.HeaderParam;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import java.util.List;
8
9 @Path("/list/default/override")
10 public interface HeaderParamsAsPrimitivesListDefaultOverrideProxy {
11 @GET
12 @Produces("application/boolean")
13 String doGetBoolean(@HeaderParam("boolean") @DefaultValue("false") List<Boolean> v);
14
15 @GET
16 @Produces("application/byte")
17 String doGetByte(@HeaderParam("byte") @DefaultValue("0") List<Byte> v);
18
19 @GET
20 @Produces("application/short")
21 String doGetShort(@HeaderParam("short") @DefaultValue("0") List<Short> v);
22
23 @GET
24 @Produces("application/int")
25 String doGetInteger(@HeaderParam("int") @DefaultValue("0") List<Integer> v);
26
27 @GET
28 @Produces("application/long")
29 String doGetLong(@HeaderParam("long") @DefaultValue("0") List<Long> v);
30
31 @GET
32 @Produces("application/float")
33 String doGetFloat(@HeaderParam("float") @DefaultValue("0.0") List<Float> v);
34
35 @GET
36 @Produces("application/double")
37 String doGetDouble(@HeaderParam("double") @DefaultValue("0.0") List<Double> v);
38 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesListDefaultProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/list/default")
7 public interface HeaderParamsAsPrimitivesListDefaultProxy {
8 @GET
9 @Produces("application/boolean")
10 String doGetBoolean();
11
12 @GET
13 @Produces("application/byte")
14 String doGetByte();
15
16 @GET
17 @Produces("application/short")
18 String doGetShort();
19
20 @GET
21 @Produces("application/int")
22 String doGetInteger();
23
24 @GET
25 @Produces("application/long")
26 String doGetLong();
27
28 @GET
29 @Produces("application/float")
30 String doGetFloat();
31
32 @GET
33 @Produces("application/double")
34 String doGetDouble();
35 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesListProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.HeaderParam;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import java.util.List;
7
8 @Path("/list")
9 public interface HeaderParamsAsPrimitivesListProxy {
10 @GET
11 @Produces("application/boolean")
12 String doGetBoolean(@HeaderParam("boolean") List<Boolean> v);
13
14 @GET
15 @Produces("application/byte")
16 String doGetByte(@HeaderParam("byte") List<Byte> v);
17
18 @GET
19 @Produces("application/short")
20 String doGetShort(@HeaderParam("short") List<Short> v);
21
22 @GET
23 @Produces("application/int")
24 String doGetInteger(@HeaderParam("int") List<Integer> v);
25
26 @GET
27 @Produces("application/long")
28 String doGetLong(@HeaderParam("long") List<Long> v);
29
30 @GET
31 @Produces("application/float")
32 String doGetFloat(@HeaderParam("float") List<Float> v);
33
34 @GET
35 @Produces("application/double")
36 String doGetDouble(@HeaderParam("double") List<Double> v);
37 }
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesPrimitivesProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.HeaderParam;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6
7 @Path("/")
8 public interface HeaderParamsAsPrimitivesPrimitivesProxy {
9 @GET
10 @Produces("application/boolean")
11 String doGet(@HeaderParam("boolean") boolean v);
12
13 @GET
14 @Produces("application/byte")
15 String doGet(@HeaderParam("byte") byte v);
16
17 @GET
18 @Produces("application/short")
19 String doGet(@HeaderParam("short") short v);
20
21 @GET
22 @Produces("application/int")
23 String doGet(@HeaderParam("int") int v);
24
25 @GET
26 @Produces("application/long")
27 String doGet(@HeaderParam("long") long v);
28
29 @GET
30 @Produces("application/float")
31 String doGet(@HeaderParam("float") float v);
32
33 @GET
34 @Produces("application/double")
35 String doGet(@HeaderParam("double") double v);
36 }
+0
-30
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceArray.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/array")
11 public class HeaderParamsAsPrimitivesResourceArray implements HeaderParamsAsPrimitivesArrayProxy {
12 @GET
13 @Produces("application/boolean")
14 public String doGetBoolean(@HeaderParam("boolean") boolean[] v) {
15 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v[0]);
16 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v[1]);
17 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v[2]);
18 return "content";
19 }
20
21 @GET
22 @Produces("application/short")
23 public String doGetShort(@HeaderParam("short") short[] v) {
24 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v[0]);
25 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v[0]);
26 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v[0]);
27 return "content";
28 }
29 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceArrayDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.HeaderParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/array/default")
12 public class HeaderParamsAsPrimitivesResourceArrayDefault {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@HeaderParam("boolean") @DefaultValue("true") boolean[] v) {
16 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v[0]);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/short")
22 public String doGetShort(@HeaderParam("short") @DefaultValue("32767") short[] v) {
23 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v[0]);
24 return "content";
25 }
26 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceArrayDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/array/default/null")
11 public class HeaderParamsAsPrimitivesResourceArrayDefaultNull {
12 @GET
13 @Produces("application/boolean")
14 public String doGetBoolean(@HeaderParam("boolean") boolean[] v) {
15 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v.length);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/short")
21 public String doGetShort(@HeaderParam("short") short[] v) {
22 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v.length);
23 return "content";
24 }
25 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceArrayDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.HeaderParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/array/default/override")
12 public class HeaderParamsAsPrimitivesResourceArrayDefaultOverride
13 implements
14 HeaderParamsAsPrimitivesArrayDefaultOverrideProxy {
15 @GET
16 @Produces("application/boolean")
17 public String doGetBoolean(@HeaderParam("boolean") @DefaultValue("false") boolean[] v) {
18 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v[0]);
19 return "content";
20 }
21
22 @GET
23 @Produces("application/short")
24 public String doGetShort(@HeaderParam("int") @DefaultValue("0") short[] v) {
25 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v[0]);
26 return "content";
27 }
28 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.HeaderParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/default")
12 public class HeaderParamsAsPrimitivesResourceDefault {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@HeaderParam("boolean") @DefaultValue("true") boolean v) {
16 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@HeaderParam("byte") @DefaultValue("127") byte v) {
23 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@HeaderParam("short") @DefaultValue("32767") short v) {
30 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@HeaderParam("int") @DefaultValue("2147483647") int v) {
37 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@HeaderParam("long") @DefaultValue("9223372036854775807") long v) {
44 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@HeaderParam("float") @DefaultValue("3.14159265") float v) {
51 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v, 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@HeaderParam("double") @DefaultValue("3.14159265358979") double v) {
58 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v, 0.0);
59 return "content";
60 }
61 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/default/null")
11 public class HeaderParamsAsPrimitivesResourceDefaultNull {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@HeaderParam("boolean") boolean v) {
15 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, false, v);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@HeaderParam("byte") byte v) {
22 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0 == v);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@HeaderParam("short") short v) {
29 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0 == v);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@HeaderParam("int") int v) {
36 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@HeaderParam("long") long v) {
43 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0L, v);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@HeaderParam("float") float v) {
50 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0.0f, v, 0.0f);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@HeaderParam("double") double v) {
57 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0.0d, v, 0.0);
58 return "content";
59 }
60 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.HeaderParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/default/override")
12 public class HeaderParamsAsPrimitivesResourceDefaultOverride implements HeaderParamsAsPrimitivesDefaultOverrideProxy {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@HeaderParam("boolean") @DefaultValue("false") boolean v) {
16 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@HeaderParam("byte") @DefaultValue("1") byte v) {
23 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@HeaderParam("short") @DefaultValue("1") short v) {
30 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@HeaderParam("int") @DefaultValue("1") int v) {
37 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@HeaderParam("long") @DefaultValue("1") long v) {
44 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@HeaderParam("float") @DefaultValue("0.0") float v) {
51 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v, 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@HeaderParam("double") @DefaultValue("0.0") double v) {
58 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v, 0.0);
59 return "content";
60 }
61 }
+0
-76
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceList.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import java.util.List;
10
11 @Path("/list")
12 public class HeaderParamsAsPrimitivesResourceList implements HeaderParamsAsPrimitivesListProxy {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@HeaderParam("boolean") List<Boolean> v) {
16 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v.get(0).booleanValue());
17 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v.get(1).booleanValue());
18 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v.get(2).booleanValue());
19 return "content";
20 }
21
22 @GET
23 @Produces("application/byte")
24 public String doGetByte(@HeaderParam("byte") List<Byte> v) {
25 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v.get(0).byteValue());
26 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v.get(1).byteValue());
27 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v.get(2).byteValue());
28 return "content";
29 }
30
31 @GET
32 @Produces("application/short")
33 public String doGetShort(@HeaderParam("short") List<Short> v) {
34 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v.get(0).shortValue());
35 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v.get(1).shortValue());
36 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v.get(2).shortValue());
37 return "content";
38 }
39
40 @GET
41 @Produces("application/int")
42 public String doGetInteger(@HeaderParam("int") List<Integer> v) {
43 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v.get(0).intValue());
44 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v.get(1).intValue());
45 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v.get(2).intValue());
46 return "content";
47 }
48
49 @GET
50 @Produces("application/long")
51 public String doGetLong(@HeaderParam("long") List<Long> v) {
52 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v.get(0).longValue());
53 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v.get(1).longValue());
54 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v.get(2).longValue());
55 return "content";
56 }
57
58 @GET
59 @Produces("application/float")
60 public String doGetFloat(@HeaderParam("float") List<Float> v) {
61 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v.get(0).floatValue(), 0.0f);
62 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v.get(1).floatValue(), 0.0f);
63 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v.get(2).floatValue(), 0.0f);
64 return "content";
65 }
66
67 @GET
68 @Produces("application/double")
69 public String doGetDouble(@HeaderParam("double") List<Double> v) {
70 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v.get(0).doubleValue(), 0.0);
71 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v.get(1).doubleValue(), 0.0);
72 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v.get(2).doubleValue(), 0.0);
73 return "content";
74 }
75 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceListDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.HeaderParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import java.util.List;
11
12 @Path("/list/default")
13 public class HeaderParamsAsPrimitivesResourceListDefault {
14 @GET
15 @Produces("application/boolean")
16 public String doGetBoolean(@HeaderParam("boolean") @DefaultValue("true") List<Boolean> v) {
17 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v.get(0).booleanValue());
18 return "content";
19 }
20
21 @GET
22 @Produces("application/byte")
23 public String doGetByte(@HeaderParam("byte") @DefaultValue("127") List<Byte> v) {
24 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v.get(0).byteValue());
25 return "content";
26 }
27
28 @GET
29 @Produces("application/short")
30 public String doGetShort(@HeaderParam("short") @DefaultValue("32767") List<Short> v) {
31 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v.get(0).shortValue());
32 return "content";
33 }
34
35 @GET
36 @Produces("application/int")
37 public String doGetInteger(@HeaderParam("int") @DefaultValue("2147483647") List<Integer> v) {
38 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v.get(0).intValue());
39 return "content";
40 }
41
42 @GET
43 @Produces("application/long")
44 public String doGetLong(@HeaderParam("long") @DefaultValue("9223372036854775807") List<Long> v) {
45 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v.get(0).longValue());
46 return "content";
47 }
48
49 @GET
50 @Produces("application/float")
51 public String doGetFloat(@HeaderParam("float") @DefaultValue("3.14159265") List<Float> v) {
52 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v.get(0).floatValue(), 0.0f);
53 return "content";
54 }
55
56 @GET
57 @Produces("application/double")
58 public String doGetDouble(@HeaderParam("double") @DefaultValue("3.14159265358979") List<Double> v) {
59 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v.get(0).doubleValue(), 0.0);
60 return "content";
61 }
62 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceListDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import java.util.List;
10
11 @Path("/list/default/null")
12 public class HeaderParamsAsPrimitivesResourceListDefaultNull {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@HeaderParam("boolean") List<Boolean> v) {
16 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v.size());
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGetByte(@HeaderParam("byte") List<Byte> v) {
23 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v.size());
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGetShort(@HeaderParam("short") List<Short> v) {
30 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v.size());
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGetInteger(@HeaderParam("int") List<Integer> v) {
37 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v.size());
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGetLong(@HeaderParam("long") List<Long> v) {
44 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v.size());
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGetFloat(@HeaderParam("float") List<Float> v) {
51 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v.size());
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGetDouble(@HeaderParam("double") List<Double> v) {
58 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 0, v.size());
59 return "content";
60 }
61 }
+0
-65
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceListDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.HeaderParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import java.util.List;
11
12 @Path("/list/default/override")
13 public class HeaderParamsAsPrimitivesResourceListDefaultOverride
14 implements
15 HeaderParamsAsPrimitivesListDefaultOverrideProxy {
16 @GET
17 @Produces("application/boolean")
18 public String doGetBoolean(@HeaderParam("boolean") @DefaultValue("false") List<Boolean> v) {
19 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v.get(0).booleanValue());
20 return "content";
21 }
22
23 @GET
24 @Produces("application/byte")
25 public String doGetByte(@HeaderParam("byte") @DefaultValue("0") List<Byte> v) {
26 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v.get(0).byteValue());
27 return "content";
28 }
29
30 @GET
31 @Produces("application/short")
32 public String doGetShort(@HeaderParam("short") @DefaultValue("0") List<Short> v) {
33 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v.get(0).shortValue());
34 return "content";
35 }
36
37 @GET
38 @Produces("application/int")
39 public String doGetInteger(@HeaderParam("int") @DefaultValue("0") List<Integer> v) {
40 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v.get(0).intValue());
41 return "content";
42 }
43
44 @GET
45 @Produces("application/long")
46 public String doGetLong(@HeaderParam("long") @DefaultValue("0") List<Long> v) {
47 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v.get(0).longValue());
48 return "content";
49 }
50
51 @GET
52 @Produces("application/float")
53 public String doGetFloat(@HeaderParam("float") @DefaultValue("0.0") List<Float> v) {
54 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v.get(0).floatValue(), 0.0f);
55 return "content";
56 }
57
58 @GET
59 @Produces("application/double")
60 public String doGetDouble(@HeaderParam("double") @DefaultValue("0.0") List<Double> v) {
61 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v.get(0).doubleValue(), 0.0);
62 return "content";
63 }
64 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourcePrimitives.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/")
11 public class HeaderParamsAsPrimitivesResourcePrimitives implements HeaderParamsAsPrimitivesPrimitivesProxy {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@HeaderParam("boolean") boolean v) {
15 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@HeaderParam("byte") byte v) {
22 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@HeaderParam("short") short v) {
29 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, v == 32767);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@HeaderParam("int") int v) {
36 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@HeaderParam("long") long v) {
43 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@HeaderParam("float") float v) {
50 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v, 0.0f);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@HeaderParam("double") double v) {
57 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v, 0.0);
58 return "content";
59 }
60 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceSet.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import java.util.Set;
10
11 @Path("/set")
12 public class HeaderParamsAsPrimitivesResourceSet implements HeaderParamsAsPrimitivesSetProxy {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@HeaderParam("header") Set<String> v) {
16 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2, v.size());
17 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, v.contains("one"));
18 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, v.contains("two"));
19 return "content";
20 }
21 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceSortedSet.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import java.util.SortedSet;
10
11 @Path("/sortedset")
12 public class HeaderParamsAsPrimitivesResourceSortedSet implements HeaderParamsAsPrimitivesSortedSetProxy {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@HeaderParam("header") SortedSet<String> v) {
16 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2, v.size());
17 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, v.contains("one"));
18 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, v.contains("two"));
19 return "content";
20 }
21 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceWrappers.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/wrappers")
11 public class HeaderParamsAsPrimitivesResourceWrappers implements HeaderParamsAsPrimitivesWrappersProxy {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@HeaderParam("boolean") Boolean v) {
15 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v.booleanValue());
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@HeaderParam("byte") Byte v) {
22 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v.byteValue());
23
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@HeaderParam("short") Short v) {
30 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v.shortValue());
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@HeaderParam("int") Integer v) {
37 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v.intValue());
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@HeaderParam("long") Long v) {
44 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v.longValue());
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@HeaderParam("float") Float v) {
51 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v.floatValue(), 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@HeaderParam("double") Double v) {
58 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v.doubleValue(), 0.0);
59 return "content";
60 }
61 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceWrappersDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.HeaderParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/wrappers/default")
12 public class HeaderParamsAsPrimitivesResourceWrappersDefault {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@HeaderParam("boolean") @DefaultValue("true") Boolean v) {
16 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v.booleanValue());
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@HeaderParam("byte") @DefaultValue("127") Byte v) {
23 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v.byteValue());
24
25 return "content";
26 }
27
28 @GET
29 @Produces("application/short")
30 public String doGet(@HeaderParam("short") @DefaultValue("32767") Short v) {
31 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v.shortValue());
32 return "content";
33 }
34
35 @GET
36 @Produces("application/int")
37 public String doGet(@HeaderParam("int") @DefaultValue("2147483647") Integer v) {
38 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v.intValue());
39 return "content";
40 }
41
42 @GET
43 @Produces("application/long")
44 public String doGet(@HeaderParam("long") @DefaultValue("9223372036854775807") Long v) {
45 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v.longValue());
46 return "content";
47 }
48
49 @GET
50 @Produces("application/float")
51 public String doGet(@HeaderParam("float") @DefaultValue("3.14159265") Float v) {
52 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v.floatValue(), 0.0f);
53 return "content";
54 }
55
56 @GET
57 @Produces("application/double")
58 public String doGet(@HeaderParam("double") @DefaultValue("3.14159265358979") Double v) {
59 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v.doubleValue(), 0.0);
60 return "content";
61 }
62 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceWrappersDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.HeaderParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/wrappers/default/null")
11 public class HeaderParamsAsPrimitivesResourceWrappersDefaultNull {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@HeaderParam("boolean") Boolean v) {
15 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, null, v);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@HeaderParam("byte") Byte v) {
22 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, null, v);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@HeaderParam("short") Short v) {
29 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, null, v);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@HeaderParam("int") Integer v) {
36 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, null, v);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@HeaderParam("long") Long v) {
43 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, null, v);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@HeaderParam("float") Float v) {
50 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, null, v);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@HeaderParam("double") Double v) {
57 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, null, v);
58 return "content";
59 }
60 }
+0
-64
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesResourceWrappersDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.HeaderParamsAsPrimitivesTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.HeaderParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/wrappers/default/override")
12 public class HeaderParamsAsPrimitivesResourceWrappersDefaultOverride
13 implements
14 HeaderParamsAsPrimitivesWrappersDefaultOverrideProxy {
15 @GET
16 @Produces("application/boolean")
17 public String doGet(@HeaderParam("boolean") @DefaultValue("false") Boolean v) {
18 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, true, v.booleanValue());
19 return "content";
20 }
21
22 @GET
23 @Produces("application/byte")
24 public String doGet(@HeaderParam("byte") @DefaultValue("1") Byte v) {
25 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 127 == v.byteValue());
26 return "content";
27 }
28
29 @GET
30 @Produces("application/short")
31 public String doGet(@HeaderParam("short") @DefaultValue("1") Short v) {
32 Assert.assertTrue(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 32767 == v.shortValue());
33 return "content";
34 }
35
36 @GET
37 @Produces("application/int")
38 public String doGet(@HeaderParam("int") @DefaultValue("1") Integer v) {
39 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 2147483647, v.intValue());
40 return "content";
41 }
42
43 @GET
44 @Produces("application/long")
45 public String doGet(@HeaderParam("long") @DefaultValue("1") Long v) {
46 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 9223372036854775807L, v.longValue());
47 return "content";
48 }
49
50 @GET
51 @Produces("application/float")
52 public String doGet(@HeaderParam("float") @DefaultValue("0.0") Float v) {
53 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265f, v.floatValue(), 0.0f);
54 return "content";
55 }
56
57 @GET
58 @Produces("application/double")
59 public String doGet(@HeaderParam("double") @DefaultValue("0.0") Double v) {
60 Assert.assertEquals(HeaderParamsAsPrimitivesTest.ERROR_MESSAGE, 3.14159265358979d, v.doubleValue(), 0.0);
61 return "content";
62 }
63 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesSetProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.HeaderParam;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import java.util.Set;
7
8 @Path("/set")
9 public interface HeaderParamsAsPrimitivesSetProxy {
10 @GET
11 @Produces("application/boolean")
12 String doGetBoolean(@HeaderParam("header") Set<String> v);
13 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesSortedSetProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.HeaderParam;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import java.util.SortedSet;
7
8 @Path("/sortedset")
9 public interface HeaderParamsAsPrimitivesSortedSetProxy {
10 @GET
11 @Produces("application/boolean")
12 String doGetBoolean(@HeaderParam("header") SortedSet<String> v);
13 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesWrappersDefaultNullProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/wrappers/default/null")
7 public interface HeaderParamsAsPrimitivesWrappersDefaultNullProxy {
8 @GET
9 @Produces("application/boolean")
10 String doGetBoolean();
11
12 @GET
13 @Produces("application/byte")
14 String doGetByte();
15
16 @GET
17 @Produces("application/short")
18 String doGetShort();
19
20 @GET
21 @Produces("application/int")
22 String doGetInt();
23
24 @GET
25 @Produces("application/long")
26 String doGetLong();
27
28 @GET
29 @Produces("application/float")
30 String doGetFloat();
31
32 @GET
33 @Produces("application/double")
34 String doGetDouble();
35 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesWrappersDefaultOverrideProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.DefaultValue;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.HeaderParam;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7
8 @Path("/wrappers/default/override")
9 public interface HeaderParamsAsPrimitivesWrappersDefaultOverrideProxy {
10 @GET
11 @Produces("application/boolean")
12 String doGet(@HeaderParam("boolean") @DefaultValue("false") Boolean v);
13
14 @GET
15 @Produces("application/byte")
16 String doGet(@HeaderParam("byte") @DefaultValue("1") Byte v);
17
18 @GET
19 @Produces("application/short")
20 String doGet(@HeaderParam("short") @DefaultValue("1") Short v);
21
22 @GET
23 @Produces("application/int")
24 String doGet(@HeaderParam("int") @DefaultValue("1") Integer v);
25
26 @GET
27 @Produces("application/long")
28 String doGet(@HeaderParam("long") @DefaultValue("1") Long v);
29
30 @GET
31 @Produces("application/float")
32 String doGet(@HeaderParam("float") @DefaultValue("0.0") Float v);
33
34 @GET
35 @Produces("application/double")
36 String doGet(@HeaderParam("double") @DefaultValue("0.0") Double v);
37 }
+0
-36
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesWrappersDefaultProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("/wrappers/default")
7 public interface HeaderParamsAsPrimitivesWrappersDefaultProxy {
8 @GET
9 @Produces("application/boolean")
10 String doGetBoolean();
11
12 @GET
13 @Produces("application/byte")
14 String doGetByte();
15
16 @GET
17 @Produces("application/short")
18 String doGetShort();
19
20 @GET
21 @Produces("application/int")
22 String doGetInteger();
23
24 @GET
25 @Produces("application/long")
26 String doGetLong();
27
28 @GET
29 @Produces("application/float")
30 String doGetFloat();
31
32 @GET
33 @Produces("application/double")
34 String doGetDouble();
35 }
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/HeaderParamsAsPrimitivesWrappersProxy.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.HeaderParam;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6
7 @Path("/wrappers")
8 public interface HeaderParamsAsPrimitivesWrappersProxy {
9 @GET
10 @Produces("application/boolean")
11 String doGet(@HeaderParam("boolean") Boolean v);
12
13 @GET
14 @Produces("application/byte")
15 String doGet(@HeaderParam("byte") Byte v);
16
17 @GET
18 @Produces("application/short")
19 String doGet(@HeaderParam("short") Short v);
20
21 @GET
22 @Produces("application/int")
23 String doGet(@HeaderParam("int") Integer v);
24
25 @GET
26 @Produces("application/long")
27 String doGet(@HeaderParam("long") Long v);
28
29 @GET
30 @Produces("application/float")
31 String doGet(@HeaderParam("float") Float v);
32
33 @GET
34 @Produces("application/double")
35 String doGet(@HeaderParam("double") Double v);
36 }
+0
-75
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveArray.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.MatrixParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/array")
11 public class MatrixParamAsPrimitiveArray {
12 @GET
13 @Produces("application/boolean")
14 public String doGetBoolean(@MatrixParam("boolean") boolean[] v) {
15 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v[0]);
16 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v[1]);
17 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v[2]);
18 return "content";
19 }
20
21 @GET
22 @Produces("application/byte")
23 public String doGetByte(@MatrixParam("byte") byte[] v) {
24 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v[0]);
25 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v[1]);
26 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v[2]);
27 return "content";
28 }
29
30 @GET
31 @Produces("application/short")
32 public String doGetShort(@MatrixParam("short") short[] v) {
33 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 32767 == v[0]);
34 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 32767 == v[1]);
35 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 32767 == v[2]);
36 return "content";
37 }
38
39 @GET
40 @Produces("application/int")
41 public String doGetInteger(@MatrixParam("int") int[] v) {
42 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[0]);
43 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[1]);
44 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[2]);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/long")
50 public String doGetLong(@MatrixParam("long") long[] v) {
51 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[0]);
52 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[1]);
53 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[2]);
54 return "content";
55 }
56
57 @GET
58 @Produces("application/float")
59 public String doGetFloat(@MatrixParam("float") float[] v) {
60 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[0], 0.0f);
61 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[1], 0.0f);
62 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[2], 0.0f);
63 return "content";
64 }
65
66 @GET
67 @Produces("application/double")
68 public String doGetDouble(@MatrixParam("double") double[] v) {
69 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[0], 0.0);
70 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[1], 0.0);
71 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[2], 0.0);
72 return "content";
73 }
74 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveArrayDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/array/default")
12 public class MatrixParamAsPrimitiveArrayDefault {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@MatrixParam("boolean") @DefaultValue("true") boolean[] v) {
16 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v[0]);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGetByte(@MatrixParam("byte") @DefaultValue("127") byte[] v) {
23 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v[0]);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGetShort(@MatrixParam("short") @DefaultValue("32767") short[] v) {
30 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v[0]);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGetInteger(@MatrixParam("int") @DefaultValue("2147483647") int[] v) {
37 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[0]);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGetLong(@MatrixParam("long") @DefaultValue("9223372036854775807") long[] v) {
44 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[0]);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGetFloat(@MatrixParam("float") @DefaultValue("3.14159265") float[] v) {
51 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[0], 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGetDouble(@MatrixParam("double") @DefaultValue("3.14159265358979") double[] v) {
58 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[0], 0.0);
59 return "content";
60 }
61 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveArrayDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.MatrixParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/array/default/null")
11 public class MatrixParamAsPrimitiveArrayDefaultNull {
12 @GET
13 @Produces("application/boolean")
14 public String doGetBoolean(@MatrixParam("boolean") boolean[] v) {
15 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.length == 0);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGetByte(@MatrixParam("byte") byte[] v) {
22 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.length == 0);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGetShort(@MatrixParam("short") short[] v) {
29 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.length == 0);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGetInteger(@MatrixParam("int") int[] v) {
36 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.length == 0);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGetLong(@MatrixParam("long") long[] v) {
43 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.length == 0);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGetFloat(@MatrixParam("float") float[] v) {
50 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.length == 0);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGetDouble(@MatrixParam("double") double[] v) {
57 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.length == 0);
58 return "content";
59 }
60 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveArrayDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/array/default/override")
12 public class MatrixParamAsPrimitiveArrayDefaultOverride {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@MatrixParam("boolean") @DefaultValue("false") boolean[] v) {
16 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v[0]);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGetByte(@MatrixParam("byte") @DefaultValue("0") byte[] v) {
23 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v[0]);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGetShort(@MatrixParam("short") @DefaultValue("0") short[] v) {
30 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v[0]);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGetInteger(@MatrixParam("int") @DefaultValue("0") int[] v) {
37 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[0]);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGetLong(@MatrixParam("long") @DefaultValue("0") long[] v) {
44 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[0]);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGetFloat(@MatrixParam("float") @DefaultValue("0.0") float[] v) {
51 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[0], 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGetDouble(@MatrixParam("double") @DefaultValue("0.0") double[] v) {
58 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[0], 0.0);
59 return "content";
60 }
61 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/default")
12 public class MatrixParamAsPrimitiveDefault {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@MatrixParam("boolean") @DefaultValue("true") boolean v) {
16 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@MatrixParam("byte") @DefaultValue("127") byte v) {
23 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@MatrixParam("short") @DefaultValue("32767") short v) {
30 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@MatrixParam("int") @DefaultValue("2147483647") int v) {
37 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@MatrixParam("long") @DefaultValue("9223372036854775807") long v) {
44 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@MatrixParam("float") @DefaultValue("3.14159265") float v) {
51 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v, 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@MatrixParam("double") @DefaultValue("3.14159265358979") double v) {
58 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v, 0.0);
59 return "content";
60 }
61 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.MatrixParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/default/null")
11 public class MatrixParamAsPrimitiveDefaultNull {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@MatrixParam("boolean") boolean v) {
15 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, false, v);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@MatrixParam("byte") byte v) {
22 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 0 == v);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@MatrixParam("short") short v) {
29 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 0 == v);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@MatrixParam("int") int v) {
36 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 0, v);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@MatrixParam("long") long v) {
43 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 0L, v);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@MatrixParam("float") float v) {
50 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 0.0f, v, 0.0f);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@MatrixParam("double") double v) {
57 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 0.0d, v, 0.0);
58 return "content";
59 }
60 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/default/override")
12 public class MatrixParamAsPrimitiveDefaultOverride {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@MatrixParam("boolean") @DefaultValue("false") boolean v) {
16 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@MatrixParam("byte") @DefaultValue("1") byte v) {
23 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@MatrixParam("short") @DefaultValue("1") short v) {
30 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@MatrixParam("int") @DefaultValue("1") int v) {
37 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@MatrixParam("long") @DefaultValue("1") long v) {
44 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@MatrixParam("float") @DefaultValue("0.0") float v) {
51 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v, 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@MatrixParam("double") @DefaultValue("0.0") double v) {
58 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v, 0.0);
59 return "content";
60 }
61 }
+0
-76
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveList.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.MatrixParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import java.util.List;
10
11 @Path("/list")
12 public class MatrixParamAsPrimitiveList {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@MatrixParam("boolean") List<Boolean> v) {
16 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(0).booleanValue());
17 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(1).booleanValue());
18 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(2).booleanValue());
19 return "content";
20 }
21
22 @GET
23 @Produces("application/byte")
24 public String doGetByte(@MatrixParam("byte") List<Byte> v) {
25 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.get(0).byteValue());
26 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.get(1).byteValue());
27 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.get(2).byteValue());
28 return "content";
29 }
30
31 @GET
32 @Produces("application/short")
33 public String doGetShort(@MatrixParam("short") List<Short> v) {
34 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v.get(0).shortValue());
35 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v.get(1).shortValue());
36 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v.get(2).shortValue());
37 return "content";
38 }
39
40 @GET
41 @Produces("application/int")
42 public String doGetInteger(@MatrixParam("int") List<Integer> v) {
43 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(0).intValue());
44 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(1).intValue());
45 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(2).intValue());
46 return "content";
47 }
48
49 @GET
50 @Produces("application/long")
51 public String doGetLong(@MatrixParam("long") List<Long> v) {
52 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(0).longValue());
53 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(1).longValue());
54 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(2).longValue());
55 return "content";
56 }
57
58 @GET
59 @Produces("application/float")
60 public String doGetFloat(@MatrixParam("float") List<Float> v) {
61 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(0).floatValue(), 0.0f);
62 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(1).floatValue(), 0.0f);
63 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(2).floatValue(), 0.0f);
64 return "content";
65 }
66
67 @GET
68 @Produces("application/double")
69 public String doGetDouble(@MatrixParam("double") List<Double> v) {
70 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(0).doubleValue(), 0.0);
71 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(1).doubleValue(), 0.0);
72 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(2).doubleValue(), 0.0);
73 return "content";
74 }
75 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveListDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import java.util.List;
11
12 @Path("/list/default")
13 public class MatrixParamAsPrimitiveListDefault {
14 @GET
15 @Produces("application/boolean")
16 public String doGetBoolean(@MatrixParam("boolean") @DefaultValue("true") List<Boolean> v) {
17 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(0).booleanValue());
18 return "content";
19 }
20
21 @GET
22 @Produces("application/byte")
23 public String doGetByte(@MatrixParam("byte") @DefaultValue("127") List<Byte> v) {
24 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.get(0).byteValue());
25 return "content";
26 }
27
28 @GET
29 @Produces("application/short")
30 public String doGetShort(@MatrixParam("short") @DefaultValue("32767") List<Short> v) {
31 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v.get(0).shortValue());
32 return "content";
33 }
34
35 @GET
36 @Produces("application/int")
37 public String doGetInteger(@MatrixParam("int") @DefaultValue("2147483647") List<Integer> v) {
38 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(0).intValue());
39 return "content";
40 }
41
42 @GET
43 @Produces("application/long")
44 public String doGetLong(@MatrixParam("long") @DefaultValue("9223372036854775807") List<Long> v) {
45 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(0).longValue());
46 return "content";
47 }
48
49 @GET
50 @Produces("application/float")
51 public String doGetFloat(@MatrixParam("float") @DefaultValue("3.14159265") List<Float> v) {
52 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(0).floatValue(), 0.0f);
53 return "content";
54 }
55
56 @GET
57 @Produces("application/double")
58 public String doGetDouble(@MatrixParam("double") @DefaultValue("3.14159265358979") List<Double> v) {
59 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(0).doubleValue(), 0.0);
60 return "content";
61 }
62 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveListDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.MatrixParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import java.util.List;
10
11 @Path("/list/default/null")
12 public class MatrixParamAsPrimitiveListDefaultNull {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@MatrixParam("boolean") List<Boolean> v) {
16 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.size() == 0);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGetByte(@MatrixParam("byte") List<Byte> v) {
23 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.size() == 0);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGetShort(@MatrixParam("short") List<Short> v) {
30 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.size() == 0);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGetInteger(@MatrixParam("int") List<Integer> v) {
37 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.size() == 0);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGetLong(@MatrixParam("long") List<Long> v) {
44 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.size() == 0);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGetFloat(@MatrixParam("float") List<Float> v) {
51 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.size() == 0);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGetDouble(@MatrixParam("double") List<Double> v) {
58 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, v.size() == 0);
59 return "content";
60 }
61 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveListDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10 import java.util.List;
11
12 @Path("/list/default/override")
13 public class MatrixParamAsPrimitiveListDefaultOverride {
14 @GET
15 @Produces("application/boolean")
16 public String doGetBoolean(@MatrixParam("boolean") @DefaultValue("false") List<Boolean> v) {
17 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(0).booleanValue());
18 return "content";
19 }
20
21 @GET
22 @Produces("application/byte")
23 public String doGetByte(@MatrixParam("byte") @DefaultValue("0") List<Byte> v) {
24 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.get(0).byteValue());
25 return "content";
26 }
27
28 @GET
29 @Produces("application/short")
30 public String doGetShort(@MatrixParam("short") @DefaultValue("0") List<Short> v) {
31 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v.get(0).shortValue());
32 return "content";
33 }
34
35 @GET
36 @Produces("application/int")
37 public String doGetInteger(@MatrixParam("int") @DefaultValue("0") List<Integer> v) {
38 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(0).intValue());
39 return "content";
40 }
41
42 @GET
43 @Produces("application/long")
44 public String doGetLong(@MatrixParam("long") @DefaultValue("0") List<Long> v) {
45 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(0).longValue());
46 return "content";
47 }
48
49 @GET
50 @Produces("application/float")
51 public String doGetFloat(@MatrixParam("float") @DefaultValue("0.0") List<Float> v) {
52 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(0).floatValue(), 0.0f);
53 return "content";
54 }
55
56 @GET
57 @Produces("application/double")
58 public String doGetDouble(@MatrixParam("double") @DefaultValue("0.0") List<Double> v) {
59 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(0).doubleValue(), 0.0);
60 return "content";
61 }
62 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitivePrimitives.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.MatrixParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/")
11 public class MatrixParamAsPrimitivePrimitives {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@MatrixParam("boolean") boolean v) {
15 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@MatrixParam("byte") byte v) {
22 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@MatrixParam("short") short v) {
29 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@MatrixParam("int") int v) {
36 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@MatrixParam("long") long v) {
43 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@MatrixParam("float") float v) {
50 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v, 0.0f);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@MatrixParam("double") double v) {
57 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v, 0.0);
58 return "content";
59 }
60 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveWrappers.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.MatrixParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/wrappers")
11 public class MatrixParamAsPrimitiveWrappers {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@MatrixParam("boolean") Boolean v) {
15 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v.booleanValue());
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@MatrixParam("byte") Byte v) {
22 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.byteValue());
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@MatrixParam("short") Short v) {
29 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v.shortValue());
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@MatrixParam("int") Integer v) {
36 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.intValue());
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@MatrixParam("long") Long v) {
43 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.longValue());
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@MatrixParam("float") Float v) {
50 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.floatValue(), 0.0f);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@MatrixParam("double") Double v) {
57 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.doubleValue(), 0.0);
58 return "content";
59 }
60 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveWrappersDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/wrappers/default")
12 public class MatrixParamAsPrimitiveWrappersDefault {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@MatrixParam("boolean") @DefaultValue("true") Boolean v) {
16 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v.booleanValue());
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@MatrixParam("byte") @DefaultValue("127") Byte v) {
23 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.byteValue());
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@MatrixParam("short") @DefaultValue("32767") Short v) {
30 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v.shortValue());
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@MatrixParam("int") @DefaultValue("2147483647") Integer v) {
37 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.intValue());
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@MatrixParam("long") @DefaultValue("9223372036854775807") Long v) {
44 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.longValue());
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@MatrixParam("float") @DefaultValue("3.14159265") Float v) {
51 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.floatValue(), 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@MatrixParam("double") @DefaultValue("3.14159265358979") Double v) {
58 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.doubleValue(), 0.0);
59 return "content";
60 }
61 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveWrappersDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.MatrixParam;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9
10 @Path("/wrappers/default/null")
11 public class MatrixParamAsPrimitiveWrappersDefaultNull {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@MatrixParam("boolean") Boolean v) {
15 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@MatrixParam("byte") Byte v) {
22 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@MatrixParam("short") Short v) {
29 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@MatrixParam("int") Integer v) {
36 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@MatrixParam("long") Long v) {
43 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@MatrixParam("float") Float v) {
50 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@MatrixParam("double") Double v) {
57 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
58 return "content";
59 }
60 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/MatrixParamAsPrimitiveWrappersDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.MatrixParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.MatrixParam;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.Produces;
10
11 @Path("/wrappers/default/override")
12 public class MatrixParamAsPrimitiveWrappersDefaultOverride {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@MatrixParam("boolean") @DefaultValue("false") Boolean v) {
16 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, true, v.booleanValue());
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@MatrixParam("byte") @DefaultValue("1") Byte v) {
23 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.byteValue());
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@MatrixParam("short") @DefaultValue("1") Short v) {
30 Assert.assertTrue(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v.shortValue());
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@MatrixParam("int") @DefaultValue("1") Integer v) {
37 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.intValue());
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@MatrixParam("long") @DefaultValue("1") Long v) {
44 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.longValue());
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@MatrixParam("float") @DefaultValue("0.0") Float v) {
51 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.floatValue(), 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@MatrixParam("double") @DefaultValue("0.0") Double v) {
58 Assert.assertEquals(MatrixParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.doubleValue(), 0.0);
59 return "content";
60 }
61 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ParamConverterClient.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.HeaderParam;
3 import javax.ws.rs.MatrixParam;
4 import javax.ws.rs.PUT;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.QueryParam;
8
9 @Path("/")
10 public interface ParamConverterClient {
11 @Path("{pojo}")
12 @PUT
13 void put(@QueryParam("pojo") String q, @PathParam("pojo") String pp, @MatrixParam("pojo") String mp,
14 @HeaderParam("pojo") String hp);
15 }
+0
-10
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ParamConverterDefaultClient.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.PUT;
3 import javax.ws.rs.Path;
4
5 @Path("/")
6 public interface ParamConverterDefaultClient {
7 @PUT
8 void put();
9 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ParamConverterDefaultResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.DefaultValue;
5 import javax.ws.rs.HeaderParam;
6 import javax.ws.rs.MatrixParam;
7 import javax.ws.rs.PUT;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/")
12 public class ParamConverterDefaultResource {
13 @PUT
14 public void putDefault(@QueryParam("pojo") @DefaultValue("default") ParamConverterPOJO q,
15 @MatrixParam("pojo") @DefaultValue("default") ParamConverterPOJO mp, @DefaultValue("default") @HeaderParam("pojo") ParamConverterPOJO hp) {
16 Assert.assertEquals(q.getName(), "default");
17 Assert.assertEquals(mp.getName(), "default");
18 Assert.assertEquals(hp.getName(), "default");
19 }
20 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ParamConverterPOJO.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public class ParamConverterPOJO {
3 private String name;
4
5 public String getName() {
6 return name;
7 }
8
9 public void setName(String name) {
10 this.name = name;
11 }
12 }
+0
-15
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ParamConverterPOJOConverter.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.ext.ParamConverter;
3
4 public class ParamConverterPOJOConverter implements ParamConverter<ParamConverterPOJO> {
5 public ParamConverterPOJO fromString(String str) {
6 ParamConverterPOJO pojo = new ParamConverterPOJO();
7 pojo.setName(str);
8 return pojo;
9 }
10
11 public String toString(ParamConverterPOJO value) {
12 return value.getName();
13 }
14 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ParamConverterPOJOConverterProvider.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.ext.ParamConverter;
3 import javax.ws.rs.ext.ParamConverterProvider;
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.Type;
6
7 public class ParamConverterPOJOConverterProvider implements ParamConverterProvider {
8 @SuppressWarnings(value = "unchecked")
9 @Override
10 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
11 if (!ParamConverterPOJO.class.equals(rawType)) {
12 return null;
13 }
14 return (ParamConverter<T>) new ParamConverterPOJOConverter();
15 }
16 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ParamConverterResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.HeaderParam;
5 import javax.ws.rs.MatrixParam;
6 import javax.ws.rs.PUT;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.PathParam;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/")
12 public class ParamConverterResource {
13 @Path("{pojo}")
14 @PUT
15 public void put(@QueryParam("pojo") ParamConverterPOJO q, @PathParam("pojo") ParamConverterPOJO pp, @MatrixParam("pojo") ParamConverterPOJO mp,
16 @HeaderParam("pojo") ParamConverterPOJO hp) {
17 Assert.assertEquals(q.getName(), "pojo");
18 Assert.assertEquals(pp.getName(), "pojo");
19 Assert.assertEquals(mp.getName(), "pojo");
20 Assert.assertEquals(hp.getName(), "pojo");
21 }
22 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ParamInterfaceResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.CookieParam;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.HeaderParam;
5 import javax.ws.rs.MatrixParam;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8
9 @Path("/test")
10 public interface ParamInterfaceResource {
11 @Path("matrix")
12 @GET
13 @Produces("text/plain")
14 String getMatrix(@MatrixParam("param") String matrix);
15
16
17 @Path("cookie")
18 @GET
19 @Produces("text/plain")
20 String getCookie(@CookieParam("param") String cookie);
21
22 @Path("header")
23 @GET
24 @Produces("text/plain")
25 String getHeader(@HeaderParam("custom") String header);
26 }
+0
-26
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/ParamResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.CookieParam;
3
4 public class ParamResource implements ParamInterfaceResource {
5 public String getMatrix(String matrix) {
6 if (matrix == null) {
7 return "null";
8 }
9 return matrix;
10 }
11
12 public String getCookie(@CookieParam("param") String cookie) {
13 if (cookie == null) {
14 return "null";
15 }
16 return cookie;
17 }
18
19 public String getHeader(@CookieParam("custom") String header) {
20 if (header == null) {
21 return "null";
22 }
23 return header;
24 }
25 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9
10 @Path("/")
11 public class QueryParamAsPrimitiveResource implements QueryParamAsPrimitiveResourceQueryPrimitivesInterface {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@QueryParam("boolean") boolean v) {
15 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@QueryParam("byte") byte v) {
22 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@QueryParam("short") short v) {
29 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@QueryParam("int") int v) {
36 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@QueryParam("long") long v) {
43 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@QueryParam("float") float v) {
50 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v, 0.0f);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@QueryParam("double") double v) {
57 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v, 0.0);
58 return "content";
59 }
60 }
+0
-75
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceArray.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9
10 @Path("/array")
11 public class QueryParamAsPrimitiveResourceArray implements QueryParamAsPrimitiveResourceResourceArray {
12 @GET
13 @Produces("application/boolean")
14 public String doGetBoolean(@QueryParam("boolean") boolean[] v) {
15 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v[0]);
16 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v[1]);
17 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v[2]);
18 return "content";
19 }
20
21 @GET
22 @Produces("application/byte")
23 public String doGetByte(@QueryParam("byte") byte[] v) {
24 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v[0]);
25 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v[1]);
26 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v[2]);
27 return "content";
28 }
29
30 @GET
31 @Produces("application/short")
32 public String doGetShort(@QueryParam("short") short[] v) {
33 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v[0]);
34 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v[1]);
35 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v[2]);
36 return "content";
37 }
38
39 @GET
40 @Produces("application/int")
41 public String doGetInteger(@QueryParam("int") int[] v) {
42 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[0]);
43 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[1]);
44 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[2]);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/long")
50 public String doGetLong(@QueryParam("long") long[] v) {
51 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[0]);
52 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[1]);
53 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[2]);
54 return "content";
55 }
56
57 @GET
58 @Produces("application/float")
59 public String doGetFloat(@QueryParam("float") float[] v) {
60 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[0], 0.0f);
61 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[1], 0.0f);
62 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[2], 0.0f);
63 return "content";
64 }
65
66 @GET
67 @Produces("application/double")
68 public String doGetDouble(@QueryParam("double") double[] v) {
69 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[0], 0.0);
70 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[1], 0.0);
71 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[2], 0.0);
72 return "content";
73 }
74 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceArrayDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/array/default")
12 public class QueryParamAsPrimitiveResourceArrayDefault {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@QueryParam("boolean") @DefaultValue("true") boolean[] v) {
16 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v[0]);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGetByte(@QueryParam("byte") @DefaultValue("127") byte[] v) {
23 Assert.assertTrue((byte) 127 == v[0]);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGetShort(@QueryParam("short") @DefaultValue("32767") short[] v) {
30 Assert.assertTrue((short) 32767 == v[0]);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGetInteger(@QueryParam("int") @DefaultValue("2147483647") int[] v) {
37 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[0]);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGetLong(@QueryParam("long") @DefaultValue("9223372036854775807") long[] v) {
44 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[0]);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGetFloat(@QueryParam("float") @DefaultValue("3.14159265") float[] v) {
51 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[0], 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGetDouble(@QueryParam("double") @DefaultValue("3.14159265358979") double[] v) {
58 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[0], 0.0);
59 return "content";
60 }
61 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceArrayDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9
10 @Path("/array/default/null")
11 public class QueryParamAsPrimitiveResourceArrayDefaultNull {
12 @GET
13 @Produces("application/boolean")
14 public String doGetBoolean(@QueryParam("boolean") boolean[] v) {
15 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.length);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGetByte(@QueryParam("byte") byte[] v) {
22 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.length);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGetShort(@QueryParam("short") short[] v) {
29 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.length);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGetInteger(@QueryParam("int") int[] v) {
36 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.length);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGetLong(@QueryParam("long") long[] v) {
43 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.length);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGetFloat(@QueryParam("float") float[] v) {
50 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.length);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGetDouble(@QueryParam("double") double[] v) {
57 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.length);
58 return "content";
59 }
60 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceArrayDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/array/default/override")
12 public class QueryParamAsPrimitiveResourceArrayDefaultOverride {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@QueryParam("boolean") @DefaultValue("false") boolean[] v) {
16 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v[0]);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGetByte(@QueryParam("byte") @DefaultValue("0") byte[] v) {
23 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v[0]);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGetShort(@QueryParam("short") @DefaultValue("0") short[] v) {
30 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v[0]);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGetInteger(@QueryParam("int") @DefaultValue("0") int[] v) {
37 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v[0]);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGetLong(@QueryParam("long") @DefaultValue("0") long[] v) {
44 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v[0]);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGetFloat(@QueryParam("float") @DefaultValue("0.0") float[] v) {
51 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v[0], 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGetDouble(@QueryParam("double") @DefaultValue("0.0") double[] v) {
58 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v[0], 0.0);
59 return "content";
60 }
61 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/default")
12 public class QueryParamAsPrimitiveResourceDefault {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@QueryParam("boolean") @DefaultValue("true") boolean v) {
16 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@QueryParam("byte") @DefaultValue("127") byte v) {
23 Assert.assertTrue((byte) 127 == v);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@QueryParam("short") @DefaultValue("32767") short v) {
30 Assert.assertTrue((short) 32767 == v);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@QueryParam("int") @DefaultValue("2147483647") int v) {
37 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@QueryParam("long") @DefaultValue("9223372036854775807") long v) {
44 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@QueryParam("float") @DefaultValue("3.14159265") float v) {
51 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v, 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@QueryParam("double") @DefaultValue("3.14159265358979") double v) {
58 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v, 0.0);
59 return "content";
60 }
61 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9
10 @Path("/default/null")
11 public class QueryParamAsPrimitiveResourceDefaultNull {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@QueryParam("boolean") boolean v) {
15 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, false, v);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@QueryParam("byte") byte v) {
22 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0 == v);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@QueryParam("short") short v) {
29 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0 == v);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@QueryParam("int") int v) {
36 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@QueryParam("long") long v) {
43 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0L, v);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@QueryParam("float") float v) {
50 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0.0f, v, 0.0f);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@QueryParam("double") double v) {
57 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0.0d, v, 0.0);
58 return "content";
59 }
60 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/default/override")
12 public class QueryParamAsPrimitiveResourceDefaultOverride {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@QueryParam("boolean") @DefaultValue("false") boolean v) {
16 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v);
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@QueryParam("byte") @DefaultValue("1") byte v) {
23 Assert.assertTrue((byte) 127 == v);
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@QueryParam("short") @DefaultValue("1") short v) {
30 Assert.assertTrue((short) 32767 == v);
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@QueryParam("int") @DefaultValue("1") int v) {
37 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v);
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@QueryParam("long") @DefaultValue("1") long v) {
44 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v);
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@QueryParam("float") @DefaultValue("0.0") float v) {
51 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v, 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@QueryParam("double") @DefaultValue("0.0") double v) {
58 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v, 0.0);
59 return "content";
60 }
61 }
+0
-76
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceList.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9 import java.util.List;
10
11 @Path("/list")
12 public class QueryParamAsPrimitiveResourceList implements QueryParamAsPrimitiveResourceResourceListInterface {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@QueryParam("boolean") List<Boolean> v) {
16 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(0).booleanValue());
17 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(1).booleanValue());
18 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(2).booleanValue());
19 return "content";
20 }
21
22 @GET
23 @Produces("application/byte")
24 public String doGetByte(@QueryParam("byte") List<Byte> v) {
25 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.get(0).byteValue());
26 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.get(1).byteValue());
27 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.get(2).byteValue());
28 return "content";
29 }
30
31 @GET
32 @Produces("application/short")
33 public String doGetShort(@QueryParam("short") List<Short> v) {
34 Assert.assertTrue((short) 32767 == v.get(0).shortValue());
35 Assert.assertTrue((short) 32767 == v.get(1).shortValue());
36 Assert.assertTrue((short) 32767 == v.get(2).shortValue());
37 return "content";
38 }
39
40 @GET
41 @Produces("application/int")
42 public String doGetInteger(@QueryParam("int") List<Integer> v) {
43 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(0).intValue());
44 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(1).intValue());
45 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(2).intValue());
46 return "content";
47 }
48
49 @GET
50 @Produces("application/long")
51 public String doGetLong(@QueryParam("long") List<Long> v) {
52 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(0).longValue());
53 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(1).longValue());
54 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(2).longValue());
55 return "content";
56 }
57
58 @GET
59 @Produces("application/float")
60 public String doGetFloat(@QueryParam("float") List<Float> v) {
61 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(0).floatValue(), 0.0f);
62 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(1).floatValue(), 0.0f);
63 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(2).floatValue(), 0.0f);
64 return "content";
65 }
66
67 @GET
68 @Produces("application/double")
69 public String doGetDouble(@QueryParam("double") List<Double> v) {
70 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(0).doubleValue(), 0.0);
71 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(1).doubleValue(), 0.0);
72 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(2).doubleValue(), 0.0);
73 return "content";
74 }
75 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceListDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10 import java.util.List;
11
12 @Path("/list/default")
13 public class QueryParamAsPrimitiveResourceListDefault {
14 @GET
15 @Produces("application/boolean")
16 public String doGetBoolean(@QueryParam("boolean") @DefaultValue("true") List<Boolean> v) {
17 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(0).booleanValue());
18 return "content";
19 }
20
21 @GET
22 @Produces("application/byte")
23 public String doGetByte(@QueryParam("byte") @DefaultValue("127") List<Byte> v) {
24 Assert.assertTrue((byte) 127 == v.get(0).byteValue());
25 return "content";
26 }
27
28 @GET
29 @Produces("application/short")
30 public String doGetShort(@QueryParam("short") @DefaultValue("32767") List<Short> v) {
31 Assert.assertTrue((short) 32767 == v.get(0).shortValue());
32 return "content";
33 }
34
35 @GET
36 @Produces("application/int")
37 public String doGetInteger(@QueryParam("int") @DefaultValue("2147483647") List<Integer> v) {
38 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(0).intValue());
39 return "content";
40 }
41
42 @GET
43 @Produces("application/long")
44 public String doGetLong(@QueryParam("long") @DefaultValue("9223372036854775807") List<Long> v) {
45 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(0).longValue());
46 return "content";
47 }
48
49 @GET
50 @Produces("application/float")
51 public String doGetFloat(@QueryParam("float") @DefaultValue("3.14159265") List<Float> v) {
52 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(0).floatValue(), 0.0f);
53 return "content";
54 }
55
56 @GET
57 @Produces("application/double")
58 public String doGetDouble(@QueryParam("double") @DefaultValue("3.14159265358979") List<Double> v) {
59 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(0).doubleValue(), 0.0);
60 return "content";
61 }
62 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceListDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9 import java.util.List;
10
11 @Path("/list/default/null")
12 public class QueryParamAsPrimitiveResourceListDefaultNull {
13 @GET
14 @Produces("application/boolean")
15 public String doGetBoolean(@QueryParam("boolean") List<Boolean> v) {
16 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.size());
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGetByte(@QueryParam("byte") List<Byte> v) {
23 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.size());
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGetShort(@QueryParam("short") List<Short> v) {
30 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.size());
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGetInteger(@QueryParam("int") List<Integer> v) {
37 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.size());
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGetLong(@QueryParam("long") List<Long> v) {
44 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.size());
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGetFloat(@QueryParam("float") List<Float> v) {
51 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.size());
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGetDouble(@QueryParam("double") List<Double> v) {
58 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v.size());
59 return "content";
60 }
61 }
+0
-63
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceListDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10 import java.util.List;
11
12 @Path("/list/default/override")
13 public class QueryParamAsPrimitiveResourceListDefaultOverride {
14 @GET
15 @Produces("application/boolean")
16 public String doGetBoolean(@QueryParam("boolean") @DefaultValue("false") List<Boolean> v) {
17 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v.get(0).booleanValue());
18 return "content";
19 }
20
21 @GET
22 @Produces("application/byte")
23 public String doGetByte(@QueryParam("byte") @DefaultValue("0") List<Byte> v) {
24 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (byte) 127 == v.get(0).byteValue());
25 return "content";
26 }
27
28 @GET
29 @Produces("application/short")
30 public String doGetShort(@QueryParam("short") @DefaultValue("0") List<Short> v) {
31 Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, (short) 32767 == v.get(0).shortValue());
32 return "content";
33 }
34
35 @GET
36 @Produces("application/int")
37 public String doGetInteger(@QueryParam("int") @DefaultValue("0") List<Integer> v) {
38 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.get(0).intValue());
39 return "content";
40 }
41
42 @GET
43 @Produces("application/long")
44 public String doGetLong(@QueryParam("long") @DefaultValue("0") List<Long> v) {
45 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.get(0).longValue());
46 return "content";
47 }
48
49 @GET
50 @Produces("application/float")
51 public String doGetFloat(@QueryParam("float") @DefaultValue("0.0") List<Float> v) {
52 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.get(0).floatValue(), 0.0f);
53 return "content";
54 }
55
56 @GET
57 @Produces("application/double")
58 public String doGetDouble(@QueryParam("double") @DefaultValue("0.0") List<Double> v) {
59 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.get(0).doubleValue(), 0.0);
60 return "content";
61 }
62 }
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceQueryPrimitivesInterface.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.QueryParam;
6
7 @Path("/")
8 public interface QueryParamAsPrimitiveResourceQueryPrimitivesInterface {
9 @GET
10 @Produces("application/boolean")
11 String doGet(@QueryParam("boolean") boolean v);
12
13 @GET
14 @Produces("application/byte")
15 String doGet(@QueryParam("byte") byte v);
16
17 @GET
18 @Produces("application/short")
19 String doGet(@QueryParam("short") short v);
20
21 @GET
22 @Produces("application/int")
23 String doGet(@QueryParam("int") int v);
24
25 @GET
26 @Produces("application/long")
27 String doGet(@QueryParam("long") long v);
28
29 @GET
30 @Produces("application/float")
31 String doGet(@QueryParam("float") float v);
32
33 @GET
34 @Produces("application/double")
35 String doGet(@QueryParam("double") double v);
36 }
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceResourceArray.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.QueryParam;
6
7 @Path("/array")
8 public interface QueryParamAsPrimitiveResourceResourceArray {
9 @GET
10 @Produces("application/boolean")
11 String doGetBoolean(@QueryParam("boolean") boolean[] v);
12
13 @GET
14 @Produces("application/byte")
15 String doGetByte(@QueryParam("byte") byte[] v);
16
17 @GET
18 @Produces("application/short")
19 String doGetShort(@QueryParam("short") short[] v);
20
21 @GET
22 @Produces("application/int")
23 String doGetInteger(@QueryParam("int") int[] v);
24
25 @GET
26 @Produces("application/long")
27 String doGetLong(@QueryParam("long") long[] v);
28
29 @GET
30 @Produces("application/float")
31 String doGetFloat(@QueryParam("float") float[] v);
32
33 @GET
34 @Produces("application/double")
35 String doGetDouble(@QueryParam("double") double[] v);
36 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceResourceListInterface.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.QueryParam;
6 import java.util.List;
7
8 @Path("/list")
9 public interface QueryParamAsPrimitiveResourceResourceListInterface {
10 @GET
11 @Produces("application/boolean")
12 String doGetBoolean(@QueryParam("boolean") List<Boolean> v);
13
14 @GET
15 @Produces("application/byte")
16 String doGetByte(@QueryParam("byte") List<Byte> v);
17
18 @GET
19 @Produces("application/short")
20 String doGetShort(@QueryParam("short") List<Short> v);
21
22 @GET
23 @Produces("application/int")
24 String doGetInteger(@QueryParam("int") List<Integer> v);
25
26 @GET
27 @Produces("application/long")
28 String doGetLong(@QueryParam("long") List<Long> v);
29
30 @GET
31 @Produces("application/float")
32 String doGetFloat(@QueryParam("float") List<Float> v);
33
34 @GET
35 @Produces("application/double")
36 String doGetDouble(@QueryParam("double") List<Double> v);
37 }
+0
-37
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceResourceWrappersInterface.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.QueryParam;
6
7 @Path("/wrappers")
8 public interface QueryParamAsPrimitiveResourceResourceWrappersInterface {
9 @GET
10 @Produces("application/boolean")
11 String doGet(@QueryParam("boolean") Boolean v);
12
13 @GET
14 @Produces("application/byte")
15 String doGet(@QueryParam("byte") Byte v);
16
17 @GET
18 @Produces("application/short")
19 String doGet(@QueryParam("short") Short v);
20
21 @GET
22 @Produces("application/int")
23 String doGet(@QueryParam("int") Integer v);
24
25 @GET
26 @Produces("application/long")
27 String doGet(@QueryParam("long") Long v);
28
29 @GET
30 @Produces("application/float")
31 String doGet(@QueryParam("float") Float v);
32
33 @GET
34 @Produces("application/double")
35 String doGet(@QueryParam("double") Double v);
36 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceWrappers.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9
10 @Path("/wrappers")
11 public class QueryParamAsPrimitiveResourceWrappers implements QueryParamAsPrimitiveResourceResourceWrappersInterface {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@QueryParam("boolean") Boolean v) {
15 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v.booleanValue());
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@QueryParam("byte") Byte v) {
22 Assert.assertTrue((byte) 127 == v.byteValue());
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@QueryParam("short") Short v) {
29 Assert.assertTrue((short) 32767 == v.shortValue());
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@QueryParam("int") Integer v) {
36 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.intValue());
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@QueryParam("long") Long v) {
43 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.longValue());
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@QueryParam("float") Float v) {
50 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.floatValue(), 0.0f);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@QueryParam("double") Double v) {
57 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.doubleValue(), 0.0);
58 return "content";
59 }
60 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceWrappersDefault.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/wrappers/default")
12 public class QueryParamAsPrimitiveResourceWrappersDefault {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@QueryParam("boolean") @DefaultValue("true") Boolean v) {
16 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v.booleanValue());
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@QueryParam("byte") @DefaultValue("127") Byte v) {
23 Assert.assertTrue((byte) 127 == v.byteValue());
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@QueryParam("short") @DefaultValue("32767") Short v) {
30 Assert.assertTrue((short) 32767 == v.shortValue());
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@QueryParam("int") @DefaultValue("2147483647") Integer v) {
37 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.intValue());
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@QueryParam("long") @DefaultValue("9223372036854775807") Long v) {
44 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.longValue());
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@QueryParam("float") @DefaultValue("3.14159265") Float v) {
51 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.floatValue(), 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@QueryParam("double") @DefaultValue("3.14159265358979") Double v) {
58 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.doubleValue(), 0.0);
59 return "content";
60 }
61 }
+0
-61
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceWrappersDefaultNull.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9
10 @Path("/wrappers/default/null")
11 public class QueryParamAsPrimitiveResourceWrappersDefaultNull {
12 @GET
13 @Produces("application/boolean")
14 public String doGet(@QueryParam("boolean") Boolean v) {
15 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
16 return "content";
17 }
18
19 @GET
20 @Produces("application/byte")
21 public String doGet(@QueryParam("byte") Byte v) {
22 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
23 return "content";
24 }
25
26 @GET
27 @Produces("application/short")
28 public String doGet(@QueryParam("short") Short v) {
29 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
30 return "content";
31 }
32
33 @GET
34 @Produces("application/int")
35 public String doGet(@QueryParam("int") Integer v) {
36 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
37 return "content";
38 }
39
40 @GET
41 @Produces("application/long")
42 public String doGet(@QueryParam("long") Long v) {
43 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
44 return "content";
45 }
46
47 @GET
48 @Produces("application/float")
49 public String doGet(@QueryParam("float") Float v) {
50 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
51 return "content";
52 }
53
54 @GET
55 @Produces("application/double")
56 public String doGet(@QueryParam("double") Double v) {
57 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, null, v);
58 return "content";
59 }
60 }
+0
-62
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamAsPrimitiveResourceWrappersDefaultOverride.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.Produces;
9 import javax.ws.rs.QueryParam;
10
11 @Path("/wrappers/default/override")
12 public class QueryParamAsPrimitiveResourceWrappersDefaultOverride {
13 @GET
14 @Produces("application/boolean")
15 public String doGet(@QueryParam("boolean") @DefaultValue("false") Boolean v) {
16 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, true, v.booleanValue());
17 return "content";
18 }
19
20 @GET
21 @Produces("application/byte")
22 public String doGet(@QueryParam("byte") @DefaultValue("1") Byte v) {
23 Assert.assertTrue((byte) 127 == v.byteValue());
24 return "content";
25 }
26
27 @GET
28 @Produces("application/short")
29 public String doGet(@QueryParam("short") @DefaultValue("1") Short v) {
30 Assert.assertTrue((short) 32767 == v.shortValue());
31 return "content";
32 }
33
34 @GET
35 @Produces("application/int")
36 public String doGet(@QueryParam("int") @DefaultValue("1") Integer v) {
37 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 2147483647, v.intValue());
38 return "content";
39 }
40
41 @GET
42 @Produces("application/long")
43 public String doGet(@QueryParam("long") @DefaultValue("1") Long v) {
44 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 9223372036854775807L, v.longValue());
45 return "content";
46 }
47
48 @GET
49 @Produces("application/float")
50 public String doGet(@QueryParam("float") @DefaultValue("0.0") Float v) {
51 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265f, v.floatValue(), 0.0f);
52 return "content";
53 }
54
55 @GET
56 @Produces("application/double")
57 public String doGet(@QueryParam("double") @DefaultValue("0.0") Double v) {
58 Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 3.14159265358979d, v.doubleValue(), 0.0);
59 return "content";
60 }
61 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryParamWithMultipleEqualsResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.QueryParam;
5
6 @Path("/")
7 public class QueryParamWithMultipleEqualsResource {
8 @Path("test")
9 @GET
10 public String test(@QueryParam("foo") String incoming) {
11 return incoming;
12 }
13 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QueryResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.GET;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.MediaType;
7
8 import org.jboss.resteasy.annotations.Query;
9
10 @Path("search")
11 public class QueryResource {
12 @GET
13 @Produces(MediaType.TEXT_PLAIN)
14 @Consumes(MediaType.TEXT_PLAIN)
15 public String get(@Query QuerySearchQuery searchQuery) {
16 return searchQuery.toString();
17 }
18 }
+0
-20
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/QuerySearchQuery.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.QueryParam;
3
4 public class QuerySearchQuery {
5
6 @QueryParam("term")
7 private String term;
8
9 @QueryParam("order")
10 private String order;
11
12 @QueryParam("limit")
13 private String limit;
14
15 @Override
16 public String toString() {
17 return new StringBuilder("term: '").append(term).append("', order: '").append(order).append("', limit: '").append(limit).append("'").toString();
18 }
19 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SerializableWithParametersObject.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import java.io.Serializable;
3
4 public class SerializableWithParametersObject implements Serializable {
5 private static final long serialVersionUID = -1068336400309384949L;
6 private String s;
7
8 public SerializableWithParametersObject(final String s) {
9 this.s = s;
10 }
11
12 public String toString() {
13 return "Foo[" + s + "]";
14 }
15
16 public boolean equals(Object o) {
17 if (o == null || !(o instanceof SerializableWithParametersObject)) {
18 return false;
19 }
20 return this.s.equals(SerializableWithParametersObject.class.cast(o).s);
21 }
22
23 public int hashCode() {
24 return super.hashCode();
25 }
26 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SerializableWithParametersResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5
6 @Path("test")
7 public class SerializableWithParametersResource {
8 @GET
9 @SuppressWarnings("deprecation")
10 public Response test() {
11 return Response.ok().entity(new SerializableWithParametersObject("abc")).type(org.jboss.resteasy.plugins.providers.SerializableProvider.APPLICATION_SERIALIZABLE + ";q=0.5").build();
12 }
13 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SpecialCharsInUrlResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.junit.Assert;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.PathParam;
6 import javax.ws.rs.QueryParam;
7
8 @Path("/")
9 public class SpecialCharsInUrlResource {
10
11 private static final String decodedPart = "foo+bar gee@foo.com";
12 private static final String queryDecodedPart = "foo bar gee@foo.com";
13
14 @Path("/simple/{bar}")
15 @GET
16 public String get(@PathParam("bar") String pathParam, @QueryParam("foo") String queryParam) {
17 Assert.assertEquals(decodedPart, pathParam);
18 Assert.assertEquals(queryDecodedPart, queryParam);
19 return pathParam;
20 }
21 }
+0
-27
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/StringParamUnmarshallerDateFormatter.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.spi.StringParameterUnmarshaller;
3 import org.jboss.resteasy.test.resource.param.StringParamUnmarshallerTest;
4 import org.jboss.resteasy.util.FindAnnotation;
5
6 import java.lang.annotation.Annotation;
7 import java.text.ParseException;
8 import java.text.SimpleDateFormat;
9 import java.util.Date;
10
11 public class StringParamUnmarshallerDateFormatter implements StringParameterUnmarshaller<Date> {
12 private SimpleDateFormat formatter;
13
14 public void setAnnotations(Annotation[] annotations) {
15 StringParamUnmarshallerTest.StringParamUnmarshallerDateFormat format = FindAnnotation.findAnnotation(annotations, StringParamUnmarshallerTest.StringParamUnmarshallerDateFormat.class);
16 formatter = new SimpleDateFormat(format.value());
17 }
18
19 public Date fromString(String str) {
20 try {
21 return formatter.parse(str);
22 } catch (ParseException e) {
23 throw new RuntimeException(e);
24 }
25 }
26 }
+0
-6
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/StringParamUnmarshallerFruit.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public enum StringParamUnmarshallerFruit {
3 ORANGE,
4 PEAR
5 }
+0
-35
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/StringParamUnmarshallerService.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.StringParamUnmarshallerTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8 import javax.ws.rs.Produces;
9 import java.util.Calendar;
10 import java.util.Date;
11
12 @Path("/")
13 public class StringParamUnmarshallerService {
14 @GET
15 @Produces("text/plain")
16 @Path("/datetest/{date}")
17 public String get(@PathParam("date") @StringParamUnmarshallerTest.StringParamUnmarshallerDateFormat("MM-dd-yyyy") Date date) {
18 Calendar c = Calendar.getInstance();
19 c.setTime(date);
20 Assert.assertEquals("Wrong date", 3, c.get(Calendar.MONTH));
21 Assert.assertEquals("Wrong date", 23, c.get(Calendar.DAY_OF_MONTH));
22 Assert.assertEquals("Wrong date", 1977, c.get(Calendar.YEAR));
23 return date.toString();
24 }
25
26 @GET
27 @Produces("text/plain")
28 @Path("fromstring/{fruit}/{sport}")
29 public String getFromString(@PathParam("fruit") StringParamUnmarshallerFruit fruit, @PathParam("sport") StringParamUnmarshallerSport sport) {
30 Assert.assertEquals("Wrong fruit", fruit, StringParamUnmarshallerFruit.ORANGE);
31 Assert.assertEquals("Wrong sport", "football", sport.name);
32 return sport.name + fruit;
33 }
34 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/StringParamUnmarshallerSport.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public class StringParamUnmarshallerSport {
3 public String name;
4
5 public static StringParamUnmarshallerSport fromString(String str) {
6 StringParamUnmarshallerSport s = new StringParamUnmarshallerSport();
7 s.name = str;
8 return s;
9 }
10
11
12 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterCompany.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public class SuperStringConverterCompany {
3 private final String name;
4
5 public SuperStringConverterCompany(final String name) {
6 this.name = name;
7 }
8
9 public String getName() {
10 return name;
11 }
12
13 @Override
14 public String toString() {
15 return getName();
16 }
17 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterCompanyConverter.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.spi.StringConverter;
3
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class SuperStringConverterCompanyConverter extends SuperStringConverterObjectConverter<SuperStringConverterCompany> implements StringConverter<SuperStringConverterCompany> {
8 public SuperStringConverterCompany fromString(String value) {
9 return new SuperStringConverterCompany(value);
10 }
11
12 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterMyClient.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.PUT;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5
6 @Path("/")
7 public interface SuperStringConverterMyClient {
8 @Path("person/{person}")
9 @PUT
10 void put(@PathParam("person") SuperStringConverterPerson p);
11
12 @Path("company/{company}")
13 @PUT
14 void putCompany(@PathParam("company") SuperStringConverterCompany c);
15 }
+0
-9
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterObjectConverter.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.spi.StringConverter;
3
4 public abstract class SuperStringConverterObjectConverter<T> implements StringConverter<T> {
5 public String toString(T value) {
6 return value.toString();
7 }
8 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterPerson.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 public class SuperStringConverterPerson {
3 private final String name;
4
5 public SuperStringConverterPerson(final String name) {
6 this.name = name;
7 }
8
9 public String getName() {
10 return name;
11 }
12 }
+0
-9
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterPersonConverter.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.spi.StringConverter;
3
4 import javax.ws.rs.ext.Provider;
5
6 @Provider
7 public class SuperStringConverterPersonConverter extends SuperStringConverterSuperPersonConverter implements StringConverter<SuperStringConverterPerson> {
8 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterResource.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.junit.Assert;
3
4 import javax.ws.rs.PUT;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7
8 @Path("/")
9 public class SuperStringConverterResource {
10 @Path("person/{person}")
11 @PUT
12 public void put(@PathParam("person") SuperStringConverterPerson p) {
13 Assert.assertEquals(p.getName(), "name");
14 }
15
16 @Path("company/{company}")
17 @PUT
18 public void putCompany(@PathParam("company") SuperStringConverterCompany c) {
19 Assert.assertEquals(c.getName(), "name");
20 }
21 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/SuperStringConverterSuperPersonConverter.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.spi.StringConverter;
3
4 public abstract class SuperStringConverterSuperPersonConverter implements StringConverter<SuperStringConverterPerson> {
5 public SuperStringConverterPerson fromString(String value) {
6 return new SuperStringConverterPerson(value);
7 }
8
9 public String toString(SuperStringConverterPerson value) {
10 return value.getName();
11 }
12 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriBoolean.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/boolean/{arg}")
10 public class UriParamAsPrimitiveResourceUriBoolean {
11 @GET
12 public String doGet(@PathParam("arg") boolean v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, true, v);
14 return "content";
15 }
16 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriBooleanInterface.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5
6 @Path("/boolean/{arg}")
7 public interface UriParamAsPrimitiveResourceUriBooleanInterface {
8 @GET
9 String doGet(@PathParam("arg") boolean v);
10 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriBooleanWrapper.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/boolean/wrapper/{arg}")
10 public class UriParamAsPrimitiveResourceUriBooleanWrapper {
11 @GET
12 public String doGet(@PathParam("arg") Boolean v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, true, v.booleanValue());
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriByte.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/byte/{arg}")
10 public class UriParamAsPrimitiveResourceUriByte {
11 @GET
12 public String doGet(@PathParam("arg") byte v) {
13 Assert.assertTrue(UriParamAsPrimitiveTest.ERROR_CODE, 127 == v);
14 return "content";
15 }
16 }
+0
-11
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriByteInterface.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5
6 @Path("/byte/{arg}")
7 public interface UriParamAsPrimitiveResourceUriByteInterface {
8 @GET
9 String doGet(@PathParam("arg") byte v);
10 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriByteWrapper.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/byte/wrapper/{arg}")
10 public class UriParamAsPrimitiveResourceUriByteWrapper {
11 @GET
12 public String doGet(@PathParam("arg") Byte v) {
13 Assert.assertTrue(UriParamAsPrimitiveTest.ERROR_CODE, 127 == v.byteValue());
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriDouble.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/double/{arg}")
10 public class UriParamAsPrimitiveResourceUriDouble {
11 @GET
12 public String doGet(@PathParam("arg") double v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, 3.14159265358979d, v, 0.0);
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriDoubleWrapper.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/double/wrapper/{arg}")
10 public class UriParamAsPrimitiveResourceUriDoubleWrapper {
11 @GET
12 public String doGet(@PathParam("arg") Double v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, 3.14159265358979d, v.doubleValue(), 0.0);
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriFloat.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/float/{arg}")
10 public class UriParamAsPrimitiveResourceUriFloat {
11 @GET
12 public String doGet(@PathParam("arg") float v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, 3.14159265f, v, 0.0f);
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriFloatWrapper.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/float/wrapper/{arg}")
10 public class UriParamAsPrimitiveResourceUriFloatWrapper {
11 @GET
12 public String doGet(@PathParam("arg") Float v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, 3.14159265f, v.floatValue(), 0.0f);
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriInt.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/int/{arg}")
10 public class UriParamAsPrimitiveResourceUriInt {
11 @GET
12 public String doGet(@PathParam("arg") int v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, 2147483647, v);
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriIntWrapper.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/int/wrapper/{arg}")
10 public class UriParamAsPrimitiveResourceUriIntWrapper {
11 @GET
12 public String doGet(@PathParam("arg") Integer v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, 2147483647, v.intValue());
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriLong.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/long/{arg}")
10 public class UriParamAsPrimitiveResourceUriLong {
11 @GET
12 public String doGet(@PathParam("arg") long v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, 9223372036854775807L, v);
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriLongWrapper.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/long/wrapper/{arg}")
10 public class UriParamAsPrimitiveResourceUriLongWrapper {
11 @GET
12 public String doGet(@PathParam("arg") Long v) {
13 Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, 9223372036854775807L, v.longValue());
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriShort.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/short/{arg}")
10 public class UriParamAsPrimitiveResourceUriShort {
11 @GET
12 public String doGet(@PathParam("arg") short v) {
13 Assert.assertTrue(UriParamAsPrimitiveTest.ERROR_CODE, 32767 == v);
14 return "content";
15 }
16 }
+0
-17
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/resource/param/resource/UriParamAsPrimitiveResourceUriShortWrapper.java less more
0 package org.jboss.resteasy.test.resource.param.resource;
1
2 import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
3 import org.junit.Assert;
4
5 import javax.ws.rs.GET;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.PathParam;
8
9 @Path("/short/wrapper/{arg}")
10 public class UriParamAsPrimitiveResourceUriShortWrapper {
11 @GET
12 public String doGet(@PathParam("arg") Short v) {
13 Assert.assertTrue(UriParamAsPrimitiveTest.ERROR_CODE, 32767 == v.shortValue());
14 return "content";
15 }
16 }
+0
-114
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/CookieTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.test.response.resource.CookieResource;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.Test;
13 import org.junit.BeforeClass;
14 import org.junit.AfterClass;
15 import org.junit.Assert;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.core.NewCookie;
21 import javax.ws.rs.core.Response;
22
23 import java.util.List;
24 import java.util.Map;
25
26 /**
27 * @tpSubChapter Resteasy-client
28 * @tpChapter Integration tests
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class CookieTest {
34
35 protected final Logger logger = LogManager.getLogger(VariantsTest.class.getName());
36
37 static Client client;
38
39 @Deployment
40 public static Archive<?> deploy() {
41 WebArchive war = TestUtil.prepareArchive(CookieTest.class.getSimpleName());
42 return TestUtil.finishContainerPrepare(war, null, CookieResource.class);
43 }
44
45 private String generateURL(String path) {
46 return PortProviderUtil.generateURL(path, CookieTest.class.getSimpleName());
47 }
48
49 @BeforeClass
50 public static void setup() {
51 client = ClientBuilder.newClient();
52 }
53
54 @AfterClass
55 public static void close() {
56 client.close();
57 client = null;
58 }
59
60
61 /**
62 * @tpTestDetails Client sends GET request to the server, server text response, the response is then checked, that
63 * it contains cookie with guid parameter sent by server.
64 * @tpPassCrit Response contains cookie sent by server
65 * @tpSince RESTEasy 3.0.16
66 */
67 @Test
68 public void testWeirdCookie() {
69 Response response = client.target(generateURL("/cookie/weird")).request().get();
70 Assert.assertEquals(response.getStatus(), 200);
71 Map<String, NewCookie> cookies = response.getCookies();
72 for (String key : cookies.keySet()) {
73 logger.info("[" + key + "] >>>>>> " + cookies.get(key) + "");
74 }
75 for (String header : response.getStringHeaders().keySet()) {
76 logger.info("header: " + header);
77 List<String> values = response.getStringHeaders().get(header);
78 for (String val : values) {
79 logger.info(" " + val);
80 }
81 }
82 Assert.assertTrue("Cookie in the response doesn't contain 'guid', which was in the cookie send by the server.",
83 cookies.containsKey("guid"));
84 response.close();
85 }
86
87 /**
88 * @tpTestDetails Client sends GET request to the server, server text response, the response is then checked, that
89 * it contains standard cookie sent by server.
90 * @tpPassCrit Response contains cookie sent by server
91 * @tpSince RESTEasy 3.0.16
92 */
93 @Test
94 public void testStandardCookie() {
95 Response response = client.target(generateURL("/cookie/standard")).request().get();
96 Assert.assertEquals(response.getStatus(), 200);
97 Map<String, NewCookie> cookies = response.getCookies();
98 for (String key : cookies.keySet()) {
99 logger.info("[" + key + "] >>>>>> " + cookies.get(key) + "");
100 Assert.assertEquals("Cookie content in the response doesn't match the cookie content send by the server.",
101 "UserID=JohnDoe;Version=1;Max-Age=3600", cookies.get(key).toString());
102 }
103 for (String header : response.getStringHeaders().keySet()) {
104 logger.info("header: " + header);
105 List<String> values = response.getStringHeaders().get(header);
106 for (String val : values) {
107 logger.info(" " + val);
108 }
109 }
110 response.close();
111 }
112
113 }
+0
-215
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/DuplicitePathTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.category.ExpectedFailing;
6 import org.jboss.resteasy.category.NotForForwardCompatibility;
7 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
8 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
9 import org.jboss.resteasy.test.response.resource.DuplicitePathDupliciteApplicationOne;
10 import org.jboss.resteasy.test.response.resource.DuplicitePathDupliciteApplicationTwo;
11 import org.jboss.resteasy.test.response.resource.DuplicitePathDupliciteResourceOne;
12 import org.jboss.resteasy.test.response.resource.DuplicitePathDupliciteResourceTwo;
13 import org.jboss.resteasy.test.response.resource.DuplicitePathMethodResource;
14 import org.jboss.resteasy.test.response.resource.DuplicitePathNoDupliciteApplication;
15 import org.jboss.resteasy.util.HttpResponseCodes;
16 import org.jboss.resteasy.utils.PortProviderUtil;
17 import org.jboss.resteasy.utils.TestUtil;
18 import org.jboss.shrinkwrap.api.Archive;
19 import org.jboss.shrinkwrap.api.ShrinkWrap;
20 import org.jboss.shrinkwrap.api.spec.WebArchive;
21 import org.junit.AfterClass;
22 import org.junit.Assert;
23 import org.junit.BeforeClass;
24 import org.junit.Test;
25 import org.junit.experimental.categories.Category;
26 import org.junit.runner.RunWith;
27
28 import javax.ws.rs.client.WebTarget;
29 import javax.ws.rs.core.MediaType;
30 import javax.ws.rs.core.Response;
31
32 import static org.hamcrest.CoreMatchers.either;
33 import static org.hamcrest.CoreMatchers.is;
34
35 /**
36 * @tpSubChapter Response
37 * @tpChapter Integration tests
38 * @tpTestCaseDetails Regression test for JBEAP-3459
39 * @tpSince RESTEasy 3.0.17
40 */
41 @RunWith(Arquillian.class)
42 @RunAsClient
43 public class DuplicitePathTest {
44 static ResteasyClient client;
45
46 private static int getWarningCount() {
47 return TestUtil.getWarningCount("RESTEASY002142", false);
48 }
49
50 @Deployment
51 public static Archive<?> deploySimpleResource() {
52 WebArchive war = ShrinkWrap.create(WebArchive.class, DuplicitePathTest.class.getSimpleName() + ".war");
53 war.addClass(DuplicitePathDupliciteApplicationOne.class);
54 war.addClass(DuplicitePathDupliciteApplicationTwo.class);
55 war.addClass(DuplicitePathDupliciteResourceOne.class);
56 war.addClass(DuplicitePathDupliciteResourceTwo.class);
57 war.addClass(DuplicitePathMethodResource.class);
58 war.addClass(DuplicitePathNoDupliciteApplication.class);
59 return war;
60 }
61
62 @BeforeClass
63 public static void init() {
64 client = new ResteasyClientBuilder().build();
65 }
66
67 @AfterClass
68 public static void close() {
69 client.close();
70 client = null;
71 }
72
73 private String generateURL(String path) {
74 return PortProviderUtil.generateURL(path, DuplicitePathTest.class.getSimpleName());
75 }
76
77 /**
78 * @tpTestDetails Check that warning message was logged, if client makes request to path,
79 * that is handled by two methods in two end-point in two application classes
80 * @tpSince RESTEasy 3.0.17
81 */
82 @Test
83 @Category({NotForForwardCompatibility.class, ExpectedFailing.class}) //[RESTEASY-1445] FIXME
84 public void testDuplicationTwoAppTwoResourceSameMethodPath() throws Exception {
85 int initWarningsCount = getWarningCount();
86 WebTarget base = client.target(generateURL("/a/b/c"));
87 Response response = null;
88 try {
89 response = base.request().get();
90 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
91 String strResponse = response.readEntity(String.class);
92 Assert.assertThat("Wrong body of response", strResponse,
93 either(is(DuplicitePathDupliciteResourceOne.DUPLICITE_RESPONSE))
94 .or(is(DuplicitePathDupliciteResourceTwo.DUPLICITE_RESPONSE)));
95 } finally {
96 response.close();
97 }
98 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("RESTEASY-1445", "Wrong count of warnings in server log"),
99 1, getWarningCount() - initWarningsCount);
100 }
101
102 /**
103 * @tpTestDetails Check that warning message was logged, if client makes request to path,
104 * that is handled by two methods in two end-point in two application classes
105 * @tpSince RESTEasy 3.0.17
106 */
107 @Test
108 @Category({NotForForwardCompatibility.class})
109 public void testDuplicationMoreAccepts() throws Exception {
110 int initWarningsCount = getWarningCount();
111 WebTarget base = client.target(generateURL("/f/g/i"));
112 Response response = null;
113 try {
114 response = base.request().accept(MediaType.TEXT_PLAIN, MediaType.WILDCARD).get();
115 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
116 String strResponse = response.readEntity(String.class);
117 Assert.assertThat("Wrong body of response", strResponse,
118 is(DuplicitePathMethodResource.NO_DUPLICITE_RESPONSE));
119 } finally {
120 response.close();
121 }
122 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-3459", "Wrong count of warnings in server log"),
123 0, getWarningCount() - initWarningsCount);
124 }
125
126 /**
127 * @tpTestDetails Check that warning message was logged, if client makes request to path,
128 * that is handled by two methods in two end-point in two application classes
129 * @tpSince RESTEasy 3.0.17
130 */
131 @Test
132 @Category({NotForForwardCompatibility.class})
133 public void testDuplicationMoretypes() throws Exception {
134 int initWarningsCount = getWarningCount();
135 WebTarget base = client.target(generateURL("/f/g/j"));
136 Response response = null;
137 try {
138 response = base.request().accept(MediaType.TEXT_PLAIN, MediaType.WILDCARD).get();
139 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
140 String strResponse = response.readEntity(String.class);
141 Assert.assertThat("Wrong body of response", strResponse,
142 is(DuplicitePathMethodResource.DUPLICITE_TYPE_GET));
143 } finally {
144 response.close();
145 }
146 Assert.assertEquals(TestUtil.getErrorMessageForKnownIssue("JBEAP-3459", "Wrong count of warnings in server log"),
147 0, getWarningCount() - initWarningsCount);
148 }
149
150 /**
151 * @tpTestDetails Check that warning message was logged, if client makes request to path,
152 * that is handled by two methods in two end-point in one application classes
153 * @tpSince RESTEasy 3.0.17
154 */
155 @Test
156 @Category({NotForForwardCompatibility.class})
157 public void testDuplicationOneAppTwoResourcesWithSamePath() throws Exception {
158 int initWarningsCount = getWarningCount();
159 WebTarget base = client.target(generateURL("/f/b/c"));
160 Response response = null;
161 try {
162 response = base.request().get();
163 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
164 String strResponse = response.readEntity(String.class);
165 Assert.assertThat("Wrong body of response", strResponse,
166 either(is(DuplicitePathDupliciteResourceOne.DUPLICITE_RESPONSE))
167 .or(is(DuplicitePathDupliciteResourceTwo.DUPLICITE_RESPONSE)));
168 } finally {
169 response.close();
170 }
171 Assert.assertEquals("Wrong count of warnings in server log", 1, getWarningCount() - initWarningsCount);
172 }
173
174 /**
175 * @tpTestDetails Check that warning message was logged, if client makes request to path, that is handled by two methods
176 * @tpSince RESTEasy 3.0.17
177 */
178 @Test
179 @Category({NotForForwardCompatibility.class})
180 public void testDuplicationPathInMethod() throws Exception {
181 int initWarningsCount = getWarningCount();
182 WebTarget base = client.target(generateURL("/f/g/h"));
183 Response response = null;
184 try {
185 response = base.request().get();
186 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
187 Assert.assertThat("Wrong body of response", response.readEntity(String.class),
188 either(is(DuplicitePathMethodResource.DUPLICITE_RESPONSE_1))
189 .or(is(DuplicitePathMethodResource.DUPLICITE_RESPONSE_2)));
190 } finally {
191 response.close();
192 }
193 Assert.assertEquals("Wrong count of warnings in server log", 1, getWarningCount() - initWarningsCount);
194 }
195
196 /**
197 * @tpTestDetails Check that warning message was not logged, if client makes request to path, that is handled by one method (correct behaviour)
198 * @tpSince RESTEasy 3.0.17
199 */
200 @Test
201 public void testNoDuplicationPathInMethod() throws Exception {
202 int initWarningsCount = getWarningCount();
203 WebTarget base = client.target(generateURL("/f/g/i"));
204 Response response = null;
205 try {
206 response = base.request().get();
207 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
208 Assert.assertEquals("Wrong body of response", DuplicitePathMethodResource.NO_DUPLICITE_RESPONSE, response.readEntity(String.class));
209 } finally {
210 response.close();
211 }
212 Assert.assertEquals("Wrong count of warnings in server log", 0, getWarningCount() - initWarningsCount);
213 }
214 }
+0
-92
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/HeadContentLengthTest.java less more
0 /*
1 * JBoss, Home of Professional Open Source
2 * Copyright 2016, Red Hat Inc., and individual contributors as indicated
3 * by the @authors tag. See the copyright.txt in the distribution for a
4 * full listing of individual contributors.
5 *
6 * This is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 2.1 of
9 * the License, or (at your option) any later version.
10 *
11 * This software is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this software; if not, write to the Free
18 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
19 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
20 */
21 package org.jboss.resteasy.test.response;
22
23 import org.jboss.arquillian.container.test.api.Deployment;
24 import org.jboss.arquillian.container.test.api.RunAsClient;
25 import org.jboss.arquillian.junit.Arquillian;
26 import org.jboss.resteasy.test.response.resource.SimpleResource;
27 import org.jboss.resteasy.utils.PortProviderUtil;
28 import org.jboss.resteasy.utils.TestUtil;
29 import org.jboss.shrinkwrap.api.Archive;
30 import org.jboss.shrinkwrap.api.spec.WebArchive;
31 import org.junit.AfterClass;
32 import org.junit.Assert;
33 import org.junit.BeforeClass;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36
37 import javax.ws.rs.client.Client;
38 import javax.ws.rs.client.ClientBuilder;
39 import javax.ws.rs.client.Invocation.Builder;
40 import javax.ws.rs.core.MediaType;
41 import javax.ws.rs.core.Response;
42
43
44 /**
45 * RESTEASY-1365
46 *
47 * @author Ivo Studensky
48 */
49 @RunWith(Arquillian.class)
50 @RunAsClient
51 public class HeadContentLengthTest {
52
53 static Client client;
54
55 @Deployment
56 public static Archive<?> deploy() throws Exception {
57 WebArchive war = TestUtil.prepareArchive(HeadContentLengthTest.class.getSimpleName());
58 return TestUtil.finishContainerPrepare(war, null, SimpleResource.class);
59 }
60
61 @BeforeClass
62 public static void init() {
63 client = ClientBuilder.newClient();
64 }
65
66 @AfterClass
67 public static void after() throws Exception {
68 client.close();
69 }
70
71 private String generateURL(String path) {
72 return PortProviderUtil.generateURL(path, HeadContentLengthTest.class.getSimpleName());
73 }
74
75 @Test
76 public void testHeadContentLength() {
77 Builder builder = client.target(generateURL("/simpleresource")).request();
78 builder.accept(MediaType.TEXT_PLAIN_TYPE);
79
80 Response getResponse = builder.get();
81 String responseBody = getResponse.readEntity(String.class);
82 Assert.assertEquals("The response body doesn't match the expected", "hello", responseBody);
83 int getResponseLength = getResponse.getLength();
84 Assert.assertEquals("The response length doesn't match the expected", 5, getResponseLength);
85
86 Response headResponse = builder.head();
87 int headResponseLength = headResponse.getLength();
88 Assert.assertEquals("The response length from GET and HEAD request doesn't match" , getResponseLength, headResponseLength);
89 }
90
91 }
+0
-86
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/HttpRequestParameterInjectorTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Old client test)
6 import org.jboss.resteasy.test.response.resource.HttpRequestParameterInjectorClassicParam;
7 import org.jboss.resteasy.test.response.resource.HttpRequestParameterInjectorParamFactoryImpl;
8 import org.jboss.resteasy.test.response.resource.HttpRequestParameterInjectorResource;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.Assert;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16
17 import javax.ws.rs.client.Client;
18 import javax.ws.rs.client.ClientBuilder;
19 import javax.ws.rs.client.Entity;
20 import javax.ws.rs.core.Form;
21
22
23 /**
24 * @tpSubChapter Localization
25 * @tpChapter Integration tests
26 * @tpTestCaseDetails Test for InjectorFactoryImpl. It is used for new type of parameters in resource.
27 * @tpSince RESTEasy 3.0.16
28 */
29 @RunWith(Arquillian.class)
30 @RunAsClient
31 public class HttpRequestParameterInjectorTest {
32
33 private static final String DEPLOYMENT_NAME = "app";
34
35 @Deployment
36 public static Archive<?> deploySimpleResource() {
37 WebArchive war = TestUtil.prepareArchive(DEPLOYMENT_NAME);
38 war.addClass(HttpRequestParameterInjectorClassicParam.class);
39 return TestUtil.finishContainerPrepare(war, null, HttpRequestParameterInjectorResource.class,
40 HttpRequestParameterInjectorParamFactoryImpl.class);
41 }
42
43 private String generateURL(String path) {
44 return PortProviderUtil.generateURL(path, DEPLOYMENT_NAME);
45 }
46
47 /**
48 * @tpTestDetails New Client usage.
49 * @tpSince RESTEasy 3.0.16
50 */
51 @Test
52 public void testCustomInjectorFactory() throws Exception {
53 Client client = ClientBuilder.newClient();
54
55 String getResult = client.target(generateURL("/foo")).queryParam("param", "getValue").request()
56 .accept("text/plain").get().readEntity(String.class);
57 Assert.assertEquals("getValue, getValue, ", getResult);
58
59
60 Form form = new Form().param("param", "postValue");
61 String postResult = client.target(generateURL("/foo")).request()
62 .accept("text/plain").post(Entity.form(form)).readEntity(String.class);
63 Assert.assertEquals("postValue, , postValue", postResult);
64
65 client.close();
66 }
67
68 /**
69 * @tpTestDetails Old Client usage.
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test
73 public void testCustomInjectorFactoryOldClient() throws Exception {
74 String url = generateURL("/foo");
75
76 String getResult = new ClientRequest(url).queryParameter("param", "getValue").accept(
77 "text/plain").get(String.class).getEntity();
78 Assert.assertEquals("getValue, getValue, ", getResult);
79
80 String postResult = new ClientRequest(generateURL("/foo")).formParameter("param", "postValue").accept(
81 "text/plain").post(String.class).getEntity();
82 Assert.assertEquals("postValue, , postValue", postResult);
83 }
84
85 }
+0
-88
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/InheritedContextTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.response.resource.InheritedContextNewService;
8 import org.jboss.resteasy.test.response.resource.InheritedContextNewSubService;
9 import org.jboss.resteasy.test.response.resource.InheritedContextService;
10 import org.jboss.resteasy.util.HttpResponseCodes;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.Assert;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Invocation;
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Response
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Regression test for RESTEASY-952
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class InheritedContextTest {
31
32 @Deployment
33 public static Archive<?> deploySimpleResource() {
34 WebArchive war = TestUtil.prepareArchive(InheritedContextTest.class.getSimpleName());
35 return TestUtil.finishContainerPrepare(war, null, InheritedContextService.class,
36 InheritedContextNewService.class, InheritedContextNewSubService.class);
37 }
38
39 private String generateURL(String path) {
40 return PortProviderUtil.generateURL(path, InheritedContextTest.class.getSimpleName());
41 }
42
43 /**
44 * @tpTestDetails Test basic resource with no inheritance
45 * @tpSince RESTEasy 3.0.16
46 */
47 @Test
48 public void testContext() throws Exception {
49 ResteasyClient client = new ResteasyClientBuilder().build();
50 Invocation.Builder request = client.target(generateURL("/super/test/BaseService")).request();
51 Response response = request.get();
52 String s = response.readEntity(String.class);
53 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
54 Assert.assertEquals("true", s);
55 response.close();
56 }
57
58 /**
59 * @tpTestDetails Test basic resource with one level of inheritance
60 * @tpSince RESTEasy 3.0.16
61 */
62 @Test
63 public void testInheritedContextOneLevel() throws Exception {
64 ResteasyClient client = new ResteasyClientBuilder().build();
65 Invocation.Builder request = client.target(generateURL("/sub/test/SomeService")).request();
66 Response response = request.get();
67 String s = response.readEntity(String.class);
68 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
69 Assert.assertEquals("true", s);
70 response.close();
71 }
72
73 /**
74 * @tpTestDetails Test basic resource with two levels of inheritance
75 * @tpSince RESTEasy 3.0.16
76 */
77 @Test
78 public void testInheritedContextTwoLevels() throws Exception {
79 ResteasyClient client = new ResteasyClientBuilder().build();
80 Invocation.Builder request = client.target(generateURL("/subsub/test/SomeSubService")).request();
81 Response response = request.get();
82 String s = response.readEntity(String.class);
83 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
84 Assert.assertEquals("true", s);
85 response.close();
86 }
87 }
+0
-124
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/MethodDefaultTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.response.resource.MethodDefaultResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.Assert;
15 import org.junit.BeforeClass;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.core.Response;
20 import java.util.HashSet;
21
22 /**
23 * @tpSubChapter Response
24 * @tpChapter Integration tests
25 * @tpTestCaseDetails Spec requires that HEAD and OPTIONS are handled in a default manner
26 * @tpSince RESTEasy 3.0.16
27 */
28 @RunWith(Arquillian.class)
29 @RunAsClient
30 public class MethodDefaultTest {
31
32 static ResteasyClient client;
33
34 @Deployment
35 public static Archive<?> deploySimpleResource() {
36 WebArchive war = TestUtil.prepareArchive(MethodDefaultTest.class.getSimpleName());
37 return TestUtil.finishContainerPrepare(war, null, MethodDefaultResource.class);
38 }
39
40 @BeforeClass
41 public static void init() {
42 client = new ResteasyClientBuilder().build();
43 }
44
45 @AfterClass
46 public static void close() {
47 client.close();
48 }
49
50 private String generateURL(String path) {
51 return PortProviderUtil.generateURL(path, MethodDefaultTest.class.getSimpleName());
52 }
53
54 /**
55 * @tpTestDetails Client invokes Head on root resource at /GetTest;
56 * which no request method designated for HEAD;
57 * Verify that corresponding GET Method is invoked.
58 * @tpSince RESTEasy 3.0.16
59 */
60 @Test
61 public void testHeadPlain() throws Exception {
62 Response response = client.target(generateURL("/GetTest")).request().header("Accept", "text/plain").head();
63 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
64 String header = response.getHeaderString("CTS-HEAD");
65 Assert.assertEquals("Wrong CTS-HEAD header", "text-plain", header);
66 response.close();
67 }
68
69 /**
70 * @tpTestDetails Client invokes HEAD on root resource at /GetTest;
71 * which no request method designated for HEAD;
72 * Verify that corresponding GET Method is invoked.
73 * @tpSince RESTEasy 3.0.16
74 */
75 @Test
76 public void testHeadHtml() throws Exception {
77 Response response = client.target(generateURL("/GetTest")).request().header("Accept", "text/html").head();
78 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
79 String header = response.getHeaderString("CTS-HEAD");
80 Assert.assertEquals("Wrong CTS-HEAD header", "text-html", header);
81 response.close();
82 }
83
84 /**
85 * @tpTestDetails Client invokes HEAD on sub resource at /GetTest/sub;
86 * which no request method designated for HEAD;
87 * Verify that corresponding GET Method is invoked instead.
88 * @tpSince RESTEasy 3.0.16
89 */
90 @Test
91 public void testHeadSubresource() throws Exception {
92 Response response = client.target(generateURL("/GetTest/sub")).request().header("Accept", "text/plain").head();
93 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
94 String header = response.getHeaderString("CTS-HEAD");
95 Assert.assertEquals("Wrong CTS-HEAD header", "sub-text-plain", header);
96 response.close();
97 }
98
99 /**
100 * @tpTestDetails If client invokes OPTIONS and there is no request method that exists, verify that an automatic response is
101 * generated
102 * @tpSince RESTEasy 3.0.16
103 */
104 @Test
105 public void testOptions() throws Exception {
106
107 Response response = client.target(generateURL("/GetTest/sub")).request().options();
108 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
109 String allowedHeader = response.getHeaderString("Allow");
110 Assert.assertNotNull("Wrong Allow header", allowedHeader);
111 String[] allowed = allowedHeader.split(",");
112 HashSet<String> set = new HashSet<String>();
113 for (String allow : allowed) {
114 set.add(allow.trim());
115 }
116
117 Assert.assertTrue("Wrong Allow header", set.contains("GET"));
118 Assert.assertTrue("Wrong Allow header", set.contains("OPTIONS"));
119 Assert.assertTrue("Wrong Allow header", set.contains("HEAD"));
120 response.close();
121 }
122
123 }
+0
-157
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/OptionsTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
6 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
7 import org.jboss.resteasy.test.response.resource.OptionParamsResource;
8 import org.jboss.resteasy.test.response.resource.OptionUsersResource;
9 import org.jboss.resteasy.util.HttpResponseCodes;
10 import org.jboss.resteasy.utils.PortProviderUtil;
11 import org.jboss.resteasy.utils.TestUtil;
12 import org.jboss.shrinkwrap.api.Archive;
13 import org.jboss.shrinkwrap.api.spec.WebArchive;
14 import org.junit.AfterClass;
15 import org.junit.Assert;
16 import org.junit.BeforeClass;
17 import org.junit.Test;
18 import org.junit.runner.RunWith;
19
20 import java.util.HashSet;
21
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.client.WebTarget;
24 import javax.ws.rs.core.Response;
25
26
27 /**
28 * @tpSubChapter Response
29 * @tpChapter Integration tests
30 * @tpTestCaseDetails Regression test for RESTEASY-363
31 * @tpSince RESTEasy 3.0.16
32 */
33 @RunWith(Arquillian.class)
34 @RunAsClient
35 public class OptionsTest {
36
37 static ResteasyClient client;
38
39 @Deployment
40 public static Archive<?> deploySimpleResource() {
41 WebArchive war = TestUtil.prepareArchive(OptionsTest.class.getSimpleName());
42 return TestUtil.finishContainerPrepare(war, null, OptionParamsResource.class, OptionUsersResource.class);
43 }
44
45 @BeforeClass
46 public static void init() {
47 client = new ResteasyClientBuilder().build();
48 }
49
50 @AfterClass
51 public static void close() {
52 client.close();
53 }
54
55 private String generateURL(String path) {
56 return PortProviderUtil.generateURL(path, OptionsTest.class.getSimpleName());
57 }
58
59 /**
60 * @tpTestDetails Check options HTTP request
61 * @tpSince RESTEasy 3.0.16
62 */
63 @Test
64 public void testOptions() throws Exception {
65 WebTarget base = client.target(generateURL("/params/customers/333/phonenumbers"));
66 Response response = base.request().options();
67 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
68 response.close();
69 }
70
71 /**
72 * @tpTestDetails Check not allowed request
73 * @tpSince RESTEasy 3.0.16
74 */
75 @Test
76 public void testMethodNotAllowed() throws Exception {
77 WebTarget base = client.target(generateURL("/params/customers/333/phonenumbers"));
78 Response response = base.request().post(Entity.text(new String()));
79 Assert.assertEquals(HttpResponseCodes.SC_METHOD_NOT_ALLOWED, response.getStatus());
80 response.close();
81
82 base = client.target(generateURL("/users"));
83 response = base.request().delete();
84 Assert.assertEquals(HttpResponseCodes.SC_METHOD_NOT_ALLOWED, response.getStatus());
85 response.close();
86
87 base = client.target(generateURL("/users/53"));
88 response = base.request().post(Entity.text(new String()));
89 Assert.assertEquals(HttpResponseCodes.SC_METHOD_NOT_ALLOWED, response.getStatus());
90 response.close();
91
92 base = client.target(generateURL("/users/53/contacts"));
93 response = base.request().get();
94 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
95 response.close();
96
97 base = client.target(generateURL("/users/53/contacts"));
98 response = base.request().options();
99 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
100 response.close();
101
102 base = client.target(generateURL("/users/53/contacts"));
103 response = base.request().delete();
104 Assert.assertEquals(HttpResponseCodes.SC_METHOD_NOT_ALLOWED, response.getStatus());
105 response.close();
106
107 base = client.target(generateURL("/users/53/contacts/carl"));
108 response = base.request().get();
109 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
110 response.close();
111
112 base = client.target(generateURL("/users/53/contacts/carl"));
113 response = base.request().post(Entity.text(new String()));
114 Assert.assertEquals(HttpResponseCodes.SC_METHOD_NOT_ALLOWED, response.getStatus());
115 response.close();
116 }
117
118 /**
119 * @tpTestDetails Check Allow header on 200 status
120 * @tpSince RESTEasy 3.0.20
121 */
122 @Test
123 public void testAllowHeaderOK() {
124 WebTarget base = client.target(generateURL("/users/53/contacts"));
125 Response response = base.request().options();
126 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
127 checkOptions(response, "GET", "POST", "HEAD", "OPTIONS");
128 response.close();
129 }
130
131 /**
132 * @tpTestDetails Check Allow header on 405 status
133 * @tpSince RESTEasy 3.0.20
134 */
135 @Test
136 public void testAllowHeaderMethodNotAllowed() {
137 WebTarget base = client.target(generateURL("/params/customers/333/phonenumbers"));
138 Response response = base.request().post(Entity.text(new String()));
139 Assert.assertEquals(HttpResponseCodes.SC_METHOD_NOT_ALLOWED, response.getStatus());
140 checkOptions(response, "GET", "HEAD", "OPTIONS");
141 response.close();
142 }
143
144 private void checkOptions(Response response, String... verbs) {
145 String allowed = response.getHeaderString("Allow");
146 Assert.assertNotNull(allowed);
147 HashSet<String> vals = new HashSet<String>();
148 for (String v : allowed.split(",")) {
149 vals.add(v.trim());
150 }
151 Assert.assertEquals(verbs.length, vals.size());
152 for (String verb : verbs) {
153 Assert.assertTrue(vals.contains(verb));
154 }
155 }
156 }
+0
-164
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/ProduceConsumeTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.response.resource.ProduceConsumeData;
6 import org.jboss.resteasy.test.response.resource.ProduceConsumeResource;
7 import org.jboss.resteasy.test.response.resource.ProduceConsumeTextData;
8 import org.jboss.resteasy.test.response.resource.ProduceConsumeWildData;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.Assert;
15 import org.junit.BeforeClass;
16 import org.junit.Test;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.ProcessingException;
20 import javax.ws.rs.client.Client;
21 import javax.ws.rs.client.ClientBuilder;
22 import javax.ws.rs.client.Entity;
23 import javax.ws.rs.core.HttpHeaders;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.core.NoContentException;
27 import javax.ws.rs.core.Response;
28 import java.math.BigDecimal;
29
30 /**
31 * @tpSubChapter Resteasy-client
32 * @tpChapter Integration tests
33 * @tpSince RESTEasy 3.0.16
34 */
35 @RunWith(Arquillian.class)
36 @RunAsClient
37 public class ProduceConsumeTest {
38
39 static Client client;
40
41 @BeforeClass
42 public static void setup() {
43 client = ClientBuilder.newClient();
44 }
45
46 @AfterClass
47 public static void cleanup() {
48 client.close();
49 }
50
51 @Deployment
52 public static Archive<?> deploy() {
53 WebArchive war = TestUtil.prepareArchive(ProduceConsumeTest.class.getSimpleName());
54 war.addClass(ProduceConsumeData.class);
55 return TestUtil.finishContainerPrepare(war, null, ProduceConsumeResource.class, ProduceConsumeWildData.class,
56 ProduceConsumeTextData.class);
57 }
58
59 private String generateURL(String path) {
60 return PortProviderUtil.generateURL(path, ProduceConsumeTest.class.getSimpleName());
61 }
62
63 /**
64 * @tpTestDetails Client sends GET request, server return empty successful response. Client parses the response
65 * and tries to read it as BigDecimal.class object.
66 * @tpPassCrit Instance of NoContentException is thrown
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void testEmpty() {
71 Response response = client.target(generateURL("/resource/empty")).request().get();
72 Assert.assertEquals(response.getStatus(), 200);
73 response.getHeaders().add(HttpHeaders.CONTENT_TYPE,
74 MediaType.TEXT_PLAIN_TYPE);
75 try {
76 BigDecimal big = response.readEntity(BigDecimal.class);
77 Assert.fail();
78 } catch (ProcessingException e) {
79 Assert.assertTrue(e.getCause() instanceof NoContentException);
80 }
81
82 }
83
84 /**
85 * @tpTestDetails Client sends GET request, server return empty successful response. Client parses the response
86 * and tries to read it as Character.class object.
87 * @tpPassCrit Instance of NoContentException is thrown
88 * @tpSince RESTEasy 3.0.16
89 */
90 @Test
91 public void testEmptyCharacter() {
92 Response response = client.target(generateURL("/resource/empty")).request().get();
93 Assert.assertEquals(response.getStatus(), 200);
94 response.getHeaders().add(HttpHeaders.CONTENT_TYPE,
95 MediaType.TEXT_PLAIN_TYPE);
96 try {
97 Character big = response.readEntity(Character.class);
98 Assert.fail();
99 } catch (ProcessingException e) {
100 Assert.assertTrue(e.getCause() instanceof NoContentException);
101 }
102
103 }
104
105 /**
106 * @tpTestDetails Client sends GET request, server return empty successful response. Client parses the response
107 * and tries to read it as Integer.class object.
108 * @tpPassCrit Instance of NoContentException is thrown
109 * @tpSince RESTEasy 3.0.16
110 */
111 @Test
112 public void testEmptyInteger() {
113 Response response = client.target(generateURL("/resource/empty")).request().get();
114 Assert.assertEquals(response.getStatus(), 200);
115 response.getHeaders().add(HttpHeaders.CONTENT_TYPE,
116 MediaType.TEXT_PLAIN_TYPE);
117 try {
118 Integer big = response.readEntity(Integer.class);
119 Assert.fail();
120 } catch (ProcessingException e) {
121 Assert.assertTrue(e.getCause() instanceof NoContentException);
122 }
123
124 }
125
126 /**
127 * @tpTestDetails Client sends GET request, server return empty successful response. Client parses the response
128 * and tries to read it as MultivaluedMap.class object.
129 * @tpPassCrit The returned MultivaluedMap object is null
130 * @tpSince RESTEasy 3.0.16
131 */
132 @Test
133 public void testEmptyForm() {
134 Response response = client.target(generateURL("/resource/empty")).request().get();
135 Assert.assertEquals(response.getStatus(), 200);
136 response.getHeaders().add(HttpHeaders.CONTENT_TYPE,
137 MediaType.APPLICATION_FORM_URLENCODED);
138 MultivaluedMap big = response.readEntity(MultivaluedMap.class);
139
140 Assert.assertTrue(big == null || big.size() == 0);
141 }
142
143 /**
144 * @tpTestDetails Client sends POST request with entity of mediatype WILDCARD. The application has two providers to
145 * write and read Data object. One for mediatype text/plain and one wildcard provider. The server choses one provider
146 * and sends response back to the client
147 * @tpPassCrit The text/plain provider is chosen by the server, because if the request has wildcard mediatype,
148 * the most specific provider has to be chosen.
149 * @tpSince RESTEasy 3.0.16
150 */
151 @Test
152 public void testWild() {
153 client.register(ProduceConsumeTextData.class);
154 client.register(ProduceConsumeWildData.class);
155 Response response = client.target(generateURL("/resource/wild")).request("*/*")
156 .post(Entity.entity("data", MediaType.WILDCARD_TYPE));
157 Assert.assertEquals(response.getStatus(), 200);
158 ProduceConsumeData data = response.readEntity(ProduceConsumeData.class);
159 Assert.assertEquals("Data{data='data:text:text', type='text'}", data.toString());
160 response.close();
161 }
162
163 }
+0
-197
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/RangeTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.test.response.resource.RangeResource;
8 import org.jboss.resteasy.util.HttpResponseCodes;
9 import org.jboss.resteasy.utils.PortProviderUtil;
10 import org.jboss.resteasy.utils.TestUtil;
11 import org.jboss.shrinkwrap.api.Archive;
12 import org.jboss.shrinkwrap.api.spec.WebArchive;
13 import org.junit.AfterClass;
14 import org.junit.BeforeClass;
15 import org.junit.Test;
16 import org.junit.Assert;
17 import org.junit.runner.RunWith;
18
19 import javax.ws.rs.client.Client;
20 import javax.ws.rs.client.ClientBuilder;
21 import javax.ws.rs.core.GenericType;
22 import javax.ws.rs.core.Response;
23 import java.text.ParseException;
24 import java.text.SimpleDateFormat;
25 import java.util.Date;
26 import java.util.Locale;
27 import java.util.TimeZone;
28
29 /**
30 * @tpSubChapter Resteasy-client
31 * @tpChapter Integration tests
32 * @tpSince RESTEasy 3.0.16
33 */
34 @RunWith(Arquillian.class)
35 @RunAsClient
36 public class RangeTest {
37
38 protected final Logger logger = LogManager.getLogger(VariantsTest.class.getName());
39
40 static Client client;
41
42 @BeforeClass
43 public static void setup() {
44 client = ClientBuilder.newClient();
45 }
46
47 @Deployment
48 public static Archive<?> deploy() {
49 WebArchive war = TestUtil.prepareArchive(RangeTest.class.getSimpleName());
50 return TestUtil.finishContainerPrepare(war, null, RangeResource.class);
51 }
52
53 @AfterClass
54 public static void close() {
55 Response response = client.target(generateURL("/deletefile")).request().get();
56 response.close();
57 response = client.target(generateURL("/deletesmallfile")).request().get();
58 response.close();
59 client.close();
60 client = null;
61 }
62
63 private static String generateURL(String path) {
64 return PortProviderUtil.generateURL(path, RangeTest.class.getSimpleName());
65 }
66
67 /**
68 * @tpTestDetails Verify that required date object can be created and parsed to string
69 * @tpPassCrit Date object is created
70 * @tpSince RESTEasy 3.0.16
71 */
72 @Test
73 public void testDate() {
74 SimpleDateFormat dateFormatRFC822 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
75 dateFormatRFC822.setTimeZone(TimeZone.getTimeZone("GMT"));
76 String format = dateFormatRFC822.format(new Date());
77 logger.info(format);
78 try {
79 Date date = dateFormatRFC822.parse(format);
80 logger.info(date.toString());
81 } catch (ParseException e) {
82 throw new RuntimeException(e);
83 }
84 }
85
86
87 /**
88 * @tpTestDetails Client sends GET request for a file with request header set to Range 0-3
89 * @tpPassCrit The returned response code is 206 (Partial Content), the length of the response is 4, the response
90 * contains string "hell" and the response contains "Content-Range" header as written in HTTP 1.1 specification.
91 * @tpSince RESTEasy 3.0.16
92 */
93 @Test
94 public void testRange0to3() {
95 Response response = client.target(generateURL("/file")).request()
96 .header("Range", "bytes=0-3").get();
97 Assert.assertEquals(HttpResponseCodes.SC_PARTIAL_CONTENT, response.getStatus());
98 Assert.assertEquals("The response doesn't contain the expected length of the answer", 4, response.getLength());
99 logger.info("Content-Range: " + response.getHeaderString("Content-Range"));
100 Assert.assertEquals("The response doesn't contain the expected substring", response.readEntity(String.class)
101 , "hell");
102 response.close();
103 }
104
105 /**
106 * @tpTestDetails Client sends GET request for a file with request header set to Range 1-4
107 * @tpPassCrit The returned response code is 206 (Partial Content), the length of the response is 4, the response
108 * contains string "ello" and the response contains "Content-Range" header as written in HTTP 1.1 specification.
109 * @tpSince RESTEasy 3.0.16
110 */
111 @Test
112 public void testRange1to4() {
113 Response response = client.target(generateURL("/file")).request()
114 .header("Range", "bytes=1-4").get();
115 Assert.assertEquals(HttpResponseCodes.SC_PARTIAL_CONTENT, response.getStatus());
116 Assert.assertEquals("The response doesn't contain the expected length of the answer", 4, response.getLength());
117 logger.info("Content-Range: " + response.getHeaderString("Content-Range"));
118 Assert.assertEquals("The response doesn't contain the expected substring", response.readEntity(String.class)
119 , "ello");
120 response.close();
121 }
122
123 /**
124 * @tpTestDetails Client sends GET request for a file with request header set to Range 0-3000
125 * @tpPassCrit The returned response code is 206 (Partial Content), the length of the response is 3001
126 * and the response contains "Content-Range" header as written in HTTP 1.1 specification.
127 * @tpSince RESTEasy 3.0.16
128 */
129 @Test
130 public void testRange0to3000() {
131 Response response = client.target(generateURL("/file")).request()
132 .header("Range", "bytes=0-3000").get();
133 Assert.assertEquals(HttpResponseCodes.SC_PARTIAL_CONTENT, response.getStatus());
134 Assert.assertEquals("The response doesn't contain the expected length of the answer", 3001, response.getLength());
135 logger.info("Content-Range: " + response.getHeaderString("Content-Range"));
136 byte[] bytes = response.readEntity(new GenericType<byte[]>() {
137 });
138 Assert.assertEquals("The response doesn't contain the expected length of entity", 3001, bytes.length);
139 response.close();
140 }
141
142 /**
143 * @tpTestDetails Client sends GET request for a file with request header set to Range -4
144 * @tpPassCrit The returned response code is 206 (Partial Content), the length of the response is 4,
145 * the response contains the last "1234" (the last 4 bytes from the file) and the response contains
146 * "Content-Range" header as written in HTTP 1.1 specification.
147 * @tpSince RESTEasy 3.0.16
148 */
149 @Test
150 public void testNegativeRange4() {
151 Response response = client.target(generateURL("/file")).request()
152 .header("Range", "bytes=-4").get();
153 Assert.assertEquals(HttpResponseCodes.SC_PARTIAL_CONTENT, response.getStatus());
154 Assert.assertEquals("The response doesn't contain the expected length of the answer", 4, response.getLength());
155 logger.info("Content-Range: " + response.getHeaderString("Content-Range"));
156 Assert.assertEquals("The response doesn't contain the expected substring", response.readEntity(String.class)
157 , "1234");
158 response.close();
159 }
160
161 /**
162 * @tpTestDetails Client sends GET request for a file with request header set to Range -6000, which is higher than
163 * the size of the file
164 * @tpPassCrit The returned response code is 200 (Success) as server should return whole content of the file this
165 * time.
166 * @tpSince RESTEasy 3.0.16
167 */
168 @Test
169 public void testNegativeRange6000OutOfSize() {
170 Response response = client.target(generateURL("/file")).request()
171 .header("Range", "bytes=-6000").get();
172 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
173 response.close();
174 }
175
176 /**
177 * @tpTestDetails Client sends GET request for a file with request header set to Range full size of the file.
178 * @tpPassCrit The returned response code is 206 (Partial Content), the length of the response is 9,
179 * the response contains the last "123456789" and the response contains "Content-Range" header
180 * as written in HTTP 1.1 specification.
181 * @tpInfo RESTEASY-1094
182 * @tpSince RESTEasy 3.0.16
183 */
184 @Test
185 public void testFullRange() {
186 Response response = client.target(generateURL("/smallfile")).request()
187 .header("Range", "bytes=0-8").get();
188 Assert.assertEquals(HttpResponseCodes.SC_PARTIAL_CONTENT, response.getStatus());
189 Assert.assertEquals("The response doesn't contain the expected length of the answer", 9, response.getLength());
190 logger.info("Content-Range: " + response.getHeaderString("Content-Range"));
191 Assert.assertEquals("The response doesn't contain the expected substring", response.readEntity(String.class)
192 , "123456789");
193 response.close();
194 }
195
196 }
+0
-224
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/ResponseTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.test.response.resource.ResponseAnnotatedClass;
8 import org.jboss.resteasy.test.response.resource.ResponseDateReaderWriter;
9 import org.jboss.resteasy.test.response.resource.ResponseResource;
10 import org.jboss.resteasy.util.HttpResponseCodes;
11 import org.jboss.resteasy.utils.PortProviderUtil;
12 import org.jboss.resteasy.utils.TestUtil;
13 import org.jboss.shrinkwrap.api.Archive;
14 import org.jboss.shrinkwrap.api.spec.WebArchive;
15 import org.junit.AfterClass;
16 import org.junit.BeforeClass;
17 import org.junit.Test;
18 import org.junit.Assert;
19 import org.junit.Rule;
20 import org.junit.rules.ExpectedException;
21 import org.junit.runner.RunWith;
22
23 import javax.ws.rs.ProcessingException;
24 import javax.ws.rs.client.Client;
25 import javax.ws.rs.client.ClientBuilder;
26 import javax.ws.rs.client.Entity;
27 import javax.ws.rs.core.GenericType;
28 import javax.ws.rs.core.Response;
29 import java.io.BufferedReader;
30 import java.io.IOException;
31 import java.io.Reader;
32 import java.lang.annotation.Annotation;
33 import java.util.Calendar;
34 import java.util.Date;
35 import java.util.concurrent.atomic.AtomicInteger;
36
37 /**
38 * @tpSubChapter Resteasy-client
39 * @tpChapter Integration tests
40 * @tpSince RESTEasy 3.0.16
41 */
42 @RunWith(Arquillian.class)
43 @RunAsClient
44 public class ResponseTest {
45
46 protected static final Logger logger = LogManager.getLogger(VariantsTest.class.getName());
47
48 @Rule
49 public ExpectedException thrown = ExpectedException.none();
50
51
52 static Client client;
53
54 @BeforeClass
55 public static void setup() throws Exception {
56 client = ClientBuilder.newClient();
57 }
58
59 @Deployment
60 public static Archive<?> deploy() {
61 WebArchive war = TestUtil.prepareArchive(ResponseTest.class.getSimpleName());
62 return TestUtil.finishContainerPrepare(war, null, ResponseResource.class);
63 }
64
65 @AfterClass
66 public static void cleanup() throws Exception {
67 client.close();
68 }
69
70 private String generateURL(String path) {
71 return PortProviderUtil.generateURL(path, ResponseTest.class.getSimpleName());
72 }
73
74 /**
75 * @tpTestDetails Client sends HEAD request. The resource returns response with entity but the resulting response
76 * must not contain entity as per HEAD method HTTP1.1 spec.
77 * @tpPassCrit Response doesn't contain entity
78 * @tpSince RESTEasy 3.0.16
79 */
80 @Test
81 public void testHead() {
82 Response response = client.target(generateURL("/head")).request().head();
83 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
84 thrown.expect(ProcessingException.class);
85 response.readEntity(String.class);
86 response.close();
87 }
88
89 /**
90 * @tpTestDetails Client sends HEAD request. The resource returns empty response.
91 * @tpPassCrit The resulting response must not contain entity as per HEAD method HTTP1.1 spec.
92 * @tpSince RESTEasy 3.0.16
93 */
94 @Test
95 public void testEmpty() {
96 Response response = client.target(generateURL("/empty")).request().head();
97 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
98 Assert.assertFalse(response.hasEntity());
99 response.close();
100 }
101
102 /**
103 * @tpTestDetails Client sends GET request. The resource creates response from RuntimeDelegate ResponseBuilder.
104 * @tpPassCrit The response code status is changed to 200 (SUCCESS) and response contains the correct entity
105 * @tpSince RESTEasy 3.0.16
106 */
107 @Test
108 public void testNoStatus() {
109 Response response = client.target(generateURL("/entitybodyresponsetest")).request().get();
110 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
111 Assert.assertEquals("", "hello", response.readEntity(String.class));
112 response.close();
113 }
114
115 /**
116 * @tpTestDetails Client sends GET request. The resource creates response from RuntimeDelegate ResponseBuilder with
117 * empty entity.
118 * @tpPassCrit The response code status is 204 (NO CONTENT)
119 * @tpSince RESTEasy 3.0.16
120 */
121 @Test
122 public void testNullEntityNoStatus() {
123 Response response = client.target(generateURL("/nullEntityResponse")).request().get();
124 Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
125 response.close();
126 }
127
128
129 /**
130 * @tpTestDetails Client sends POST request, The resource creates link and attaches it to the Response.
131 * @tpPassCrit The response contains the link
132 * @tpSince RESTEasy 3.0.16
133 */
134 @Test
135 public void hasLinkWhenLinkTest() {
136 Response response = client.target(generateURL("/link")).request().post(Entity.text("path"));
137 Assert.assertTrue(response.hasLink("path"));
138 response.close();
139 }
140
141
142 protected String readLine(Reader reader) throws IOException {
143 String line = null;
144 BufferedReader buffered = new BufferedReader(reader);
145 try {
146 line = buffered.readLine();
147 } catch (IOException e) {
148 buffered.close();
149 throw e;
150 }
151 return line;
152 }
153
154 protected <T> GenericType<T> generic(Class<T> clazz) {
155 return new GenericType<T>(clazz);
156 }
157
158 /**
159 * @tpTestDetails Client sends registers DateReaderWriter and sends get request. The resource sends the date back
160 * in the response.
161 * @tpPassCrit The ANNOTATIONS fields are set up correctly in the DateReaderWriter after processing the response and
162 * the correct date is returned
163 * @tpSince RESTEasy 3.0.16
164 */
165 @Test
166 public void readEntityGenericTypeAnnotationTest() {
167 Date date = Calendar.getInstance().getTime();
168 String sDate = String.valueOf(date.getTime());
169 Annotation[] annotations = ResponseAnnotatedClass.class.getAnnotations();
170 int expected = ResponseDateReaderWriter.ANNOTATION_CONSUMES
171 | ResponseDateReaderWriter.ANNOTATION_PROVIDER;
172
173 AtomicInteger ai = new AtomicInteger();
174 ResponseDateReaderWriter drw = new ResponseDateReaderWriter(ai);
175
176 Response response = client.target(generateURL("/date")).register(drw).queryParam("date", sDate).request().get();
177 response.bufferEntity();
178
179 Date entity = response.readEntity(generic(Date.class), annotations);
180 logger.info(entity.toString());
181 Assert.assertTrue("The original date doesn't match to the returned entity", date.equals(entity));
182
183 Assert.assertTrue("The AtomicInteger in the DateReaderWriter doesn't match with the original value",
184 ai.get() == expected);
185
186 String responseDate = response.readEntity(generic(String.class),
187 annotations);
188 Assert.assertTrue("The original string date doesn't match to generic entity extracted from the response",
189 sDate.equals(responseDate));
190
191 Assert.assertTrue("The AtomicInteger in the DateReaderWriter doesn't match with the original value",
192 ai.get() == expected);
193 response.close();
194
195 }
196
197 /**
198 * @tpTestDetails Client sends GET request. The returned Response contains string entity, which is buffered and
199 * read multiple times as generic entity
200 * @tpPassCrit The response code status is changed to 200 (SUCCESS) and the entity can be read with generic Reader
201 * class and can be stored directly as array of bytes
202 * @tpSince RESTEasy 3.0.16
203 */
204 @Test
205 public void readEntityGenericTypeTest() throws Exception {
206 Response response = client.target(generateURL("/entity")).request().get();
207 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
208 response.bufferEntity();
209 String line;
210
211 Reader reader = response.readEntity(new GenericType<Reader>(Reader.class));
212 line = readLine(reader);
213 Assert.assertTrue("The entity extracted with genetic Reader doesn't match the original entity",
214 ResponseResource.ENTITY.equals(line));
215 byte[] buffer = new byte[0];
216 buffer = response.readEntity(generic(buffer.getClass()));
217 Assert.assertNotNull(buffer);
218 line = new String(buffer);
219 Assert.assertTrue("The entity extracted with as array of bytes doesn't match the original entity",
220 ResponseResource.ENTITY.equals(line));
221 response.close();
222 }
223 }
+0
-103
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/VariantAcceptTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import static junit.framework.TestCase.assertEquals;
3
4 import java.util.HashMap;
5 import java.util.Map;
6
7 import javax.ws.rs.client.Invocation;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Response;
10
11 import org.jboss.arquillian.container.test.api.Deployment;
12 import org.jboss.arquillian.container.test.api.RunAsClient;
13 import org.jboss.arquillian.junit.Arquillian;
14 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
15 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
16 import org.jboss.resteasy.test.response.resource.VariantAcceptResource;
17 import org.jboss.resteasy.util.HttpResponseCodes;
18 import org.jboss.resteasy.utils.PortProviderUtil;
19 import org.jboss.resteasy.utils.TestUtil;
20 import org.jboss.shrinkwrap.api.Archive;
21 import org.jboss.shrinkwrap.api.spec.WebArchive;
22 import org.junit.Test;
23 import org.junit.runner.RunWith;
24
25 /**
26 * @tpSubChapter Resteasy-client
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Regression test for RESTEASY-994
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class VariantAcceptTest {
34
35 public static final MediaType WILDCARD_WITH_PARAMS;
36 public static final MediaType TEXT_HTML_WITH_PARAMS;
37 public static final MediaType TEXT_PLAIN_WITH_PARAMS;
38
39 static {
40 Map<String, String> params = new HashMap<String, String>();
41 params.put("q", "0.5");
42 params.put("a", "1");
43 params.put("b", "2");
44 params.put("c", "3");
45 WILDCARD_WITH_PARAMS = new MediaType("*", "*", params);
46
47 params.clear();
48 params.put("a", "1");
49 params.put("b", "2");
50 params.put("c", "3");
51 TEXT_HTML_WITH_PARAMS = new MediaType("text", "html", params);
52
53 params.clear();
54 params.put("a", "1");
55 params.put("b", "2");
56 params.put("c", "3");
57 TEXT_PLAIN_WITH_PARAMS = new MediaType("text", "plain", params);
58 }
59
60 @Deployment
61 public static Archive<?> deploy() {
62 WebArchive war = TestUtil.prepareArchive(VariantAcceptTest.class.getSimpleName());
63 war.addClass(VariantAcceptTest.class);
64 return TestUtil.finishContainerPrepare(war, null, VariantAcceptResource.class);
65 }
66
67 private String generateURL(String path) {
68 return PortProviderUtil.generateURL(path, VariantAcceptTest.class.getSimpleName());
69 }
70
71 /**
72 * @tpTestDetails Verifies that a more specific media type is preferred.
73 * @tpSince RESTEasy 3.0.16
74 */
75 @Test
76 public void testVariant() throws Exception {
77 ResteasyClient client = new ResteasyClientBuilder().build();
78 Invocation.Builder request = client.target(generateURL("/variant")).request();
79 request.accept(MediaType.WILDCARD_TYPE);
80 request.accept(MediaType.TEXT_HTML_TYPE);
81 Response response = request.get();
82 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
83 String entity = response.readEntity(String.class);
84 assertEquals("Wrong media type on response", MediaType.TEXT_HTML, entity);
85 }
86
87 /**
88 * @tpTestDetails Verifies that the number of parameters does not outweigh more specific media types.
89 * @tpSince RESTEasy 3.0.16
90 */
91 @Test
92 public void testVariantWithParameters() throws Exception {
93 ResteasyClient client = new ResteasyClientBuilder().build();
94 Invocation.Builder request = client.target(generateURL("/params")).request();
95 request.accept(WILDCARD_WITH_PARAMS);
96 request.accept(MediaType.TEXT_HTML_TYPE);
97 Response response = request.get();
98 assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
99 String entity = response.readEntity(String.class);
100 assertEquals("Wrong media type on response", TEXT_HTML_WITH_PARAMS.toString(), entity);
101 }
102 }
+0
-381
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/VariantsTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.apache.logging.log4j.LogManager;
3 import org.apache.logging.log4j.Logger;
4 import org.jboss.arquillian.container.test.api.Deployment;
5 import org.jboss.arquillian.container.test.api.RunAsClient;
6 import org.jboss.arquillian.junit.Arquillian;
7 import org.jboss.resteasy.plugins.delegates.LocaleDelegate;
8 import org.jboss.resteasy.test.response.resource.VariantComplexResource;
9 import org.jboss.resteasy.test.response.resource.VariantEncodingResource;
10 import org.jboss.resteasy.test.response.resource.VariantLanguageResource;
11 import org.jboss.resteasy.util.HttpHeaderNames;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.TestUtil;
14 import org.jboss.shrinkwrap.api.Archive;
15 import org.jboss.shrinkwrap.api.spec.WebArchive;
16 import org.junit.After;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.junit.Assert;
20 import org.junit.runner.RunWith;
21
22 import javax.ws.rs.client.Client;
23 import javax.ws.rs.client.ClientBuilder;
24 import javax.ws.rs.core.Response;
25 import javax.ws.rs.core.MediaType;
26 import java.util.List;
27
28 import org.jboss.resteasy.utils.PortProviderUtil;
29
30 /**
31 * @tpSubChapter Response
32 * @tpChapter Integration tests
33 * @tpTestCaseDetails Tests that correct variant headers are returned in the response
34 * @tpSince RESTEasy 3.0.16
35 */
36 @RunWith(Arquillian.class)
37 @RunAsClient
38 public class VariantsTest {
39
40 protected static final Logger logger = LogManager.getLogger(VariantsTest.class.getName());
41
42 static Client client;
43
44 @Deployment
45 public static Archive<?> deploy() {
46 WebArchive war = TestUtil.prepareArchive(VariantsTest.class.getSimpleName());
47 war.addClass(VariantsTest.class);
48 return TestUtil.finishContainerPrepare(war, null, VariantLanguageResource.class, VariantComplexResource.class, VariantEncodingResource.class);
49 }
50
51 @Before
52 public void init() {
53 client = ClientBuilder.newClient();
54 }
55
56 @After
57 public void after() throws Exception {
58 client.close();
59 }
60
61 private String generateURL(String path) {
62 return PortProviderUtil.generateURL(path, VariantsTest.class.getSimpleName());
63 }
64
65 /**
66 * @tpTestDetails Simple http GET conditional request
67 * @tpSince RESTEasy 3.0.16
68 */
69 @Test
70 public void evaluatePreconditionsTagNullAndSimpleGetTest() {
71 client = ClientBuilder.newClient();
72 logger.info(generateURL("/preconditionsSimpleGet"));
73 Response response = client.target(generateURL("/preconditionsSimpleGet")).request()
74 .get();
75 Assert.assertEquals(200, response.getStatus());
76 response.close();
77 client.close();
78 }
79
80 /**
81 * @tpTestDetails PUT request is send, request selects best variant from the list od empty variants,
82 * IllegalArgumentException is thrown
83 * @tpSince RESTEasy 3.0.16
84 */
85 @Test
86 public void selectVariantPutRequestTest() {
87 Response response = client.target(generateURL("/SelectVariantTestPut")).request()
88 .put(null);
89 Assert.assertEquals(200, response.getStatus());
90 Assert.assertEquals("PASSED", response.readEntity(String.class));
91 response.close();
92 }
93
94 /**
95 * @tpTestDetails GET request is send, test that variant is selected and response contains proper headers
96 * @tpSince RESTEasy 3.0.16
97 */
98 @Test
99 public void selectVariantResponseVaryTest() {
100 Response response = client.target(generateURL("/SelectVariantTestResponse")).request()
101 .accept("application/json")
102 .acceptEncoding("*").get();
103 Assert.assertEquals(200, response.getStatus());
104 List<String> headers = response.getStringHeaders().get("Vary");
105 Assert.assertEquals(1, headers.size());
106 String vary = headers.get(0);
107 logger.info(vary);
108 Assert.assertTrue(vary.contains("Accept-Language"));
109 Assert.assertTrue(vary.contains("Accept-Encoding"));
110 Assert.assertTrue(vary.matches(".*Accept.*Accept.*Accept.*"));
111 response.close();
112 }
113
114 /**
115 * @tpTestDetails Tests that variant preferred by client request by Accept-Language is selected
116 * @tpSince RESTEasy 3.0.16
117 */
118 @Test
119 public void testGetLanguageEn() throws Exception {
120 Response response = client.target(generateURL("/")).request().acceptLanguage("en").get();
121 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
122 Assert.assertEquals("en", response.readEntity(String.class));
123 Assert.assertEquals("en", response.getLanguage().toString());
124 response.close();
125 }
126
127 /**
128 * @tpTestDetails Tests that given wildcard client request by Accept-Language header returns some concrete language
129 * header in the response.
130 * @tpSince RESTEasy 3.0.16
131 */
132 @Test
133 public void testGetLanguageWildcard() throws Exception {
134 Response response = client.target(generateURL("/")).request().acceptLanguage("*").get();
135 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
136 Assert.assertNotNull(response.getLanguage());
137 response.close();
138 }
139
140 /**
141 * @tpTestDetails Tests that variant preferred by client request by Accept-Language is selected. Variant defined with
142 * Locale("pt", "BR")
143 * @tpSince RESTEasy 3.0.16
144 */
145 @Test
146 public void testGetLanguageSubLocal() throws Exception {
147 Response response = client.target(generateURL("/brazil")).request()
148 .acceptLanguage("pt").get();
149 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
150 Assert.assertNotNull(response.getLanguage());
151 response.close();
152 }
153
154 /**
155 * @tpTestDetails Test that language variant which has 0 preference is not returned
156 * @tpSince RESTEasy 3.0.16
157 */
158 @Test
159 public void testGetLanguageZero() throws Exception {
160 Response response = client.target(generateURL("/")).request()
161 .acceptLanguage("*", "zh;q=0", "en;q=0", "fr;q=0").get();
162 Assert.assertEquals(HttpResponseCodes.SC_NOT_ACCEPTABLE, response.getStatus());
163 response.close();
164 }
165
166 /**
167 * @tpTestDetails Simple Get for with Accept-Language "zh". Lanfuage "zh" in the response is returned
168 * @tpSince RESTEasy 3.0.16
169 */
170 @Test
171 public void testGetLanguageZh() throws Exception {
172 Response response = client.target(generateURL("/")).request().acceptLanguage("zh").get();
173 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
174 Assert.assertEquals("zh", response.readEntity(String.class));
175 Assert.assertEquals("zh", response.getLanguage().toString());
176 response.close();
177 }
178
179 /**
180 * @tpTestDetails Tests client request with multiple Accept-language preferences, check the most preferred language
181 * is returned in the response
182 * @tpSince RESTEasy 3.0.16
183 */
184 @Test
185 public void testGetLanguageMultiple() throws Exception {
186 Response response = client.target(generateURL("/")).request()
187 .acceptLanguage("en;q=0.3", "zh;q=0.4", "fr").get();
188 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
189 Assert.assertEquals("fr", response.readEntity(String.class));
190 Assert.assertEquals("fr", response.getLanguage().toString());
191 response.close();
192 }
193
194 /**
195 * @tpTestDetails Verifies that a more specific media type is preferred.
196 * @tpSince RESTEasy 3.0.16
197 */
198 @Test
199 public void testGetComplexAcceptLanguageEn() throws Exception {
200 Response response = client.target(generateURL("/complex")).request()
201 .accept("text/xml", "application/xml", "application/xhtml+xml", "image/png", "text/html;q=0.9", "text/plain;q=0.8", "*/*;q=0.5")
202 .acceptLanguage("en-us", "en;q=0.5").get();
203 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
204 Assert.assertEquals("GET", response.readEntity(String.class));
205 Assert.assertEquals(MediaType.APPLICATION_XML_TYPE.withCharset("UTF-8"), response.getMediaType());
206 Assert.assertEquals("en-us", new LocaleDelegate().toString(response.getLanguage()));
207 response.close();
208 }
209
210 /**
211 * @tpTestDetails Verifies that a more specific media type is preferred.
212 * @tpSince RESTEasy 3.0.16
213 */
214 @Test
215 public void testGetComplexAcceptLanguageEnUs() throws Exception {
216 Response response = client.target(generateURL("/complex")).request()
217 .accept("text/xml", "application/xml", "application/xhtml+xml", "image/png", "text/html;q=0.9", "text/plain;q=0.8", "*/*;q=0.5")
218 .acceptLanguage("en", "en-us").get();
219 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
220 Assert.assertEquals("GET", response.readEntity(String.class));
221 Assert.assertEquals(MediaType.APPLICATION_XML_TYPE.withCharset("UTF-8"), response.getMediaType());
222 Assert.assertEquals("en-us", new LocaleDelegate().toString(response.getLanguage()));
223 response.close();
224 }
225
226 /**
227 * @tpTestDetails Test that expected variants are selected from list of multiple weighted content and language type.
228 * @tpSince RESTEasy 3.0.16
229 */
230 @Test
231 public void testGetComplexShuffleAcceptMedia() throws Exception {
232 Response response = client.target(generateURL("/complex")).request()
233 .accept("application/xml", "text/xml", "application/xhtml+xml", "image/png", "text/html;q=0.9", "text/plain;q=0.8", "*/*;q=0.5")
234 .acceptLanguage("en-us", "en;q=0.5").get();
235 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
236 Assert.assertEquals("GET", response.readEntity(String.class));
237 Assert.assertEquals(MediaType.APPLICATION_XML_TYPE.withCharset("UTF-8"), response.getMediaType());
238 Assert.assertEquals("en-us", new LocaleDelegate().toString(response.getLanguage()));
239 response.close();
240 }
241
242 /**
243 * @tpTestDetails Test that expected variants are selected from list of multiple weighted content and language type.
244 * en-us with preference
245 * @tpSince RESTEasy 3.0.16
246 */
247 @Test
248 public void testGetComplexAcceptLanguageEnUsWithPreference() throws Exception {
249 Response response = client.target(generateURL("/complex")).request()
250 .accept("application/xml", "text/xml", "application/xhtml+xml", "image/png", "text/html;q=0.9", "text/plain;q=0.8", "*/*;q=0.5")
251 .acceptLanguage("en", "en-us;q=0.5").get();
252 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
253 Assert.assertEquals("GET", response.readEntity(String.class));
254 Assert.assertEquals("en", response.getLanguage().toString());
255 Assert.assertEquals(MediaType.TEXT_XML_TYPE.withCharset("UTF-8"), response.getMediaType());
256 response.close();
257 }
258
259 /**
260 * @tpTestDetails Tests client request which has accept header which cannot be served by server.
261 * @tpSince RESTEasy 3.0.16
262 */
263 @Test
264 public void testGetComplexNotAcceptable() throws Exception {
265 {
266 Response response = client.target(generateURL("/complex")).request()
267 .accept("application/atom+xml")
268 .acceptLanguage("en-us", "en").get();
269 Assert.assertEquals(406, response.getStatus());
270
271 String vary = response.getHeaderString(HttpHeaderNames.VARY);
272 Assert.assertNotNull(vary);
273 logger.info("vary: " + vary);
274 Assert.assertTrue(contains(vary, "Accept"));
275 Assert.assertTrue(contains(vary, "Accept-Language"));
276 response.close();
277 }
278
279 {
280 Response response = client.target(generateURL("/complex")).request()
281 .accept("application/xml")
282 .acceptLanguage("fr").get();
283 Assert.assertEquals(406, response.getStatus());
284
285 String vary = response.getHeaderString(HttpHeaderNames.VARY);
286 Assert.assertNotNull(vary);
287 logger.info("vary: " + vary);
288 Assert.assertTrue(contains(vary, "Accept"));
289 Assert.assertTrue(contains(vary, "Accept-Language"));
290 response.close();
291 }
292 }
293
294 /**
295 * @tpTestDetails Tests client request with custom Accept-encoding
296 * @tpSince RESTEasy 3.0.16
297 */
298 @Test
299 public void testGetEncodingCustomEnc1() throws Exception {
300 Response response = client.target(generateURL("/encoding")).request()
301 .acceptEncoding("enc1").get();
302 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
303
304 Assert.assertEquals("enc1", response.readEntity(String.class));
305 Assert.assertEquals("enc1", response.getHeaderString(HttpHeaderNames.CONTENT_ENCODING));
306 response.close();
307 }
308
309 /**
310 * @tpTestDetails Tests client request with custom Accept-encoding
311 * @tpSince RESTEasy 3.0.16
312 */
313 @Test
314 public void testGetEncodingCustomEnc2() throws Exception {
315 Response response = client.target(generateURL("/encoding")).request()
316 .acceptEncoding("enc2").get();
317 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
318
319 Assert.assertEquals("enc2", response.readEntity(String.class));
320 Assert.assertEquals("enc2", response.getHeaderString(HttpHeaderNames.CONTENT_ENCODING));
321 response.close();
322 }
323
324 /**
325 * @tpTestDetails Tests client request with custom Accept-encoding
326 * @tpSince RESTEasy 3.0.16
327 */
328 @Test
329 public void testGetEncodingCustomEnc3() throws Exception {
330 Response response = client.target(generateURL("/encoding")).request()
331 .acceptEncoding("enc3").get();
332 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
333
334 Assert.assertEquals("enc3", response.readEntity(String.class));
335 Assert.assertEquals("enc3", response.getHeaderString(HttpHeaderNames.CONTENT_ENCODING));
336 response.close();
337 }
338
339 /**
340 * @tpTestDetails Tests client request with custom Accept-encoding with preference specified
341 * @tpSince RESTEasy 3.0.16
342 */
343 @Test
344 public void testGetEncodingCustomPreference() throws Exception {
345 Response response = client.target(generateURL("/encoding")).request()
346 .acceptEncoding("enc1;q=0.5", "enc2;q=0.9").get();
347 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
348
349 Assert.assertEquals("enc2", response.readEntity(String.class));
350 Assert.assertEquals("enc2", response.getHeaderString(HttpHeaderNames.CONTENT_ENCODING));
351 response.close();
352 }
353
354 /**
355 * @tpTestDetails Tests client request with custom Accept-encoding with preference specified
356 * @tpSince RESTEasy 3.0.16
357 */
358 @Test
359 public void testGetEncodingCustomPreferenceZero() throws Exception {
360 Response response = client.target(generateURL("/encoding")).request()
361 .acceptEncoding("enc1;q=0", "enc2;q=0.888", "enc3;q=0.889").get();
362 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
363
364 Assert.assertEquals("enc3", response.readEntity(String.class));
365 Assert.assertEquals("enc3", response.getHeaderString(HttpHeaderNames.CONTENT_ENCODING));
366 response.close();
367 }
368
369 private boolean contains(String all, String one) {
370 String[] allSplit = all.split(",");
371 for (String s : allSplit) {
372 s = s.trim();
373 if (s.equalsIgnoreCase(one)) {
374 return true;
375 }
376 }
377
378 return false;
379 }
380 }
+0
-69
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/WriterMatchingTest.java less more
0 package org.jboss.resteasy.test.response;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.test.response.resource.WriterMatchingBoolWriter;
6 import org.jboss.resteasy.test.response.resource.WriterMatchingResource;
7 import org.jboss.resteasy.util.HttpResponseCodes;
8 import org.jboss.resteasy.utils.PortProviderUtil;
9 import org.jboss.resteasy.utils.TestUtil;
10 import org.jboss.shrinkwrap.api.Archive;
11 import org.jboss.shrinkwrap.api.spec.WebArchive;
12 import org.junit.After;
13 import org.junit.Assert;
14 import org.junit.Before;
15 import org.junit.Test;
16 import org.junit.runner.RunWith;
17
18 import javax.ws.rs.client.Client;
19 import javax.ws.rs.client.ClientBuilder;
20 import javax.ws.rs.core.Response;
21
22 /**
23 * @tpSubChapter Writers
24 * @tpChapter Integration tests
25 * @tpSince RESTEasy 3.0.16
26 */
27 @RunWith(Arquillian.class)
28 @RunAsClient
29 public class WriterMatchingTest {
30
31 static Client client;
32
33
34 private String generateURL(String path) {
35 return PortProviderUtil.generateURL(path, WriterMatchingTest.class.getSimpleName());
36 }
37
38 @Deployment
39 public static Archive<?> deploy() {
40 WebArchive war = TestUtil.prepareArchive(WriterMatchingTest.class.getSimpleName());
41 return TestUtil.finishContainerPrepare(war, null, WriterMatchingResource.class, WriterMatchingBoolWriter.class);
42 }
43
44 @Before
45 public void setup() {
46 client = ClientBuilder.newClient();
47 }
48
49 @After
50 public void cleanup() {
51 client.close();
52 }
53
54 /**
55 * @tpTestDetails Check correct sort of writers. RESTEasy should check correct writer.
56 * @tpSince RESTEasy 3.0.16
57 */
58 @Test
59 public void testMatch() {
60 // writers sorted by type, mediatype, and then by app over builtin
61 Response response = client.target(generateURL("/bool")).request("text/plain").get();
62 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
63 String data = response.readEntity(String.class);
64 response.close();
65 Assert.assertEquals("RESTEasy returns wrong data", data, "true");
66 }
67
68 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/CookieResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Response;
6
7 @Path("cookie")
8 public class CookieResource {
9 @GET
10 @Path("weird")
11 @Produces("text/plain")
12 public Response responseOkWeird() {
13 return Response.ok("ok")
14 .header("Set-Cookie",
15 "guid=1.9112608617070927872;Path=/;Domain=localhost;Expires=Thu, 03-May-2028 10:36:34 GMT;Max-Age=150000000")
16 .build();
17 }
18
19 @GET
20 @Path("standard")
21 @Produces("text/plain")
22 public Response responseOkStandard() {
23 return Response.ok("ok")
24 .header("Set-Cookie", "UserID=JohnDoe; Max-Age=3600; Version=1")
25 .build();
26 }
27
28 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/DuplicitePathDupliciteApplicationOne.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4 import java.util.HashSet;
5 import java.util.Set;
6
7 @ApplicationPath("a")
8 public class DuplicitePathDupliciteApplicationOne extends Application {
9 @Override
10 public Set<Class<?>> getClasses() {
11 HashSet<Class<?>> set = new HashSet<Class<?>>();
12 set.add(DuplicitePathDupliciteResourceOne.class);
13 return set;
14 }
15 }
+0
-16
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/DuplicitePathDupliciteApplicationTwo.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4 import java.util.HashSet;
5 import java.util.Set;
6
7 @ApplicationPath("a")
8 public class DuplicitePathDupliciteApplicationTwo extends Application {
9 @Override
10 public Set<Class<?>> getClasses() {
11 HashSet<Class<?>> set = new HashSet<Class<?>>();
12 set.add(DuplicitePathDupliciteResourceTwo.class);
13 return set;
14 }
15 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/DuplicitePathDupliciteResourceOne.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.MediaType;
6
7 @Path("/b")
8 public class DuplicitePathDupliciteResourceOne {
9 public static final String DUPLICITE_RESPONSE = "response4";
10
11 @Path("/c")
12 @GET
13 @Produces(MediaType.TEXT_PLAIN)
14 public String duplicite() {
15 return DUPLICITE_RESPONSE;
16 }
17 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/DuplicitePathDupliciteResourceTwo.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.MediaType;
6
7 @Path("/b")
8 public class DuplicitePathDupliciteResourceTwo {
9 public static final String DUPLICITE_RESPONSE = "response5";
10
11 @Path("/c")
12 @GET
13 @Produces(MediaType.TEXT_PLAIN)
14 public String dupliciteOne() {
15 return DUPLICITE_RESPONSE;
16 }
17 }
+0
-44
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/DuplicitePathMethodResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5
6 @Path("/g")
7 public class DuplicitePathMethodResource {
8 public static final String DUPLICITE_RESPONSE_1 = "response1";
9 public static final String DUPLICITE_RESPONSE_2 = "response2";
10 public static final String NO_DUPLICITE_RESPONSE = "response3";
11 public static final String DUPLICITE_TYPE_GET = "response7";
12 public static final String DUPLICITE_TYPE_POST = "response8";
13
14 @Path("/h")
15 @GET
16 public String dupliciteOne() {
17 return DUPLICITE_RESPONSE_1;
18 }
19
20 @Path("/h")
21 @GET
22 public String dupliciteTwo() {
23 return DUPLICITE_RESPONSE_2;
24 }
25
26 @Path("/i")
27 @GET
28 public String noDuplicite() {
29 return NO_DUPLICITE_RESPONSE;
30 }
31
32 @Path("/j")
33 @POST
34 public String dupliciteDifferentTypePost() {
35 return DUPLICITE_TYPE_POST;
36 }
37
38 @Path("/j")
39 @GET
40 public String dupliciteDifferentTypeGet() {
41 return DUPLICITE_TYPE_GET;
42 }
43 }
+0
-18
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/DuplicitePathNoDupliciteApplication.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.ApplicationPath;
3 import javax.ws.rs.core.Application;
4 import java.util.HashSet;
5 import java.util.Set;
6
7 @ApplicationPath("/f")
8 public class DuplicitePathNoDupliciteApplication extends Application {
9 @Override
10 public Set<Class<?>> getClasses() {
11 HashSet<Class<?>> set = new HashSet<Class<?>>();
12 set.add(DuplicitePathMethodResource.class);
13 set.add(DuplicitePathDupliciteResourceOne.class);
14 set.add(DuplicitePathDupliciteResourceTwo.class);
15 return set;
16 }
17 }
+0
-12
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/HttpRequestParameterInjectorClassicParam.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import java.lang.annotation.ElementType;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.annotation.Target;
6
7 @Target(ElementType.PARAMETER)
8 @Retention(RetentionPolicy.RUNTIME)
9 public @interface HttpRequestParameterInjectorClassicParam {
10 String value();
11 }
+0
-59
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/HttpRequestParameterInjectorParamFactoryImpl.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import org.jboss.resteasy.core.InjectorFactoryImpl;
3 import org.jboss.resteasy.core.ValueInjector;
4 import org.jboss.resteasy.spi.HttpRequest;
5 import org.jboss.resteasy.spi.HttpResponse;
6 import org.jboss.resteasy.spi.ResteasyProviderFactory;
7 import org.jboss.resteasy.spi.metadata.Parameter;
8 import org.jboss.resteasy.util.FindAnnotation;
9
10 import javax.servlet.http.HttpServletRequest;
11 import java.lang.annotation.Annotation;
12 import java.lang.reflect.AccessibleObject;
13 import java.lang.reflect.Type;
14
15 public class HttpRequestParameterInjectorParamFactoryImpl extends InjectorFactoryImpl {
16 @SuppressWarnings("unchecked")
17 @Override
18 public ValueInjector createParameterExtractor(Class injectTargetClass,
19 AccessibleObject injectTarget, Class type, Type genericType, Annotation[] annotations, ResteasyProviderFactory factory) {
20 final HttpRequestParameterInjectorClassicParam param = FindAnnotation.findAnnotation(annotations, HttpRequestParameterInjectorClassicParam.class);
21 if (param == null) {
22 return super.createParameterExtractor(injectTargetClass, injectTarget, type,
23 genericType, annotations, factory);
24 } else {
25 return new ValueInjector() {
26 public Object inject(HttpRequest request, HttpResponse response) {
27 return ResteasyProviderFactory.getContextData(HttpServletRequest.class)
28 .getParameter(param.value());
29 }
30
31 public Object inject() {
32 // do nothing.
33 return null;
34 }
35 };
36 }
37 }
38
39 @Override
40 public ValueInjector createParameterExtractor(Parameter parameter, ResteasyProviderFactory providerFactory) {
41 final HttpRequestParameterInjectorClassicParam param = FindAnnotation.findAnnotation(parameter.getAnnotations(), HttpRequestParameterInjectorClassicParam.class);
42 if (param == null) {
43 return super.createParameterExtractor(parameter, providerFactory);
44 } else {
45 return new ValueInjector() {
46 public Object inject(HttpRequest request, HttpResponse response) {
47 return ResteasyProviderFactory.getContextData(HttpServletRequest.class)
48 .getParameter(param.value());
49 }
50
51 public Object inject() {
52 // do nothing.
53 return null;
54 }
55 };
56 }
57 }
58 }
+0
-21
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/HttpRequestParameterInjectorResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.DefaultValue;
3 import javax.ws.rs.FormParam;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.Path;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9
10 @Path("/foo")
11 public class HttpRequestParameterInjectorResource {
12 @GET
13 @POST
14 @Produces("text/plain")
15 public String get(@HttpRequestParameterInjectorClassicParam("param") String param,
16 @QueryParam("param") @DefaultValue("") String query,
17 @FormParam("param") @DefaultValue("") String form) {
18 return String.format("%s, %s, %s", param, query, form);
19 }
20 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/InheritedContextNewService.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5
6 @Path("sub")
7 public class InheritedContextNewService extends InheritedContextService {
8 @Path("test/{level}")
9 @GET
10 public String test(@PathParam("level") String level) {
11 return Boolean.toString(level.equals("SomeService") && testContexts());
12 }
13 }
+0
-14
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/InheritedContextNewSubService.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5
6 @Path("subsub")
7 public class InheritedContextNewSubService extends InheritedContextNewService {
8 @Path("test/{level}")
9 @GET
10 public String test(@PathParam("level") String level) {
11 return Boolean.toString(level.equals("SomeSubService") && testContexts());
12 }
13 }
+0
-54
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/InheritedContextService.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.PathParam;
5 import javax.ws.rs.container.ResourceContext;
6 import javax.ws.rs.core.Configuration;
7 import javax.ws.rs.core.Context;
8 import javax.ws.rs.core.HttpHeaders;
9 import javax.ws.rs.core.Request;
10 import javax.ws.rs.core.SecurityContext;
11 import javax.ws.rs.core.UriInfo;
12 import javax.ws.rs.ext.Providers;
13
14
15 @Path("super")
16 public class InheritedContextService {
17 @Context
18 protected UriInfo uriInfo;
19
20 @Context
21 protected HttpHeaders httpHeaders;
22
23 @Context
24 protected Request request;
25
26 @Context
27 protected SecurityContext securityContext;
28
29 @Context
30 protected Providers providers;
31
32 @Context
33 protected ResourceContext resourceContext;
34
35 @Context
36 protected Configuration configuration;
37
38 @Path("test/{level}")
39 @GET
40 public String test(@PathParam("level") String level) {
41 return Boolean.toString(level.equals("BaseService") && testContexts());
42 }
43
44 protected boolean testContexts() {
45 return uriInfo != null
46 && httpHeaders != null
47 && request != null
48 && securityContext != null
49 && providers != null
50 && resourceContext != null
51 && configuration != null;
52 }
53 }
+0
-43
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/MethodDefaultResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import javax.ws.rs.core.Response;
6
7 @Path(value = "/GetTest")
8 public class MethodDefaultResource {
9
10 static String html_content =
11 "<html>" + "<head><title>CTS-get text/html</title></head>" +
12 "<body>CTS-get text/html</body></html>";
13
14 @GET
15 public Response getPlain() {
16 return Response.ok("CTS-get text/plain").header("CTS-HEAD", "text-plain").
17 build();
18 }
19
20 @GET
21 @Produces(value = "text/html")
22 public Response getHtml() {
23 return Response.ok(html_content).header("CTS-HEAD", "text-html").
24 build();
25 }
26
27 @GET
28 @Path(value = "/sub")
29 public Response getSub() {
30 return Response.ok("CTS-get text/plain").header("CTS-HEAD",
31 "sub-text-plain").
32 build();
33 }
34
35 @GET
36 @Path(value = "/sub")
37 @Produces(value = "text/html")
38 public Response headSub() {
39 return Response.ok(html_content).header("CTS-HEAD", "sub-text-html").
40 build();
41 }
42 }
+0
-22
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/OptionParamsResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5
6 @Path("params")
7 public class OptionParamsResource {
8 @Path("/customers/{custid}/phonenumbers")
9 @GET
10 @Produces("text/plain")
11 public String getPhoneNumbers() {
12 return "912-111-1111";
13 }
14
15 @Path("/customers/{custid}/phonenumbers/{id}")
16 @GET
17 @Produces("text/plain")
18 public String getPhoneIds() {
19 return "1111";
20 }
21 }
+0
-82
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/OptionUsersResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.DELETE;
4 import javax.ws.rs.GET;
5 import javax.ws.rs.POST;
6 import javax.ws.rs.PUT;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.PathParam;
9 import javax.ws.rs.Produces;
10
11 @Path("/users")
12 public class OptionUsersResource {
13 @GET
14 @Produces("text/plain")
15 public String get() {
16 return "users";
17 }
18
19 @POST
20 @Consumes("text/plain")
21 public void post(String users) {
22
23 }
24
25 @GET
26 @Path("{user-id}")
27 @Produces("text/plain")
28 public String getUserId(@PathParam("user-id") String userId) {
29 return userId;
30 }
31
32 @DELETE
33 @Path("{user-id}")
34 @Produces("text/plain")
35 public String deleteUserId(@PathParam("user-id") String userId) {
36 return userId;
37 }
38
39 @PUT
40 @Path("{user-id}")
41 @Consumes("text/plain")
42 public void postUserId(@PathParam("user-id") String userId, String user) {
43
44 }
45
46 @GET
47 @Path("{user-id}/contacts")
48 @Produces("text/plain")
49 public String getContacts(@PathParam("user-id") String userId) {
50 return userId;
51 }
52
53 @POST
54 @Path("{user-id}/contacts")
55 @Consumes("text/plain")
56 public void postContacts(@PathParam("user-id") String userId, String user) {
57
58 }
59
60 @GET
61 @Path("{user-id}/contacts/{contact-id}")
62 @Produces("text/plain")
63 public String getContactId(@PathParam("user-id") String userId) {
64 return userId;
65 }
66
67 @DELETE
68 @Path("{user-id}/contacts/{contact-id}")
69 @Produces("text/plain")
70 public String deleteCotactId(@PathParam("user-id") String userId) {
71 return userId;
72 }
73
74 @PUT
75 @Path("{user-id}/contacts/{contact-id}")
76 @Consumes("text/plain")
77 public void postContactId(@PathParam("user-id") String userId, String user) {
78
79 }
80
81 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/ProduceConsumeData.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 public class ProduceConsumeData {
3 public final String data;
4 public final String type;
5
6 public ProduceConsumeData(final String data, final String type) {
7 this.data = data;
8 this.type = type;
9 }
10
11 @Override
12 public String toString() {
13 return "Data{" +
14 "data='" + data + '\'' +
15 ", type='" + type + '\'' +
16 '}';
17 }
18 }
+0
-33
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/ProduceConsumeResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.POST;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.Response;
8
9 @Path("resource")
10 public class ProduceConsumeResource {
11
12 @POST
13 @Path("plain")
14 @Produces(MediaType.TEXT_PLAIN)
15 public String postPlain() {
16 return MediaType.TEXT_PLAIN;
17 }
18
19 @POST
20 @Path("wild")
21 public ProduceConsumeData data(ProduceConsumeData data) {
22 return data;
23 }
24
25 @Path("empty")
26 @GET
27 public Response entity() {
28 return Response.ok().build();
29 }
30
31
32 }
+0
-47
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/ProduceConsumeTextData.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import org.jboss.resteasy.plugins.providers.ProviderHelper;
3
4 import javax.ws.rs.Consumes;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.WebApplicationException;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyReader;
10 import javax.ws.rs.ext.MessageBodyWriter;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.OutputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16
17 @Produces("text/plain")
18 @Consumes("text/plain")
19 public class ProduceConsumeTextData implements MessageBodyReader<ProduceConsumeData>, MessageBodyWriter<ProduceConsumeData> {
20 @Override
21 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
22 return type.equals(ProduceConsumeData.class);
23 }
24
25 @Override
26 public ProduceConsumeData readFrom(Class<ProduceConsumeData> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
27 String str = ProviderHelper.readString(entityStream, mediaType);
28 return new ProduceConsumeData(str, "text");
29 }
30
31 @Override
32 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
33 return type.equals(ProduceConsumeData.class);
34 }
35
36 @Override
37 public long getSize(ProduceConsumeData data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
38 return -1;
39 }
40
41 @Override
42 public void writeTo(ProduceConsumeData data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
43 String str = data.data + ":" + data.type + ":text";
44 entityStream.write(str.getBytes());
45 }
46 }
+0
-43
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/ProduceConsumeWildData.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import org.jboss.resteasy.plugins.providers.ProviderHelper;
3
4 import javax.ws.rs.WebApplicationException;
5 import javax.ws.rs.core.MediaType;
6 import javax.ws.rs.core.MultivaluedMap;
7 import javax.ws.rs.ext.MessageBodyReader;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14
15 public class ProduceConsumeWildData implements MessageBodyReader<ProduceConsumeData>, MessageBodyWriter<ProduceConsumeData> {
16 @Override
17 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
18 return type.equals(ProduceConsumeData.class);
19 }
20
21 @Override
22 public ProduceConsumeData readFrom(Class<ProduceConsumeData> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
23 String str = ProviderHelper.readString(entityStream, mediaType);
24 return new ProduceConsumeData(str, "wild");
25 }
26
27 @Override
28 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
29 return type.equals(ProduceConsumeData.class);
30 }
31
32 @Override
33 public long getSize(ProduceConsumeData data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
34 return -1;
35 }
36
37 @Override
38 public void writeTo(ProduceConsumeData data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
39 String str = data.data + ":" + data.type + ":wild";
40 entityStream.write(str.getBytes());
41 }
42 }
+0
-82
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/RangeResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.Produces;
5 import java.io.File;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8
9 @Path("/")
10 public class RangeResource {
11
12 static File file;
13 static File smallFile;
14
15 static {
16 file = createFile();
17 smallFile = createSmallFile();
18 }
19
20 @GET
21 @Path("file")
22 @Produces("text/plain")
23 public File getFile() {
24 return file;
25 }
26
27 @GET
28 @Path("deletefile")
29 public void deleteFile() throws Exception {
30 if (file.exists()) {
31 file.delete();
32 }
33 }
34
35 @GET
36 @Path("smallfile")
37 @Produces("text/plain")
38 public File getSmallFile() {
39 return smallFile;
40 }
41
42 @GET
43 @Path("deletesmallfile")
44 public void deleteSmallFile() throws Exception {
45 if (smallFile.exists()) {
46 smallFile.delete();
47 }
48 }
49
50 private static File createFile() {
51 File file = null;
52 try {
53 file = File.createTempFile("tmp", "tmp");
54 FileOutputStream fos = new FileOutputStream(file);
55 for (int i = 0; i < 1000; i++) {
56 fos.write("hello".getBytes());
57 }
58 fos.write("1234".getBytes());
59 fos.flush();
60 fos.close();
61 } catch (IOException e) {
62 throw new RuntimeException(e);
63 }
64 return file;
65 }
66
67 private static File createSmallFile() {
68 File smallfile = null;
69 try {
70 smallfile = File.createTempFile("smalltmp", "tmp");
71 FileOutputStream fos = new FileOutputStream(smallfile);
72 fos.write("123456789".getBytes());
73 fos.flush();
74 fos.close();
75 } catch (IOException e) {
76 throw new RuntimeException(e);
77 }
78 return smallfile;
79 }
80
81 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/ResponseAnnotatedClass.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.ext.Provider;
4
5 /**
6 * This is the dummy class to get annotations from it
7 */
8 @Provider
9 @Consumes
10 public abstract class ResponseAnnotatedClass {
11
12 }
+0
-89
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/ResponseDateReaderWriter.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.Consumes;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyReader;
7 import javax.ws.rs.ext.MessageBodyWriter;
8 import javax.ws.rs.ext.Provider;
9 import java.io.BufferedReader;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.InputStreamReader;
13 import java.io.OutputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.util.Date;
17 import java.util.concurrent.atomic.AtomicInteger;
18
19 @Provider
20 public class ResponseDateReaderWriter implements MessageBodyReader<Date>,
21 MessageBodyWriter<Date> {
22
23 public static final int ANNOTATION_NONE = 0;
24 public static final int ANNOTATION_CONSUMES = 1 << 2;
25 public static final int ANNOTATION_PROVIDER = 1 << 3;
26 public static final int ANNOTATION_UNKNOWN = 1 << 7;
27
28 private final AtomicInteger atom;
29
30 public ResponseDateReaderWriter(final AtomicInteger atom) {
31 super();
32 this.atom = atom;
33 }
34
35 @Override
36 public long getSize(Date arg0, Class<?> arg1, Type arg2, Annotation[] arg3,
37 MediaType arg4) {
38 return String.valueOf(Long.MAX_VALUE).length();
39 }
40
41 @Override
42 public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2,
43 MediaType arg3) {
44 return arg0 == Date.class;
45 }
46
47 @Override
48 public void writeTo(Date date, Class<?> arg1, Type arg2, Annotation[] arg3,
49 MediaType arg4, MultivaluedMap<String, Object> arg5,
50 OutputStream stream) throws IOException, WebApplicationException {
51 parseAnnotations(arg3);
52 stream.write(String.valueOf(date.getTime()).getBytes());
53 }
54
55 @Override
56 public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2,
57 MediaType arg3) {
58 return isWriteable(arg0, arg1, arg2, arg3);
59 }
60
61 @Override
62 public Date readFrom(Class<Date> arg0, Type arg1, Annotation[] arg2,
63 MediaType arg3, MultivaluedMap<String, String> arg4,
64 InputStream arg5) throws IOException, WebApplicationException {
65 parseAnnotations(arg2);
66
67 InputStreamReader reader = new InputStreamReader(arg5);
68 BufferedReader br = new BufferedReader(reader);
69 long date = Long.parseLong(br.readLine());
70 return new Date(date);
71 }
72
73 protected void parseAnnotations(Annotation[] annotations) {
74 int value = ANNOTATION_NONE;
75 if (annotations != null) {
76 for (Annotation annotation : annotations) {
77 if (annotation.annotationType() == Consumes.class) {
78 value |= ANNOTATION_CONSUMES;
79 } else if (annotation.annotationType() == Provider.class) {
80 value |= ANNOTATION_PROVIDER;
81 } else {
82 value |= ANNOTATION_UNKNOWN;
83 }
84 }
85 }
86 atom.set(value);
87 }
88 }
+0
-86
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/ResponseResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.HEAD;
4 import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.QueryParam;
8 import javax.ws.rs.core.Link;
9 import javax.ws.rs.core.MediaType;
10 import javax.ws.rs.core.Response;
11 import javax.ws.rs.ext.RuntimeDelegate;
12 import java.net.URI;
13 import java.net.URISyntaxException;
14
15 @Path("/")
16 public class ResponseResource {
17 public static final String ENTITY = "ENtiTy";
18
19 @GET
20 @Path("empty")
21 public Response empty() {
22 return Response.ok().build();
23 }
24
25 @HEAD
26 @Path("head")
27 public String head() {
28 return "head";
29 }
30
31 @GET
32 @Path("entity")
33 @Produces(MediaType.TEXT_PLAIN)
34 public String entity() {
35 return ENTITY;
36 }
37
38 @GET
39 @Path("date")
40 public String date(@QueryParam("date") String date) {
41 return date;
42 }
43
44 @POST
45 @Path("link")
46 public Response getLink(String rel) {
47 Response.ResponseBuilder builder = Response.ok();
48 if (rel != null && rel.length() != 0) {
49 builder.links(createLink("path", rel));
50 }
51 return builder.build();
52 }
53
54 protected static Link createLink(String path, String rel) {
55 return Link.fromUri(createUri(path)).rel(rel).build();
56 }
57
58 protected static URI createUri(String path) {
59 URI uri;
60 try {
61 uri = new URI("http://localhost.tck:888/url404/" + path);
62 } catch (URISyntaxException e) {
63 throw new RuntimeException(e);
64 }
65 return uri;
66 }
67
68 @GET
69 @Path("entitybodyresponsetest")
70 public Response entityResponseTest() {
71 RuntimeDelegate rd = RuntimeDelegate.getInstance();
72 Response.ResponseBuilder rb = rd.createResponseBuilder();
73 String rwe = "hello";
74 Response build = rb.entity(rwe).build();
75 return build;
76 }
77
78 @GET
79 @Path("nullEntityResponse")
80 public Response nullEntityResponse() {
81 RuntimeDelegate rd = RuntimeDelegate.getInstance();
82 Response.ResponseBuilder rb = rd.createResponseBuilder();
83 return rb.entity(null).build();
84 }
85 }
+0
-39
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/SimpleResource.java less more
0 /*
1 * JBoss, Home of Professional Open Source
2 * Copyright 2016, Red Hat Inc., and individual contributors as indicated
3 * by the @authors tag. See the copyright.txt in the distribution for a
4 * full listing of individual contributors.
5 *
6 * This is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 2.1 of
9 * the License, or (at your option) any later version.
10 *
11 * This software is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this software; if not, write to the Free
18 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
19 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
20 */
21 package org.jboss.resteasy.test.response.resource;
22
23 import javax.ws.rs.GET;
24 import javax.ws.rs.Path;
25 import javax.ws.rs.Produces;
26
27 /**
28 * @author Ivo Studensky
29 */
30 @Path("/simpleresource")
31 public class SimpleResource {
32
33 @GET
34 @Produces("text/plain")
35 public String get() {
36 return "hello";
37 }
38 }
+0
-40
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/VariantAcceptResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import org.jboss.resteasy.test.response.VariantAcceptTest;
3
4 import javax.ws.rs.GET;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.core.Context;
7 import javax.ws.rs.core.HttpHeaders;
8 import javax.ws.rs.core.MediaType;
9 import javax.ws.rs.core.Request;
10 import javax.ws.rs.core.Variant;
11 import java.util.List;
12
13 import static javax.ws.rs.core.MediaType.TEXT_HTML_TYPE;
14 import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
15
16 @Path("")
17 public class VariantAcceptResource {
18 @Context
19 private Request request;
20
21 @Context
22 private HttpHeaders headers;
23
24 @GET
25 @Path("variant")
26 public String variant() {
27 List<Variant> variants = Variant.mediaTypes(TEXT_PLAIN_TYPE, TEXT_HTML_TYPE).build();
28 MediaType selected = request.selectVariant(variants).getMediaType();
29 return selected.toString();
30 }
31
32 @GET
33 @Path("params")
34 public String params() {
35 List<Variant> variants = Variant.mediaTypes(VariantAcceptTest.TEXT_PLAIN_WITH_PARAMS, VariantAcceptTest.TEXT_HTML_WITH_PARAMS).build();
36 MediaType selected = request.selectVariant(variants).getMediaType();
37 return selected.toString();
38 }
39 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/VariantComplexResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Response;
5 import javax.ws.rs.core.Request;
6 import javax.ws.rs.core.Variant;
7 import javax.ws.rs.core.Context;
8 import javax.ws.rs.core.MediaType;
9 import java.util.List;
10 import java.util.Locale;
11
12 @Path("/complex")
13 public class VariantComplexResource {
14 @GET
15 public Response doGet(@Context Request req) {
16 List<Variant> vs = Variant.VariantListBuilder.newInstance().mediaTypes(MediaType.valueOf("image/jpeg")).add()
17 .mediaTypes(MediaType.valueOf("application/xml")).languages(new Locale("en", "us")).add().mediaTypes(
18 MediaType.valueOf("text/xml")).languages(new Locale("en")).add().mediaTypes(
19 MediaType.valueOf("text/xml")).languages(new Locale("en", "us")).add().build();
20
21 Variant v = req.selectVariant(vs);
22 if (v == null) {
23 return Response.notAcceptable(vs).build();
24 } else {
25 return Response.ok("GET", v).build();
26 }
27 }
28 }
+0
-23
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/VariantEncodingResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4 import javax.ws.rs.core.Context;
5 import javax.ws.rs.core.Request;
6 import javax.ws.rs.core.Response;
7 import javax.ws.rs.core.Variant;
8 import java.util.List;
9
10 @Path("/encoding")
11 public class VariantEncodingResource {
12 @GET
13 public Response doGet(@Context Request req) {
14 List<Variant> vs = Variant.VariantListBuilder.newInstance().encodings("enc1", "enc2", "enc3").add().build();
15 Variant v = req.selectVariant(vs);
16 if (v == null) {
17 return Response.notAcceptable(vs).build();
18 } else {
19 return Response.ok(v.getEncoding(), v).build();
20 }
21 }
22 }
+0
-152
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/VariantLanguageResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.PUT;
4 import javax.ws.rs.Path;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.POST;
7 import javax.ws.rs.DELETE;
8 import javax.ws.rs.core.Context;
9 import javax.ws.rs.core.Request;
10 import javax.ws.rs.core.Response;
11 import javax.ws.rs.core.Variant;
12 import javax.ws.rs.core.MediaType;
13 import javax.ws.rs.core.EntityTag;
14 import java.util.Calendar;
15 import java.util.Date;
16 import java.util.List;
17 import java.util.Locale;
18
19 @Path("/")
20 public class VariantLanguageResource {
21
22
23 @GET
24 @Produces("text/plain")
25 public Response doGet(@Context Request req) {
26 List<Variant> vs = Variant.VariantListBuilder.newInstance().languages(new Locale("zh")).languages(
27 new Locale("fr")).languages(new Locale("en")).add().build();
28
29 Variant v = req.selectVariant(vs);
30 if (v == null) {
31 return Response.notAcceptable(vs).build();
32 } else {
33 return Response.ok(v.getLanguage(), v).build();
34 }
35 }
36
37 @Path("/brazil")
38 @GET
39 @Produces("text/plain")
40 public Response doGetBrazil(@Context Request req) {
41 List<Variant> vs = Variant.VariantListBuilder.newInstance().languages(new Locale("pt", "BR")).add().build();
42
43 Variant v = req.selectVariant(vs);
44 if (v == null) {
45 return Response.notAcceptable(vs).build();
46 } else {
47 return Response.ok(v.getLanguage(), v).build();
48 }
49 }
50
51 @GET
52 @Path("/SelectVariantTestResponse")
53 public Response selectVariantTestResponse(@Context Request req) {
54 List<Variant> list = Variant.encodings("CP1250", "UTF-8")
55 .languages(Locale.ENGLISH)
56 .mediaTypes(MediaType.APPLICATION_JSON_TYPE).add().build();
57 Variant selectedVariant = req.selectVariant(list);
58 if (null == selectedVariant) {
59 return Response.notAcceptable(list).build();
60 }
61 return Response.ok("entity").build();
62 }
63
64 @GET
65 @Path("/SelectVariantTestGet")
66 public Response selectVariantTestGet(@Context Request req) {
67 List<Variant> vs = null;
68
69 try {
70 req.selectVariant(vs);
71 return Response.ok("Test FAILED - no exception thrown").build();
72 } catch (IllegalArgumentException ile) {
73 return Response.ok("PASSED")
74 .build();
75 } catch (Throwable th) {
76 //logger.error("This not the expected exception", th);
77 return Response.ok(
78 "Test FAILED - wrong type exception thrown" +
79 th.getMessage()).build();
80 }
81 }
82
83 @PUT
84 @Path("/SelectVariantTestPut")
85 public Response selectVariantTestPut(@Context Request req) {
86 return selectVariantTestGet(req);
87 }
88
89 @POST
90 @Path("/SelectVariantTestPost")
91 public Response selectVariantTestPost(@Context Request req) {
92 return selectVariantTestGet(req);
93 }
94
95 @DELETE
96 @Path("/SelectVariantTestDelete")
97 public Response selectVariantTestDelete(@Context Request req) {
98 return selectVariantTestGet(req);
99 }
100
101 @GET
102 @Path("/preconditionsSimpleGet")
103 public Response evaluatePreconditionsEntityTagGetSimpleTest(
104 @Context Request req) {
105 boolean ok = evaluatePreconditionsEntityTag(req, "AAA");
106 if (!ok) {
107 return Response.status(Response.Status.GONE).build();
108 }
109 ok &= evaluatePreconditionsNowEntityTagNull(req);
110 if (!ok) {
111 return Response.status(Response.Status.NOT_ACCEPTABLE).build();
112 }
113 ok &= evaluatePreconditionsEntityTagNull(req);
114 return createResponse(ok);
115 }
116
117 private boolean evaluatePreconditionsEntityTagNull(Request req) {
118 try {
119 req.evaluatePreconditions((EntityTag) null);
120 return false;
121 } catch (IllegalArgumentException iae) {
122 return true;
123 }
124 }
125
126 private boolean evaluatePreconditionsNowEntityTagNull(Request req) {
127 try {
128 Date now = Calendar.getInstance().getTime();
129 req.evaluatePreconditions(now, (EntityTag) null);
130 return false;
131 } catch (IllegalArgumentException iae) {
132 return true;
133 }
134 }
135
136 private EntityTag createTag(String tag) {
137 String xtag = new StringBuilder().append("\"").append(tag).append("\"")
138 .toString();
139 return EntityTag.valueOf(xtag);
140 }
141
142 private boolean evaluatePreconditionsEntityTag(Request req, String tag) {
143 Response.ResponseBuilder rb = req.evaluatePreconditions(createTag(tag));
144 return rb == null;
145 }
146
147 private Response createResponse(boolean ok) {
148 Response.Status status = ok ? Response.Status.OK : Response.Status.PRECONDITION_FAILED;
149 return Response.status(status).build();
150 }
151 }
+0
-34
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/WriterMatchingBoolWriter.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.Produces;
3 import javax.ws.rs.WebApplicationException;
4 import javax.ws.rs.core.MediaType;
5 import javax.ws.rs.core.MultivaluedMap;
6 import javax.ws.rs.ext.MessageBodyWriter;
7 import java.io.IOException;
8 import java.io.OutputStream;
9 import java.lang.annotation.Annotation;
10 import java.lang.reflect.Type;
11
12 @Produces(MediaType.WILDCARD)
13 public class WriterMatchingBoolWriter implements MessageBodyWriter<Object> {
14 @Override
15 public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
16 return type.equals(Boolean.class);
17 }
18
19 @Override
20 public long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
21 return -1;
22 }
23
24 @Override
25 public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
26 Boolean b = (Boolean) o;
27 if (b.booleanValue()) {
28 entityStream.write("YES".getBytes());
29 } else {
30 entityStream.write("NO".getBytes());
31 }
32 }
33 }
+0
-13
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/response/resource/WriterMatchingResource.java less more
0 package org.jboss.resteasy.test.response.resource;
1
2 import javax.ws.rs.GET;
3 import javax.ws.rs.Path;
4
5 @Path("/")
6 public class WriterMatchingResource {
7 @GET
8 @Path("bool")
9 public Boolean responseOk() {
10 return true;
11 }
12 }
+0
-74
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/validation/ContextProvidersOldClientTest.java less more
0 package org.jboss.resteasy.test.validation;
1
2 import org.jboss.arquillian.container.test.api.Deployment;
3 import org.jboss.arquillian.container.test.api.RunAsClient;
4 import org.jboss.arquillian.junit.Arquillian;
5 import org.jboss.resteasy.client.ClientRequest; //@cs-: clientrequest (Test for old client)
6 import org.jboss.resteasy.client.ClientResponse; //@cs-: clientresponse (Test for old client)
7 import org.jboss.resteasy.test.validation.resource.ContextProvidersCustomer;
8 import org.jboss.resteasy.test.validation.resource.ContextProvidersCustomerForm;
9 import org.jboss.resteasy.test.validation.resource.ContextProvidersName;
10 import org.jboss.resteasy.test.validation.resource.ContextProvidersResource;
11 import org.jboss.resteasy.test.validation.resource.ContextProvidersXop;
12 import org.jboss.resteasy.util.HttpResponseCodes;
13 import org.jboss.resteasy.utils.PortProviderUtil;
14 import org.jboss.resteasy.utils.TestUtil;
15 import org.jboss.shrinkwrap.api.Archive;
16 import org.jboss.shrinkwrap.api.asset.EmptyAsset;
17 import org.jboss.shrinkwrap.api.spec.WebArchive;
18 import org.junit.Assert;
19 import org.junit.runner.RunWith;
20
21 import javax.ws.rs.core.MediaType;
22 import java.lang.annotation.Annotation;
23 import java.lang.reflect.Type;
24
25 /**
26 * @tpSubChapter Multipart provider
27 * @tpChapter Integration tests
28 * @tpTestCaseDetails Regression test for RESTEASY-1119. Test for old client.
29 * @tpSince RESTEasy 3.0.16
30 */
31 @RunWith(Arquillian.class)
32 @RunAsClient
33 public class ContextProvidersOldClientTest extends ContextProvidersTestBase {
34 @Deployment
35 public static Archive<?> createTestArchive() {
36 WebArchive war = TestUtil.prepareArchive(ContextProvidersOldClientTest.class.getSimpleName())
37 .addClasses(ContextProvidersCustomer.class, ContextProvidersCustomerForm.class, ContextProvidersName.class, ContextProvidersXop.class)
38 .addClass(ContextProvidersTestBase.class)
39 .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
40
41 return TestUtil.finishContainerPrepare(war, null, ContextProvidersResource.class);
42 }
43
44 private static String generateURL(String path) {
45 return PortProviderUtil.generateURL(path, ContextProvidersOldClientTest.class.getSimpleName());
46 }
47
48 @Override
49 <T> T get(String path, Class<T> clazz, Annotation[] annotations) throws Exception {
50 ClientRequest request = new ClientRequest(generateURL(path));
51 ClientResponse<T> response = request.get(clazz);
52 Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
53 T entity = response.getEntity(clazz, null, annotations);
54 return entity;
55 }
56
57 @Override
58 <S, T> T post(String path, S payload, MediaType mediaType,
59 Class<T> returnType, Type genericReturnType, Annotation[] annotations) throws Exception {
60 ClientRequest request = new ClientRequest(generateURL(path));
61 request.body(mediaType, payload, payload.getClass(), null, annotations);
62 ClientResponse response = request.post();
63 T entity;
64 if (genericReturnType != null) {
65 entity = (T) response.getEntity(returnType, genericReturnType);
66 } else {
67 entity = (T) response.getEntity(returnType);
68 }
69
70 return entity;
71 }
72
73 }
+0
-359
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/validation/ContextProvidersTestBase.java less more
0 package org.jboss.resteasy.test.validation;
1
2 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
3 import org.jboss.resteasy.annotations.providers.multipart.PartType;
4 import org.jboss.resteasy.annotations.providers.multipart.XopWithMultipartRelated;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
7 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
8 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
9 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
10 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedInput;
11 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedOutput;
12 import org.jboss.resteasy.test.validation.resource.ContextProvidersCustomer;
13 import org.jboss.resteasy.test.validation.resource.ContextProvidersCustomerForm;
14 import org.jboss.resteasy.test.validation.resource.ContextProvidersName;
15 import org.jboss.resteasy.test.validation.resource.ContextProvidersXop;
16 import org.junit.Assert;
17 import org.junit.Test;
18
19 import javax.enterprise.util.AnnotationLiteral;
20 import javax.ws.rs.core.MediaType;
21 import java.lang.annotation.Annotation;
22 import java.lang.reflect.Type;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30
31 /**
32 * @tpSubChapter Multipart provider
33 * @tpChapter Integration tests
34 * @tpTestCaseDetails Regression test for RESTEASY-1119.
35 * This is abstract class, ContextProvidersOldClientTest and ContextProvidersOldClientTest use this abstract class.
36 * @tpSince RESTEasy 3.0.16
37 */
38 public abstract class ContextProvidersTestBase {
39 static final String RESPONSE_ERROR_MSG = "Response has wrong content";
40 static final MediaType MULTIPART_MIXED = new MediaType("multipart", "mixed");
41 static final MediaType MULTIPART_FORM_DATA = new MediaType("multipart", "form-data");
42 static final MediaType MULTIPART_RELATED = new MediaType("multipart", "related");
43
44 static final javax.ws.rs.core.GenericType<List<ContextProvidersName>> LIST_NAME_TYPE = new javax.ws.rs.core.GenericType<List<ContextProvidersName>>() {
45 };
46
47 public abstract static class S1 extends AnnotationLiteral<PartType> implements PartType {
48 private static final long serialVersionUID = 1L;
49 }
50
51 public static final Annotation PART_TYPE_APPLICATION_XML = new S1() {
52 private static final long serialVersionUID = 1L;
53
54 @Override
55 public String value() {
56 return "application/xml";
57 }
58 };
59
60 public abstract static class S2 extends AnnotationLiteral<MultipartForm> implements MultipartForm {
61 private static final long serialVersionUID = 1L;
62 }
63
64 public static final Annotation MULTIPART_FORM = new S2() {
65 private static final long serialVersionUID = 1L;
66 };
67
68 public abstract static class S3 extends AnnotationLiteral<XopWithMultipartRelated> implements XopWithMultipartRelated {
69 private static final long serialVersionUID = 1L;
70 }
71
72 public static final Annotation XOP_WITH_MULTIPART_RELATED = new S3() {
73 private static final long serialVersionUID = 1L;
74 };
75
76 /**
77 * @tpTestDetails Test get request and form data in response.
78 * @tpSince RESTEasy 3.0.16
79 */
80 @Test
81 public void testGetFormData() throws Exception {
82 MultipartFormDataInput entity = get("/get/form", MultipartFormDataInput.class);
83
84 // Get parts by name.
85 ContextProvidersCustomer c = entity.getFormDataPart("bill", ContextProvidersCustomer.class, null);
86 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bill", c.getName());
87 String s = entity.getFormDataPart("bob", String.class, null);
88 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bob", s);
89
90 // Iterate over list of parts.
91 Map<String, List<InputPart>> map = entity.getFormDataMap();
92 for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
93 String key = it.next();
94 List<InputPart> list = map.get(key);
95 for (Iterator<InputPart> it2 = list.iterator(); it2.hasNext(); ) {
96 InputPart inputPart = it2.next();
97 if (MediaType.APPLICATION_XML_TYPE.equals(inputPart.getMediaType())) {
98 c = inputPart.getBody(ContextProvidersCustomer.class, null);
99 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bill", c.getName());
100 } else {
101 s = inputPart.getBody(String.class, null);
102 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bob", s);
103 }
104 }
105 }
106 }
107
108 /**
109 * @tpTestDetails Test get request. Response should contain xml and text-plain data.
110 * @tpSince RESTEasy 3.0.16
111 */
112 @Test
113 public void testGetMixed() throws Exception {
114 MultipartInput entity = get("/get/mixed", MultipartInput.class);
115
116 // Iterate over list of parts.
117 List<InputPart> parts = entity.getParts();
118 for (Iterator<InputPart> it = parts.iterator(); it.hasNext(); ) {
119 InputPart inputPart = it.next();
120 if (MediaType.APPLICATION_XML_TYPE.equals(inputPart.getMediaType())) {
121 ContextProvidersCustomer c = inputPart.getBody(ContextProvidersCustomer.class, null);
122 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bill", c.getName());
123 } else {
124 String s = inputPart.getBody(String.class, null);
125 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bob", s);
126 }
127 }
128 }
129
130 /**
131 * @tpTestDetails Test get request. Response should contain list.
132 * @tpSince RESTEasy 3.0.16
133 */
134 @Test
135 public void testGetList() throws Exception {
136 MultipartInput entity = get("/get/list", MultipartInput.class);
137
138 // Iterate over list of parts.
139 List<InputPart> parts = entity.getParts();
140 Set<String> customers = new HashSet<String>();
141 for (Iterator<InputPart> it = parts.iterator(); it.hasNext(); ) {
142 InputPart inputPart = it.next();
143 customers.add(inputPart.getBody(ContextProvidersCustomer.class, null).getName());
144 }
145 Assert.assertEquals(RESPONSE_ERROR_MSG, 2, customers.size());
146 Assert.assertTrue(RESPONSE_ERROR_MSG, customers.contains("Bill"));
147 Assert.assertTrue(RESPONSE_ERROR_MSG, customers.contains("Bob"));
148 }
149
150 /**
151 * @tpTestDetails Test get request. Response should contain map.
152 * @tpSince RESTEasy 3.0.16
153 */
154 @Test
155 public void testGetMap() throws Exception {
156 MultipartFormDataInput entity = get("/get/map", MultipartFormDataInput.class);
157
158 // Get parts by name.
159 ContextProvidersCustomer c = entity.getFormDataPart("bill", ContextProvidersCustomer.class, null);
160 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bill", c.getName());
161 c = entity.getFormDataPart("bob", ContextProvidersCustomer.class, null);
162 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bob", c.getName());
163
164 // Iterate over map of parts.
165 Map<String, List<InputPart>> map = entity.getFormDataMap();
166 Set<String> customers = new HashSet<String>();
167 for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
168 String key = it.next();
169 List<InputPart> list = map.get(key);
170 for (Iterator<InputPart> it2 = list.iterator(); it2.hasNext(); ) {
171 InputPart inputPart = it2.next();
172 customers.add(inputPart.getBody(ContextProvidersCustomer.class, null).getName());
173 }
174 }
175 Assert.assertEquals(RESPONSE_ERROR_MSG, 2, customers.size());
176 Assert.assertTrue(RESPONSE_ERROR_MSG, customers.contains("Bill"));
177 Assert.assertTrue(RESPONSE_ERROR_MSG, customers.contains("Bob"));
178 }
179
180 /**
181 * @tpTestDetails Test get request. Response should contain multipart/related.
182 * @tpSince RESTEasy 3.0.16
183 */
184 @Test
185 public void testGetRelated() throws Exception {
186 MultipartRelatedInput entity = get("/get/related", MultipartRelatedInput.class);
187
188 // Iterate over map of parts.
189 Map<String, InputPart> map = entity.getRelatedMap();
190 Set<String> keys = map.keySet();
191 Assert.assertEquals(RESPONSE_ERROR_MSG, 2, keys.size());
192 Assert.assertTrue(RESPONSE_ERROR_MSG, keys.contains("bill"));
193 Assert.assertTrue(RESPONSE_ERROR_MSG, keys.contains("bob"));
194 Set<String> parts = new HashSet<String>();
195 for (Iterator<InputPart> it = map.values().iterator(); it.hasNext(); ) {
196 parts.add(it.next().getBody(String.class, null));
197 }
198 Assert.assertTrue(RESPONSE_ERROR_MSG, parts.contains("Bill"));
199 Assert.assertTrue(RESPONSE_ERROR_MSG, parts.contains("Bob"));
200 }
201
202 /**
203 * @tpTestDetails Test get request. Response should contain multipart/form.
204 * @tpSince RESTEasy 3.0.16
205 */
206 @Test
207 public void testGetMultipartForm() throws Exception {
208 Annotation[] annotations = new Annotation[1];
209 annotations[0] = MULTIPART_FORM;
210 ContextProvidersCustomerForm form = get("/get/multipartform", ContextProvidersCustomerForm.class, annotations);
211 ContextProvidersCustomer customer = form.getCustomer();
212 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bill", customer.getName());
213 }
214
215 /**
216 * @tpTestDetails Test get request. Response should contain xop (XML-binary Optimized Packaging).
217 * @tpSince RESTEasy 3.0.16
218 */
219 @Test
220 public void testGetXop() throws Exception {
221 Annotation[] annotations = new Annotation[1];
222 annotations[0] = XOP_WITH_MULTIPART_RELATED;
223 ContextProvidersXop xop = get("/get/xop", ContextProvidersXop.class, annotations);
224 Assert.assertEquals(RESPONSE_ERROR_MSG, "goodbye world", new String(xop.getBytes()));
225 }
226
227 /**
228 * @tpTestDetails Test post request with mixed params.
229 * @tpSince RESTEasy 3.0.16
230 */
231 @Test
232 @SuppressWarnings("unchecked")
233 public void testPostMixed() throws Exception {
234 MultipartOutput output = new MultipartOutput();
235 output.addPart(new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE);
236 output.addPart("Bob", MediaType.TEXT_PLAIN_TYPE);
237 Annotation[] annotations = new Annotation[1];
238 annotations[0] = PART_TYPE_APPLICATION_XML;
239 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
240 names = post("/post/mixed", output, MULTIPART_MIXED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
241 Assert.assertEquals(RESPONSE_ERROR_MSG, 2, names.size());
242 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("Bill")));
243 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("Bob")));
244 }
245
246 /**
247 * @tpTestDetails Test post request with form params.
248 * @tpSince RESTEasy 3.0.16
249 */
250 @Test
251 @SuppressWarnings("unchecked")
252 public void testPostFormData() throws Exception {
253 MultipartFormDataOutput output = new MultipartFormDataOutput();
254 output.addFormData("bill", new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE);
255 output.addFormData("bob", "Bob", MediaType.TEXT_PLAIN_TYPE);
256 Annotation[] annotations = new Annotation[1];
257 annotations[0] = PART_TYPE_APPLICATION_XML;
258 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
259 names = post("/post/form", output, MULTIPART_FORM_DATA, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
260 Assert.assertEquals(RESPONSE_ERROR_MSG, 2, names.size());
261 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("Bill")));
262 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("Bob")));
263 }
264
265 /**
266 * @tpTestDetails Test post request with list param.
267 * @tpSince RESTEasy 3.0.16
268 */
269 @Test
270 @SuppressWarnings("unchecked")
271 public void testPostList() throws Exception {
272 List<ContextProvidersCustomer> customers = new ArrayList<ContextProvidersCustomer>();
273 customers.add(new ContextProvidersCustomer("Bill"));
274 customers.add(new ContextProvidersCustomer("Bob"));
275 Annotation[] annotations = new Annotation[1];
276 annotations[0] = PART_TYPE_APPLICATION_XML;
277 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
278 names = post("/post/list", customers, MULTIPART_MIXED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
279 Assert.assertEquals(RESPONSE_ERROR_MSG, 2, names.size());
280 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("Bill")));
281 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("Bob")));
282 }
283
284 /**
285 * @tpTestDetails Test post request with map param.
286 * @tpSince RESTEasy 3.0.16
287 */
288 @Test
289 @SuppressWarnings("unchecked")
290 public void testPostMap() throws Exception {
291 Map<String, ContextProvidersCustomer> customers = new HashMap<String, ContextProvidersCustomer>();
292 customers.put("bill", new ContextProvidersCustomer("Bill"));
293 customers.put("bob", new ContextProvidersCustomer("Bob"));
294 Annotation[] annotations = new Annotation[1];
295 annotations[0] = PART_TYPE_APPLICATION_XML;
296 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
297 names = post("/post/map", customers, MULTIPART_FORM_DATA, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
298 Assert.assertEquals(RESPONSE_ERROR_MSG, 2, names.size());
299 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("bill:Bill")));
300 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("bob:Bob")));
301 }
302
303 /**
304 * @tpTestDetails Test post request with multipart/related param.
305 * @tpSince RESTEasy 3.0.16
306 */
307 @Test
308 @SuppressWarnings("unchecked")
309 public void testPostRelated() throws Exception {
310 MultipartRelatedOutput output = new MultipartRelatedOutput();
311 output.setStartInfo("text/html");
312 output.addPart("Bill", new MediaType("image", "png"), "bill", "binary");
313 output.addPart("Bob", new MediaType("image", "png"), "bob", "binary");
314 Annotation[] annotations = new Annotation[1];
315 annotations[0] = PART_TYPE_APPLICATION_XML;
316 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
317 names = post("/post/related", output, MULTIPART_RELATED, names.getClass(), LIST_NAME_TYPE.getType(), annotations);
318 Assert.assertEquals(RESPONSE_ERROR_MSG, 2, names.size());
319 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("Bill")));
320 Assert.assertTrue(RESPONSE_ERROR_MSG, names.contains(new ContextProvidersName("Bob")));
321 }
322
323 /**
324 * @tpTestDetails Test post request with multipart/form param.
325 * @tpSince RESTEasy 3.0.16
326 */
327 @Test
328 public void testPostMultipartForm() throws Exception {
329 ContextProvidersCustomerForm form = new ContextProvidersCustomerForm();
330 form.setCustomer(new ContextProvidersCustomer("Bill"));
331 Annotation[] annotations = new Annotation[1];
332 annotations[0] = MULTIPART_FORM;
333 String name = post("/post/multipartform", form, MULTIPART_FORM_DATA, String.class, null, annotations);
334 Assert.assertEquals(RESPONSE_ERROR_MSG, "Bill", name);
335 }
336
337 /**
338 * @tpTestDetails Test post request with xop param (XML-binary Optimized Packaging).
339 * @tpSince RESTEasy 3.0.16
340 */
341 @Test
342 public void testPostXop() throws Exception {
343 ContextProvidersXop xop = new ContextProvidersXop("hello world".getBytes());
344 Annotation[] annotations = new Annotation[1];
345 annotations[0] = XOP_WITH_MULTIPART_RELATED;
346 String s = post("/post/xop", xop, MULTIPART_RELATED, String.class, null, annotations);
347 Assert.assertEquals(RESPONSE_ERROR_MSG, "hello world", s);
348 }
349
350 <T> T get(String path, Class<T> clazz) throws Exception {
351 return get(path, clazz, null);
352 }
353
354 abstract <T> T get(String path, Class<T> clazz, Annotation[] annotations) throws Exception;
355
356 abstract <S, T> T post(String path, S payload, MediaType mediaType, Class<T> returnType, Type genericReturnType, Annotation[] annotations) throws Exception;
357
358 }
+0
-24
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/validation/resource/ContextProvidersCustomer.java less more
0 package org.jboss.resteasy.test.validation.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "customer")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class ContextProvidersCustomer {
10 @XmlElement
11 private String name;
12
13 public ContextProvidersCustomer() {
14 }
15
16 public ContextProvidersCustomer(final String name) {
17 this.name = name;
18 }
19
20 public String getName() {
21 return name;
22 }
23 }
+0
-19
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/validation/resource/ContextProvidersCustomerForm.java less more
0 package org.jboss.resteasy.test.validation.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.PartType;
3
4 import javax.ws.rs.FormParam;
5
6 public class ContextProvidersCustomerForm {
7 @FormParam("customer")
8 @PartType("application/xml")
9 private ContextProvidersCustomer customer;
10
11 public ContextProvidersCustomer getCustomer() {
12 return customer;
13 }
14
15 public void setCustomer(ContextProvidersCustomer cust) {
16 this.customer = cust;
17 }
18 }
+0
-38
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/validation/resource/ContextProvidersName.java less more
0 package org.jboss.resteasy.test.validation.resource;
1
2 import javax.xml.bind.annotation.XmlAccessType;
3 import javax.xml.bind.annotation.XmlAccessorType;
4 import javax.xml.bind.annotation.XmlElement;
5 import javax.xml.bind.annotation.XmlRootElement;
6
7 @XmlRootElement(name = "name")
8 @XmlAccessorType(XmlAccessType.FIELD)
9 public class ContextProvidersName {
10 @XmlElement
11 private String name;
12
13 public ContextProvidersName() {
14 }
15
16 public ContextProvidersName(final String name) {
17 this.name = name;
18 }
19
20 public String getName() {
21 return name;
22 }
23
24 public boolean equals(Object o) {
25 if (o == null) {
26 return false;
27 }
28 if (!(o instanceof ContextProvidersName)) {
29 return false;
30 }
31 return name.equals(((ContextProvidersName) o).getName());
32 }
33
34 public int hashCode() {
35 return super.hashCode();
36 }
37 }
+0
-191
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/validation/resource/ContextProvidersResource.java less more
0 package org.jboss.resteasy.test.validation.resource;
1
2 import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
3 import org.jboss.resteasy.annotations.providers.multipart.PartType;
4 import org.jboss.resteasy.annotations.providers.multipart.XopWithMultipartRelated;
5 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
6 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
7 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
8 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
9 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
10 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedInput;
11 import org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedOutput;
12
13 import javax.ws.rs.Consumes;
14 import javax.ws.rs.GET;
15 import javax.ws.rs.POST;
16 import javax.ws.rs.Path;
17 import javax.ws.rs.Produces;
18 import javax.ws.rs.core.MediaType;
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25
26 @Path("")
27 public class ContextProvidersResource {
28 @GET
29 @Produces("multipart/mixed")
30 @Path("get/mixed")
31 public MultipartOutput getMixed() {
32 MultipartOutput output = new MultipartOutput();
33 output.addPart(new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE);
34 output.addPart("Bob", MediaType.TEXT_PLAIN_TYPE);
35 return output;
36 }
37
38 @GET
39 @Produces("multipart/form-data")
40 @MultipartForm
41 @Path("get/form")
42 public MultipartFormDataOutput getForm() {
43 MultipartFormDataOutput output = new MultipartFormDataOutput();
44 output.addFormData("bill", new ContextProvidersCustomer("Bill"), MediaType.APPLICATION_XML_TYPE, "tmp1");
45 output.addFormData("bob", "Bob", MediaType.TEXT_PLAIN_TYPE);
46 return output;
47 }
48
49 @GET
50 @Produces("multipart/mixed")
51 @PartType("application/xml")
52 @Path("get/list")
53 public List<ContextProvidersCustomer> getList() {
54 List<ContextProvidersCustomer> list = new ArrayList<ContextProvidersCustomer>();
55 list.add(new ContextProvidersCustomer("Bill"));
56 list.add(new ContextProvidersCustomer("Bob"));
57 return list;
58 }
59
60 @GET
61 @Produces("multipart/form-data")
62 @PartType("application/xml")
63 @Path("get/map")
64 public Map<String, ContextProvidersCustomer> getMap() {
65 Map<String, ContextProvidersCustomer> map = new HashMap<String, ContextProvidersCustomer>();
66 map.put("bill", new ContextProvidersCustomer("Bill"));
67 map.put("bob", new ContextProvidersCustomer("Bob"));
68 return map;
69 }
70
71 @GET
72 @Produces("multipart/related")
73 @Path("get/related")
74 public MultipartRelatedOutput getRelated() {
75 MultipartRelatedOutput output = new MultipartRelatedOutput();
76 output.setStartInfo("text/html");
77 output.addPart("Bill", new MediaType("image", "png"), "bill", "binary");
78 output.addPart("Bob", new MediaType("image", "png"), "bob", "binary");
79 return output;
80 }
81
82 @GET
83 @Path("get/multipartform")
84 @Produces("multipart/form-data")
85 @MultipartForm
86 public ContextProvidersCustomerForm getMultipartForm() {
87 ContextProvidersCustomerForm form = new ContextProvidersCustomerForm();
88 form.setCustomer(new ContextProvidersCustomer("Bill"));
89 return form;
90 }
91
92 @GET
93 @Path("get/xop")
94 @Produces("multipart/related")
95 @XopWithMultipartRelated
96 public ContextProvidersXop getXop() {
97 return new ContextProvidersXop("goodbye world".getBytes());
98 }
99
100 @POST
101 @Consumes("multipart/mixed")
102 @Produces(MediaType.APPLICATION_XML)
103 @Path("post/mixed")
104 public List<ContextProvidersName> postMixed(MultipartInput input) throws IOException {
105 List<InputPart> list = input.getParts();
106 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
107 for (Iterator<InputPart> it = list.iterator(); it.hasNext(); ) {
108 InputPart inputPart = it.next();
109 if (MediaType.APPLICATION_XML_TYPE.equals(inputPart.getMediaType())) {
110 names.add(new ContextProvidersName(inputPart.getBody(ContextProvidersCustomer.class, null).getName()));
111 } else {
112 names.add(new ContextProvidersName(inputPart.getBody(String.class, null)));
113 }
114 }
115 return names;
116 }
117
118 @POST
119 @Consumes("multipart/form-data")
120 @Produces(MediaType.APPLICATION_XML)
121 @Path("post/form")
122 public List<ContextProvidersName> postForm(MultipartFormDataInput input) throws IOException {
123 Map<String, List<InputPart>> map = input.getFormDataMap();
124 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
125 for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
126 String key = it.next();
127 InputPart inputPart = map.get(key).iterator().next();
128 if (MediaType.APPLICATION_XML_TYPE.equals(inputPart.getMediaType())) {
129 names.add(new ContextProvidersName(inputPart.getBody(ContextProvidersCustomer.class, null).getName()));
130 } else {
131 names.add(new ContextProvidersName(inputPart.getBody(String.class, null)));
132 }
133 }
134 return names;
135 }
136
137 @POST
138 @Consumes("multipart/mixed")
139 @Produces(MediaType.APPLICATION_XML)
140 @Path("post/list")
141 public List<ContextProvidersName> postList(List<ContextProvidersCustomer> customers) throws IOException {
142 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
143 for (ContextProvidersCustomer customer : customers) {
144 names.add(new ContextProvidersName(customer.getName()));
145 }
146 return names;
147 }
148
149 @POST
150 @Consumes("multipart/form-data")
151 @Produces(MediaType.APPLICATION_XML)
152 @Path("post/map")
153 public List<ContextProvidersName> postMap(Map<String, ContextProvidersCustomer> customers) throws IOException {
154 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
155 for (Iterator<String> it = customers.keySet().iterator(); it.hasNext(); ) {
156 String key = it.next();
157 ContextProvidersCustomer customer = customers.get(key);
158 names.add(new ContextProvidersName(key + ":" + customer.getName()));
159 }
160 return names;
161 }
162
163 @POST
164 @Consumes("multipart/related")
165 @Produces(MediaType.APPLICATION_XML)
166 @Path("post/related")
167 public List<ContextProvidersName> postRelated(MultipartRelatedInput customers) throws IOException {
168 List<ContextProvidersName> names = new ArrayList<ContextProvidersName>();
169 for (Iterator<InputPart> it = customers.getParts().iterator(); it.hasNext(); ) {
170 InputPart part = it.next();
171 String name = part.getBody(String.class, null);
172 names.add(new ContextProvidersName(name));
173 }
174 return names;
175 }
176
177 @POST
178 @Consumes("multipart/form-data")
179 @Path("post/multipartform")
180 public String postMultipartForm(@MultipartForm ContextProvidersCustomerForm form) throws IOException {
181 return form.getCustomer().getName();
182 }
183
184 @POST
185 @Path("post/xop")
186 @Consumes("multipart/related")
187 public String postXop(@XopWithMultipartRelated ContextProvidersXop xop) {
188 return new String(xop.getBytes());
189 }
190 }
+0
-29
testsuite/legacy-integration-tests/src/test/java/org/jboss/resteasy/test/validation/resource/ContextProvidersXop.java less more
0 package org.jboss.resteasy.test.validation.resource;
1
2 import javax.ws.rs.core.MediaType;
3 import javax.xml.bind.annotation.XmlAccessType;
4 import javax.xml.bind.annotation.XmlAccessorType;
5 import javax.xml.bind.annotation.XmlMimeType;
6 import javax.xml.bind.annotation.XmlRootElement;
7
8 @XmlRootElement
9 @XmlAccessorType(XmlAccessType.FIELD)
10 public class ContextProvidersXop {
11 @XmlMimeType(MediaType.APPLICATION_OCTET_STREAM)
12 private byte[] bytes;
13
14 public ContextProvidersXop(final byte[] bytes) {
15 this.bytes = bytes;
16 }
17
18 public ContextProvidersXop() {
19 }
20
21 public byte[] getBytes() {
22 return bytes;
23 }
24
25 public void setBytes(byte[] bytes) {
26 this.bytes = bytes;
27 }
28 }
+0
-22
testsuite/legacy-integration-tests/src/test/resources/arquillian.xml less more
0 <arquillian xmlns="http://jboss.org/schema/arquillian"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="
3 http://jboss.org/schema/arquillian
4 http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
5 <defaultProtocol type="Servlet 3.0" />
6 <container qualifier="jbossas-managed" default="true">
7 <configuration>
8 <property name="jbossHome">${jboss.home}</property>
9 <property name="serverConfig">standalone-resteasy-legacy.xml</property>
10 <!--<property name="javaVmArguments">-Xmx512m -XX:MaxPermSize=128m
11 -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y
12 -agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=y
13 </property>-->
14 <property name="javaVmArguments">-server -Xms256m -Xmx1G -Djboss.bind.address=${node} -Djboss.bind.address.management=${node} -Dnode=${node} -Dipv6=${ipv6} ${additionalJvmArgs} ${ipv6ArquillianSettings}</property>
15 <property name="managementAddress">${node}</property>
16 </configuration>
17 </container>
18 <extension qualifier="systemproperties">
19 <property name="prefix">org.jboss.resteasy.</property>
20 </extension>
21 </arquillian>
+0
-8
testsuite/legacy-integration-tests/src/test/resources/jboss-deployment-structure-bouncycastle.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <jboss-deployment-structure>
2 <deployment>
3 <dependencies>
4 <module name="org.bouncycastle" services="import"/>
5 </dependencies>
6 </deployment>
7 </jboss-deployment-structure>
+0
-12
testsuite/legacy-integration-tests/src/test/resources/jboss-deployment-structure-jackson-v1-jettison.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <jboss-deployment-structure>
2 <deployment>
3 <exclusions>
4 <module name="org.jboss.resteasy.resteasy-jackson2-provider"/>
5 </exclusions>
6 <dependencies>
7 <module name="org.jboss.resteasy.resteasy-jackson-provider" services="import"/>
8 <module name="org.jboss.resteasy.resteasy-jettison-provider" services="import"/>
9 </dependencies>
10 </deployment>
11 </jboss-deployment-structure>
+0
-11
testsuite/legacy-integration-tests/src/test/resources/jboss-deployment-structure-jackson-v1.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <jboss-deployment-structure>
2 <deployment>
3 <exclusions>
4 <module name="org.jboss.resteasy.resteasy-jackson2-provider"/>
5 </exclusions>
6 <dependencies>
7 <module name="org.jboss.resteasy.resteasy-jackson-provider" services="import"/>
8 </dependencies>
9 </deployment>
10 </jboss-deployment-structure>
+0
-8
testsuite/legacy-integration-tests/src/test/resources/jboss-deployment-structure-jackson-v2-jettison.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <jboss-deployment-structure>
2 <deployment>
3 <dependencies>
4 <module name="org.jboss.resteasy.resteasy-jettison-provider" services="import"/>
5 </dependencies>
6 </deployment>
7 </jboss-deployment-structure>
+0
-12
testsuite/legacy-integration-tests/src/test/resources/jboss-deployment-structure-no-jackson.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <jboss-deployment-structure>
2 <deployment>
3 <exclusions>
4 <module name="org.jboss.resteasy.resteasy-jackson2-provider"/>
5 <module name="org.jboss.resteasy.resteasy-jackson-provider"/>
6 </exclusions>
7 <dependencies>
8 <module name="org.jboss.resteasy.resteasy-jettison-provider" services="import"/>
9 </dependencies>
10 </deployment>
11 </jboss-deployment-structure>
+0
-13
testsuite/legacy-integration-tests/src/test/resources/log4j2.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <Configuration status="WARN">
2 <Appenders>
3 <Console name="Console" target="SYSTEM_OUT">
4 <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level [%logger{36}] (%t) %msg%n"/>
5 </Console>
6 </Appenders>
7 <Loggers>
8 <Root level="info">
9 <AppenderRef ref="Console"/>
10 </Root>
11 </Loggers>
12 </Configuration>
+0
-22
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/asynch/AsyncPostProcessingTestWeb.xml less more
0 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
3
4 <display-name>RESTEASY-736</display-name>
5
6 <servlet>
7 <servlet-name>Resteasy</servlet-name>
8 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher</servlet-class>
9 <init-param>
10 <param-name>javax.ws.rs.Application</param-name>
11 <param-value>org.jboss.resteasy.utils.TestApplication</param-value>
12 </init-param>
13 <async-supported>true</async-supported>
14 </servlet>
15
16 <servlet-mapping>
17 <servlet-name>Resteasy</servlet-name>
18 <url-pattern>/*</url-pattern>
19 </servlet-mapping>
20
21 </web-app>
+0
-21
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/asynch/CallbackTestWeb.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <web-app xmlns="http://java.sun.com/xml/ns/javaee"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
4 version="3.0">
5 <servlet>
6 <servlet-name>Resteasy</servlet-name>
7 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher</servlet-class>
8 <init-param>
9 <param-name>javax.ws.rs.Application</param-name>
10 <param-value>org.jboss.resteasy.utils.TestApplication</param-value>
11 </init-param>
12 <async-supported>true</async-supported>
13 </servlet>
14
15 <servlet-mapping>
16 <servlet-name>Resteasy</servlet-name>
17 <url-pattern>/*</url-pattern>
18 </servlet-mapping>
19
20 </web-app>
+0
-21
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/asynch/JaxrsAsyncServletWeb.xml less more
0 <!DOCTYPE web-app PUBLIC
1 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
2 "http://java.sun.com/dtd/web-app_2_3.dtd" >
3
4 <web-app>
5 <servlet>
6 <servlet-name>Resteasy</servlet-name>
7 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher</servlet-class>
8 <init-param>
9 <param-name>javax.ws.rs.Application</param-name>
10 <param-value>org.jboss.resteasy.test.asynch.resource.JaxrsAsyncServletApp</param-value>
11 </init-param>
12 <async-supported>true</async-supported>
13 </servlet>
14
15 <servlet-mapping>
16 <servlet-name>Resteasy</servlet-name>
17 <url-pattern>/*</url-pattern>
18 </servlet-mapping>
19
20 </web-app>
+0
-3
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/cdi/basic/BeanReaderWriterBeans.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
2 </beans>
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/cdi/basic/RESTEASY-1082.war less more
Binary diff not shown
+0
-18
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/cdi/basic/decoratorBeans.xml less more
0 <beans xmlns="http://java.sun.com/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
3
4 <interceptors>
5 <class>org.jboss.resteasy.test.cdi.basic.resource.DecoratorsResourceInterceptor</class>
6 </interceptors>
7
8 <decorators>
9 <class>org.jboss.resteasy.test.cdi.basic.resource.DecoratorsRequestFilterDecorator</class>
10 <class>org.jboss.resteasy.test.cdi.basic.resource.DecoratorsResponseFilterDecorator</class>
11 <class>org.jboss.resteasy.test.cdi.basic.resource.DecoratorsBookReaderInterceptorDecorator</class>
12 <class>org.jboss.resteasy.test.cdi.basic.resource.DecoratorsBookReaderDecorator</class>
13 <class>org.jboss.resteasy.test.cdi.basic.resource.DecoratorsBookWriterInterceptorDecorator</class>
14 <class>org.jboss.resteasy.test.cdi.basic.resource.DecoratorsBookWriterDecorator</class>
15 <class>org.jboss.resteasy.test.cdi.basic.resource.DecoratorsResourceDecorator</class>
16 </decorators>
17 </beans>
+0
-23
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/cdi/basic/ejbtest_web.xml less more
0 <web-app>
1
2 <display-name>Archetype Created Web Application</display-name>
3 <context-param>
4 <param-name>resteasy.jndi.resources</param-name>
5 <param-value>global/resteasy-ejb-test/EJBBookResource!org.jboss.resteasy.test.cdi.basic.resource.EJBLocalResource</param-value>
6 </context-param>
7
8 <servlet>
9 <servlet-name>Resteasy</servlet-name>
10 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
11 <init-param>
12 <param-name>javax.ws.rs.Application</param-name>
13 <param-value>org.jboss.resteasy.test.cdi.basic.resource.EJBApplication</param-value>
14 </init-param>
15 </servlet>
16
17 <servlet-mapping>
18 <servlet-name>Resteasy</servlet-name>
19 <url-pattern>/*</url-pattern>
20 </servlet-mapping>
21
22 </web-app>
+0
-3
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/client/javax.ws.rs.ext.Providers less more
0 org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter
1 org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor
2 org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor
+0
-30
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/basic/AppConfigWeb.xml less more
0 <!DOCTYPE web-app PUBLIC
1 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
2 "http://java.sun.com/dtd/web-app_2_3.dtd" >
3
4 <web-app>
5 <display-name>Archetype Created Web Application</display-name>
6 <context-param>
7 <param-name>resteasy.scan</param-name>
8 <param-value>false</param-value>
9 </context-param>
10
11 <context-param>
12 <param-name>javax.ws.rs.core.Application</param-name>
13 <param-value>org.jboss.resteasy.test.core.basic.resource.AppConfigApplication</param-value>
14 </context-param>
15
16 <listener>
17 <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
18 </listener>
19
20 <servlet>
21 <servlet-name>Resteasy</servlet-name>
22 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
23 </servlet>
24
25 <servlet-mapping>
26 <servlet-name>Resteasy</servlet-name>
27 <url-pattern>/*</url-pattern>
28 </servlet-mapping>
29 </web-app>
+0
-1
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/basic/ApplicationFilter.html less more
0 <h1>hello world</h1>
+0
-22
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/basic/ApplicationFilterWeb.xml less more
0 <?xml version="1.0"?>
1 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
2 "http://java.sun.com/dtd/web-app_2_3.dtd">
3
4 <web-app>
5 <filter>
6 <filter-name>Resteasy</filter-name>
7 <filter-class>
8 org.jboss.resteasy.plugins.server.servlet.FilterDispatcher
9 </filter-class>
10 <init-param>
11 <param-name>javax.ws.rs.Application</param-name>
12 <param-value>org.jboss.resteasy.utils.TestApplication</param-value>
13 </init-param>
14 </filter>
15
16 <filter-mapping>
17 <filter-name>Resteasy</filter-name>
18 <url-pattern>/*</url-pattern>
19 </filter-mapping>
20
21 </web-app>
+0
-11
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/basic/ApplicationWeb.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <web-app xmlns="http://java.sun.com/xml/ns/javaee"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
4 version="3.0">
5 <servlet-mapping>
6 <servlet-name>org.jboss.resteasy.test.core.basic.resource.ApplicationTestMappedApplication</servlet-name>
7 <url-pattern>/mapped/*</url-pattern>
8 </servlet-mapping>
9
10 </web-app>
+0
-1
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/basic/ContextIndex.html less more
0 hello world
+0
-66
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/basic/ContextWeb.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
2 "http://java.sun.com/dtd/web-app_2_3.dtd">
3 <web-app>
4 <display-name>Archetype RestEasy Web Application</display-name>
5
6 <!-- testing configuration -->
7 <context-param>
8 <param-name>resteasy.append.interceptor.precedence</param-name>
9 <param-value>END</param-value>
10 </context-param>
11 <context-param>
12 <param-name>resteasy.interceptor.before.precedence</param-name>
13 <param-value>ENCODER : BEFORE_ENCODER</param-value>
14 </context-param>
15
16 <context-param>
17 <param-name>resteasy.interceptor.after.precedence</param-name>
18 <param-value>ENCODER : AFTER_ENCODER</param-value>
19 </context-param>
20
21 <context-param>
22 <param-name>resteasy.media.type.mappings</param-name>
23 <param-value>xml : application/xml,
24 json : application/json
25 </param-value>
26 </context-param>
27
28 <context-param>
29 <param-name>resteasy.resources</param-name>
30 <param-value>org.jboss.resteasy.test.core.basic.resource.ContextService</param-value>
31 </context-param>
32
33 <context-param>
34 <param-name>resteasy.providers</param-name>
35 <param-value>org.jboss.resteasy.test.core.basic.resource.ContextAfterEncoderInterceptor,
36 org.jboss.resteasy.test.core.basic.resource.ContextEncoderInterceptor,
37 org.jboss.resteasy.test.core.basic.resource.ContextEndInterceptor,
38 org.jboss.resteasy.test.core.basic.resource.ContextBeforeEncoderInterceptor
39 </param-value>
40 </context-param>
41
42 <context-param>
43 <param-name>resteasy.servlet.mapping.prefix</param-name>
44 <param-value>/test</param-value>
45 </context-param>
46
47 <listener>
48 <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
49 </listener>
50
51 <servlet>
52 <servlet-name>Resteasy</servlet-name>
53 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
54 <init-param>
55 <param-name>servlet.greeting</param-name>
56 <param-value>servlet hello</param-value>
57 </init-param>
58 </servlet>
59
60 <servlet-mapping>
61 <servlet-name>Resteasy</servlet-name>
62 <url-pattern>/test/*</url-pattern>
63 </servlet-mapping>
64
65 </web-app>
+0
-28
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/basic/FileExtensionMapping.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
2 "http://java.sun.com/dtd/web-app_2_3.dtd">
3 <web-app>
4 <display-name>FileExtensionMappingTest</display-name>
5
6 <!-- testing configuration -->
7 <context-param>
8 <param-name>resteasy.media.type.mappings</param-name>
9 <param-value>txt : text/plain, html : text/html</param-value>
10 </context-param>
11
12 <context-param>
13 <param-name>javax.ws.rs.core.Application</param-name>
14 <param-value>org.jboss.resteasy.test.core.basic.resource.FileExtensionMappingApplication</param-value>
15 </context-param>
16
17 <servlet>
18 <servlet-name>Resteasy</servlet-name>
19 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
20 </servlet>
21
22 <servlet-mapping>
23 <servlet-name>Resteasy</servlet-name>
24 <url-pattern>/*</url-pattern>
25 </servlet-mapping>
26
27 </web-app>
+0
-54
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/servlet/FilterWeb.xml less more
0 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
3
4 <display-name>RESTEASY-903</display-name>
5
6 <!--filter>
7 <filter-name>Resteasy</filter-name>
8 <filter-class>
9 org.jboss.resteasy.plugins.server.servlet.FilterDispatcher
10 </filter-class>
11 <init-param>
12 <param-name>javax.ws.rs.Application</param-name>
13 <param-value>org.jboss.resteasy.resteasy903.TestApplication</param-value>
14 </init-param>
15 </filter>
16
17 <filter-mapping>
18 <filter-name>Resteasy</filter-name>
19 <url-pattern>/*</url-pattern>
20 <dispatcher>FORWARD</dispatcher>
21 <dispatcher>REQUEST</dispatcher>
22 </filter-mapping-->
23
24 <servlet>
25 <servlet-name>Resteasy</servlet-name>
26 <servlet-class>
27 org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
28 </servlet-class>
29 <init-param>
30 <param-name>javax.ws.rs.Application</param-name>
31 <param-value>org.jboss.resteasy.utils.TestApplication</param-value>
32 </init-param>
33 </servlet>
34
35 <servlet>
36 <servlet-name>Forward</servlet-name>
37 <servlet-class>
38 org.jboss.resteasy.test.core.servlet.resource.FilterForwardServlet
39 </servlet-class>
40 </servlet>
41
42 <servlet-mapping>
43 <servlet-name>Resteasy</servlet-name>
44 <url-pattern>/*</url-pattern>
45 </servlet-mapping>
46
47 <servlet-mapping>
48 <servlet-name>Forward</servlet-name>
49 <url-pattern>/forward/*</url-pattern>
50 </servlet-mapping>
51
52
53 </web-app>
+0
-30
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/servlet/ServletConfigWeb.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
2 "http://java.sun.com/dtd/web-app_2_3.dtd">
3 <web-app>
4 <display-name>Archetype RestEasy Web Application</display-name>
5 <context-param>
6 <param-name>javax.ws.rs.Application</param-name>
7 <param-value>org.jboss.resteasy.test.core.servlet.resource.ServletConfigApplication</param-value>
8 </context-param>
9
10 <context-param>
11 <param-name>context.greeting</param-name>
12 <param-value>context hello</param-value>
13 </context-param>
14
15 <servlet>
16 <servlet-name>Resteasy</servlet-name>
17 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
18 <init-param>
19 <param-name>servlet.greeting</param-name>
20 <param-value>servlet hello</param-value>
21 </init-param>
22 </servlet>
23
24 <servlet-mapping>
25 <servlet-name>Resteasy</servlet-name>
26 <url-pattern>/*</url-pattern>
27 </servlet-mapping>
28
29 </web-app>
+0
-3
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/servlet/ServletMappingJbossWeb.xml less more
0 <jboss-web>
1 <context-root>resteasy</context-root>
2 </jboss-web>
+0
-45
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/servlet/ServletMappingWeb.xml less more
0 <!DOCTYPE web-app PUBLIC
1 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
2 "http://java.sun.com/dtd/web-app_2_3.dtd" >
3
4 <web-app>
5 <display-name>Archetype Created Web Application</display-name>
6 <context-param>
7 <param-name>resteasy.scan</param-name>
8 <param-value>true</param-value>
9 </context-param>
10
11 <context-param>
12 <param-name>resteasy.servlet.mapping.prefix</param-name>
13 <param-value>/rest</param-value>
14 </context-param>
15
16 <filter>
17 <filter-name>MyFilter</filter-name>
18 <filter-class>org.jboss.resteasy.test.core.basic.resource.MyFilter</filter-class>
19 </filter>
20
21 <filter-mapping>
22 <filter-name>MyFilter</filter-name>
23 <url-pattern>/*</url-pattern>
24 </filter-mapping>
25
26 <listener>
27 <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
28 </listener>
29
30 <servlet>
31 <servlet-name>Resteasy</servlet-name>
32 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
33 </servlet>
34
35 <servlet-mapping>
36 <servlet-name>Resteasy</servlet-name>
37 <url-pattern>/rest/*</url-pattern>
38 </servlet-mapping>
39
40 <security-role>
41 <role-name>admin</role-name>
42 </security-role>
43
44 </web-app>
+0
-31
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/core/servlet/UndertowWeb.xml less more
0 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
3
4 <display-name>RESTEASY-903</display-name>
5
6 <servlet>
7 <servlet-name>Test</servlet-name>
8 <servlet-class>
9 org.jboss.resteasy.test.core.servlet.resource.UndertowServlet
10 </servlet-class>
11 </servlet>
12
13 <servlet>
14 <servlet-name>Forward</servlet-name>
15 <servlet-class>
16 org.jboss.resteasy.test.core.servlet.resource.FilterForwardServlet
17 </servlet-class>
18 </servlet>
19
20 <servlet-mapping>
21 <servlet-name>Test</servlet-name>
22 <url-pattern>/test/*</url-pattern>
23 </servlet-mapping>
24
25 <servlet-mapping>
26 <servlet-name>Forward</servlet-name>
27 <url-pattern>/forward/*</url-pattern>
28 </servlet-mapping>
29
30 </web-app>
+0
-2
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/providers/custom/FilterDispatcherManifest.MF less more
0 Manifest-Version: 1.0
1 Dependencies: org.apache.httpcomponents
+0
-31
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/providers/custom/FilterDispatcherManifestWeb.xml less more
0 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
3
4 <display-name>RESTEASY-903</display-name>
5
6 <servlet>
7 <servlet-name>Test</servlet-name>
8 <servlet-class>
9 org.jboss.resteasy.test.providers.custom.resource.FilterDispatcherServlet
10 </servlet-class>
11 </servlet>
12
13 <servlet>
14 <servlet-name>Forward</servlet-name>
15 <servlet-class>
16 org.jboss.resteasy.test.providers.custom.resource.FilterDispatcherForwardServlet
17 </servlet-class>
18 </servlet>
19
20 <servlet-mapping>
21 <servlet-name>Test</servlet-name>
22 <url-pattern>/test/*</url-pattern>
23 </servlet-mapping>
24
25 <servlet-mapping>
26 <servlet-name>Forward</servlet-name>
27 <url-pattern>/forward/*</url-pattern>
28 </servlet-mapping>
29
30 </web-app>
+0
-1
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/providers/custom/MissingProducer.Providers less more
0 org.jboss.resteasy.Missing
+0
-42
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/providers/jaxb/orders/order.xsd less more
0 <?xml version="1.0" encoding="UTF-8" ?>
1 <xs:schema targetNamespace="http://jboss.org/resteasy/test/providers/jaxb/generated/order" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:o="http://jboss.org/resteasy/test/providers/jaxb/generated/order" elementFormDefault="qualified">
2 <xs:simpleType name="stringtype">
3 <xs:restriction base="xs:string" />
4 </xs:simpleType>
5 <xs:simpleType name="inttype">
6 <xs:restriction base="xs:positiveInteger" />
7 </xs:simpleType>
8 <xs:simpleType name="dectype">
9 <xs:restriction base="xs:decimal" />
10 </xs:simpleType>
11 <xs:simpleType name="orderidtype">
12 <xs:restriction base="xs:string">
13 <xs:pattern value="[0-9]{6}" />
14 </xs:restriction>
15 </xs:simpleType>
16 <xs:complexType name="shiptotype">
17 <xs:sequence>
18 <xs:element name="name" type="o:stringtype" />
19 <xs:element name="address" type="o:stringtype" />
20 <xs:element name="city" type="o:stringtype" />
21 <xs:element name="country" type="o:stringtype" />
22 </xs:sequence>
23 </xs:complexType>
24 <xs:complexType name="itemtype">
25 <xs:sequence>
26 <xs:element name="title" type="o:stringtype" />
27 <xs:element name="note" type="o:stringtype" minOccurs="0" />
28 <xs:element name="quantity" type="o:inttype" />
29 <xs:element name="price" type="o:dectype" />
30 </xs:sequence>
31 </xs:complexType>
32 <xs:complexType name="ordertype">
33 <xs:sequence>
34 <xs:element name="person" type="o:stringtype" />
35 <xs:element name="shipto" type="o:shiptotype" />
36 <xs:element name="item" maxOccurs="unbounded" type="o:itemtype" />
37 </xs:sequence>
38 <xs:attribute name="orderid" type="o:orderidtype" use="required" />
39 </xs:complexType>
40 <xs:element name="order" type="o:ordertype" />
41 </xs:schema>
+0
-22
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/providers/jaxb/orders/order_123.xml less more
0 <?xml version="1.0" encoding="UTF-8"?>
1 <order orderid="123" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:noNamespaceSchemaLocation="order.xsd">
3 <person>Ryan J. McDonough</person>
4 <shipto>
5 <name>Bill Burke</name>
6 <address>Langgt 23</address>
7 <city>4000 Stavanger</city>
8 <country>USA</country>
9 </shipto>
10 <item>
11 <title>Empire Burlesque</title>
12 <note>Special Edition</note>
13 <quantity>1</quantity>
14 <price>10.90</price>
15 </item>
16 <item>
17 <title>Hide your heart</title>
18 <quantity>1</quantity>
19 <price>9.90</price>
20 </item>
21 </order>
+0
-1
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/providers/multipart/HeaderFlushedOutputStreamTestData.txt less more
0 hello world
+0
-1
testsuite/legacy-integration-tests/src/test/resources/org/jboss/resteasy/test/resource/param/javax.ws.rs.ext.Providers less more
0 org.jboss.resteasy.plugins.providers.SerializableProvider
+0
-16
testsuite/legacy-integration-tests/src/test/scripts/legacy.groovy less more
0 def root = new XmlParser().parse(inputFile)
1
2 def subsystems = root.profile.subsystem
3 def s = subsystems.find{it.name().getNamespaceURI().contains('urn:jboss:domain:ee:')}
4 def globalModules = s.appendNode('global-modules')
5 globalModules.appendNode('module', ['name':'org.jboss.resteasy.resteasy-legacy','services':'true'])
6
7 /**
8 * Save the configuration to a new file
9 */
10
11 def writer = new StringWriter()
12 writer.println('<?xml version="1.0" encoding="UTF-8"?>')
13 new XmlNodePrinter(new PrintWriter(writer)).print(root)
14 def f = new File(outputFile)
15 f.write(writer.toString())
0 <?xml version="1.0" encoding="UTF-8"?>
1 <!--
2 Licensed under the Apache License, Version 2.0 (the
3 "License"); you may not use this file except in compliance
4 with the License. You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing,
9 software distributed under the License is distributed on an
10 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11 KIND, either express or implied. See the License for the
12 specific language governing permissions and limitations
13 under the License.
14 -->
15 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
16 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
17 <modelVersion>4.0.0</modelVersion>
18
19 <parent>
20 <groupId>org.jboss.resteasy</groupId>
21 <artifactId>resteasy-testsuite</artifactId>
22 <version>3.5.0.Final</version>
23 <relativePath>../</relativePath>
24 </parent>
25
26 <artifactId>microprofile-tck-runner</artifactId>
27 <name>MicroProfile Rest Client TCK</name>
28 <packaging>jar</packaging>
29
30 <properties>
31 <version.arquillian>1.1.13.Final</version.arquillian>
32 <version.microprofile.restclient>1.0</version.microprofile.restclient>
33 <version.microprofile-config>1.2</version.microprofile-config>
34 <version.wildfly-microprofile-config>1.2.1</version.wildfly-microprofile-config>
35 </properties>
36
37 <dependencies>
38
39 <!-- REST Client implementation-->
40
41 <dependency>
42 <groupId>org.jboss.resteasy</groupId>
43 <artifactId>resteasy-client</artifactId>
44 <scope>test</scope>
45 <version>${project.version}</version>
46 </dependency>
47
48 <dependency>
49 <groupId>org.jboss.resteasy</groupId>
50 <artifactId>resteasy-cdi</artifactId>
51 <scope>test</scope>
52 <version>${project.version}</version>
53 </dependency>
54
55 <!-- Config Implementation -->
56
57 <dependency>
58 <groupId>org.eclipse.microprofile.config</groupId>
59 <artifactId>microprofile-config-api</artifactId>
60 <version>${version.microprofile-config}</version>
61 <scope>test</scope>
62 </dependency>
63
64 <dependency>
65 <groupId>org.wildfly</groupId>
66 <artifactId>wildfly-microprofile-config-implementation</artifactId>
67 <version>${version.wildfly-microprofile-config}</version>
68 <scope>test</scope>
69 </dependency>
70
71 <!-- Microprofile TCK tests -->
72
73 <dependency>
74 <groupId>org.eclipse.microprofile.rest.client</groupId>
75 <artifactId>microprofile-rest-client-tck</artifactId>
76 <version>${version.microprofile.restclient}</version>
77 <scope>test</scope>
78 </dependency>
79
80 <!-- TCK Support -->
81
82 <dependency>
83 <groupId>org.slf4j</groupId>
84 <artifactId>slf4j-jdk14</artifactId>
85 <version>1.7.25</version>
86 <scope>test</scope>
87 </dependency>
88
89 <dependency>
90 <groupId>com.github.tomakehurst</groupId>
91 <artifactId>wiremock</artifactId>
92 <version>2.10.1</version>
93 <scope>test</scope>
94 </dependency>
95
96 <dependency>
97 <groupId>org.jboss.arquillian.testng</groupId>
98 <artifactId>arquillian-testng-container</artifactId>
99 <scope>test</scope>
100 </dependency>
101
102 <dependency>
103 <groupId>org.jboss.weld.se</groupId>
104 <artifactId>weld-se-core</artifactId>
105 <version>2.4.5.Final</version>
106 <scope>test</scope>
107 </dependency>
108
109 <dependency>
110 <groupId>org.jboss.arquillian.container</groupId>
111 <artifactId>arquillian-weld-embedded</artifactId>
112 <version>2.0.0.Beta5</version>
113 <scope>test</scope>
114 </dependency>
115
116 <dependency>
117 <groupId>javax.json</groupId>
118 <artifactId>javax.json-api</artifactId>
119 <version>1.0</version>
120 <scope>test</scope>
121 </dependency>
122
123 <dependency>
124 <groupId>org.jboss.resteasy</groupId>
125 <artifactId>resteasy-json-p-provider</artifactId>
126 <scope>test</scope>
127 <version>${project.version}</version>
128 </dependency>
129
130 <dependency>
131 <groupId>org.glassfish</groupId>
132 <artifactId>javax.json</artifactId>
133 <version>1.0.4</version>
134 <scope>test</scope>
135 </dependency>
136 </dependencies>
137
138 <build>
139 <plugins>
140 <plugin>
141 <groupId>uk.co.deliverymind</groupId>
142 <artifactId>wiremock-maven-plugin</artifactId>
143 <version>2.7.0</version>
144 <executions>
145 <execution>
146 <phase>generate-test-sources</phase>
147 <goals>
148 <goal>run</goal>
149 </goals>
150 <configuration>
151 <dir>target/classes</dir>
152 <params>--port=8765 --verbose</params>
153 </configuration>
154 </execution>
155 </executions>
156 </plugin>
157
158 <plugin>
159 <groupId>org.apache.maven.plugins</groupId>
160 <artifactId>maven-surefire-plugin</artifactId>
161 <version>2.20</version>
162 <configuration>
163
164 <dependenciesToScan>
165 <dependency>org.eclipse.microprofile.rest.client:microprofile-rest-client-tck</dependency>
166 </dependenciesToScan>
167 <excludes>
168
169 <!--
170 the dependency on MP config in the resteasy client is not desireable
171 this requires further thought
172 -->
173 <exclude>org.eclipse.microprofile.rest.client.tck.DefaultExceptionMapperConfigTest</exclude>
174
175 <!-- Challenged, see https://github.com/eclipse/microprofile-rest-client/pull/69 -->
176 <exclude>org.eclipse.microprofile.rest.client.tck.InvokeWithJsonPProviderTest</exclude>
177 <exclude>org.eclipse.microprofile.rest.client.tck.InvokeWithBuiltProvidersTest</exclude>
178 <exclude>org.eclipse.microprofile.rest.client.tck.InvokeWithRegisteredProvidersTest</exclude>
179 <exclude>org.eclipse.microprofile.rest.client.tck.cditests.CDIInvokeWithRegisteredProvidersTest</exclude>
180 </excludes>
181 </configuration>
182 </plugin>
183
184 </plugins>
185 </build>
186 </project>
22 <parent>
33 <groupId>org.jboss.resteasy</groupId>
44 <artifactId>resteasy-jaxrs-all</artifactId>
5 <version>3.1.4.Final</version>
5 <version>3.5.0.Final</version>
66 <relativePath>../pom.xml</relativePath>
77 </parent>
88 <name>RESTEasy Main testsuite</name>
99 <description/>
1010 <modelVersion>4.0.0</modelVersion>
1111 <packaging>pom</packaging>
12
12
1313 <artifactId>resteasy-testsuite</artifactId>
1414
1515 <properties>
1616 <version.resteasy.testsuite>${project.version}</version.resteasy.testsuite>
1717 <additional.surefire.excluded.groups></additional.surefire.excluded.groups>
18 <securityManagerArg></securityManagerArg>
18 <!-- default value required for cmd-line -->
19 <securityManagerArg>-DSECMGR="false"</securityManagerArg>
1920 <!-- Optional property for jacoco report generation -->
2021 <sources.path></sources.path>
2122 <jacoco.agent></jacoco.agent>
2223 <additionalJvmArgs></additionalJvmArgs>
24 <ee8.preview.mode>true</ee8.preview.mode>
2325 </properties>
2426
2527 <build>
2931 <configuration>
3032 <failIfNoTests>false</failIfNoTests>
3133 <systemPropertyVariables>
32 <additionalJvmArgs>${additionalJvmArgs} ${securityManagerArg} ${modular.jdk.props}</additionalJvmArgs>
34 <securityManagerArg>${securityManagerArg}</securityManagerArg>
35 <additionalJvmArgs>${additionalJvmArgs}</additionalJvmArgs>
3336 <ipv6>false</ipv6>
3437 <ipv6ArquillianSettings></ipv6ArquillianSettings>
3538 <node>127.0.0.1</node>
6770 <modules>
6871 <module>arquillian-utils</module>
6972 <module>unit-tests</module>
70 <module>legacy-integration-tests</module>
7173 <module>integration-tests</module>
7274 <module>integration-tests-spring</module>
75 <module>microprofile-tck</module>
7376 </modules>
77 </profile>
78 <!-- Enable Jaxrs 2.0 mode for the integration tests. -->
79 <profile>
80 <id>jaxrs20</id>
81 <activation>
82 <property>
83 <name>jaxrs20</name>
84 </property>
85 </activation>
86 <properties>
87 <ee8.preview.mode>false</ee8.preview.mode>
88 <additional.surefire.excluded.groups>org.jboss.resteasy.category.Jaxrs21</additional.surefire.excluded.groups>
89 </properties>
7490 </profile>
7591 <!-- Forward compatibility: use EAP 7.0.0.GA and newer Client from CP stream (e.g. client from RESTEasy delivered by EAP 7.0.2 -->
7692 <profile>
8399 <modules>
84100 <module>arquillian-utils</module>
85101 <module>unit-tests</module>
86 <!-- Uncomment module below when EAP/Widlfly with Resteasy 3.1 is released -->
87 <!-- <module>legacy-integration-tests</module>-->
88102 <module>integration-tests</module>
89103 <module>integration-tests-spring</module>
90104 </modules>
164178 <configuration>
165179 <testFailureIgnore>true</testFailureIgnore>
166180 <systemPropertyVariables>
167 <additionalJvmArgs>${additionalJvmArgs} ${securityManagerArg}</additionalJvmArgs>
181 <securityManagerArg>${securityManagerArg}</securityManagerArg>
182 <additionalJvmArgs>${additionalJvmArgs}</additionalJvmArgs>
168183 <ipv6>true</ipv6>
169184 <ipv6ArquillianSettings>-Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=true</ipv6ArquillianSettings>
170185 <node>::1</node>
205220 </property>
206221 </activation>
207222 <properties>
208 <securityManagerArg>-Djava.security.manager</securityManagerArg>
223 <securityManagerArg>-secmgr</securityManagerArg>
209224 </properties>
210225 </profile>
211226 <!-- This profile creates custom server configuration file with configured Elytron subsystem -->
269284 <artifactId>maven-surefire-plugin</artifactId>
270285 <configuration combine.children="append">
271286 <systemPropertyVariables>
272 <additionalJvmArgs>${additionalJvmArgs} ${securityManagerArg}</additionalJvmArgs>
287 <securityManagerArg>${securityManagerArg}</securityManagerArg>
288 <additionalJvmArgs>${additionalJvmArgs}</additionalJvmArgs>
273289 <jboss.server.config.file.name>standalone-full-elytron.xml</jboss.server.config.file.name>
274 <additionalJvmArgs>${securityManagerArg} ${modular.jdk.props}</additionalJvmArgs>
275290 <ipv6>false</ipv6>
276291 <ipv6ArquillianSettings></ipv6ArquillianSettings>
277292 <node>127.0.0.1</node>
66 <parent>
77 <groupId>org.jboss.resteasy</groupId>
88 <artifactId>resteasy-testsuite</artifactId>
9 <version>3.1.4.Final</version>
9 <version>3.5.0.Final</version>
1010 <relativePath>../pom.xml</relativePath>
1111 </parent>
1212
2323
2424 <dependency>
2525 <groupId>org.jboss.resteasy</groupId>
26 <artifactId>resteasy-legacy</artifactId>
26 <artifactId>resteasy-jaxrs</artifactId>
2727 <version>${version.resteasy.testsuite}</version>
2828 </dependency>
2929
99 import javax.ws.rs.client.Entity;
1010 import javax.ws.rs.core.Response;
1111
12 import org.jboss.logging.Logger;
1213 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
1314 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
1415 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
3233 private static Thread t;
3334 private static ServerSocket ss;
3435 private static Socket s;
36 private final static Logger logger = Logger.getLogger(ChunkedTransferEncodingUnitTest.class);
3537
3638 private static String RESPONSE_200 =
3739 "HTTP/1.1 200 OK\r\n" +
5860 @Before
5961 public void before() throws Exception
6062 {
61 int[] chars = new int[1024];
63 final int[] chars = new int[1024];
6264
6365 t = new Thread() {
6466 public void run() {
8587 }
8688 return;
8789 } catch (IOException e) {
88 e.printStackTrace();
90 logger.error(e.getMessage(), e);
8991 }
9092 }
9193 };
157159 response.close();
158160 client.close();
159161 }
160 }
162 }
1010 import javax.ws.rs.core.Configuration;
1111 import javax.ws.rs.core.Feature;
1212 import javax.ws.rs.core.FeatureContext;
13 import javax.ws.rs.core.Link;
14 import javax.ws.rs.core.MediaType;
1315 import javax.ws.rs.core.Response;
14
16 import javax.ws.rs.ext.RuntimeDelegate;
1517
1618 import static org.jboss.resteasy.test.TestPortProvider.generateURL;
1719
5052
5153 }
5254
55
5356 /**
5457 * @tpTestDetails Create client with custom property, check that property is set and remove the property
5558 * from client configuration
97100 client.close();
98101 Response response = base.request().get();
99102 }
103 /**
104 * @tpTestDetails Create link instance with jaxrs spec apis to check there is no NPE thrown
105 * @tpPassCrit Link object is successfully created
106 * @tpSince RESTEasy 3.5
107 */
108 @Test
109 public void testLinkBuilder() throws Exception {
110 Link link = RuntimeDelegate.getInstance().createLinkBuilder()
111 .baseUri("http://jboss.org/resteasy").rel("relation relation2").title("titleX")
112 .param("param1", "value1").param("param2", "value2")
113 .type(MediaType.APPLICATION_OCTET_STREAM).build();
114 Assert.assertNotNull("Build link failed", link);
115 }
100116
101117 public static class FeatureReturningFalse implements Feature {
102118 @Override
00 package org.jboss.resteasy.test.client;
11
2 import org.jboss.resteasy.client.LinkHeaderDelegate;
3 import org.jboss.resteasy.client.Link;
4 import org.jboss.resteasy.client.LinkHeader;
2 import org.jboss.resteasy.plugins.delegates.LinkHeaderDelegate;
3 import org.jboss.resteasy.spi.Link;
4 import org.jboss.resteasy.spi.LinkHeader;
55 import org.junit.Assert;
66 import org.junit.Test;
77
00 package org.jboss.resteasy.test.client;
11
2 import org.jboss.resteasy.client.jaxrs.engines.SelfExpandingBufferredInputStream;
2 import org.jboss.resteasy.client.core.SelfExpandingBufferredInputStream;
33 import org.junit.Before;
44 import org.junit.Test;
55
00 package org.jboss.resteasy.test.crypto;
11
2 import org.jboss.logging.Logger;
3 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
2 import org.apache.logging.log4j.LogManager;
3 import org.jboss.resteasy.logging.Logger;
44 import org.jboss.resteasy.security.doseta.DKIMSignature;
55 import org.jboss.resteasy.security.doseta.DosetaKeyRepository;
66 import org.jboss.resteasy.security.doseta.Verification;
2626 * @tpSince RESTEasy 3.0.16
2727 */
2828 public class LocalTest {
29 protected static final LogMessages logger = Logger.getMessageLogger(LogMessages.class, LocalTest.class.getName());
29 protected static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(LocalTest.class.getName());
3030 public static KeyPair keys;
3131 public static DosetaKeyRepository repository;
3232 static final String filePath = TestUtil.getResourcePath(LocalTest.class, "LocalTest.jks");
3434
3535 @BeforeClass
3636 public static void setup() throws Exception {
37 Logger.setLoggerType(Logger.LoggerType.JUL);
3738 repository = new DosetaKeyRepository();
3839 repository.setKeyStoreFile(filePath);
3940 repository.setKeyStorePassword("password");
22 import org.jboss.resteasy.core.interception.ClientResponseFilterRegistry;
33 import org.jboss.resteasy.core.interception.ContainerResponseFilterRegistry;
44 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
5 import org.jboss.resteasy.core.interception.LegacyPrecedence;
56 import org.jboss.resteasy.spi.ResteasyProviderFactory;
67 import org.jboss.resteasy.test.interception.resource.PriorityClientRequestFilter1;
78 import org.jboss.resteasy.test.interception.resource.PriorityClientRequestFilter2;
3536 */
3637 @Test
3738 public void testPriority() throws Exception {
38 ContainerResponseFilterRegistry containerResponseFilterRegistry = new ContainerResponseFilterRegistry(new ResteasyProviderFactory());
39 ContainerResponseFilterRegistry containerResponseFilterRegistry = new ContainerResponseFilterRegistry(new ResteasyProviderFactory(), new LegacyPrecedence());
3940 ClientResponseFilterRegistry clientResponseFilterRegistry = new ClientResponseFilterRegistry(new ResteasyProviderFactory());
4041 JaxrsInterceptorRegistry<ClientRequestFilter> clientRequestFilterRegistry = new JaxrsInterceptorRegistry<ClientRequestFilter>(new ResteasyProviderFactory(), ClientRequestFilter.class);
4142
00 package org.jboss.resteasy.test.providers;
11
2 import com.sun.istack.NotNull;
3 import com.sun.istack.Nullable;
42 import com.sun.xml.bind.api.ClassResolver;
53 import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
64 import org.apache.logging.log4j.LogManager;
00 package org.jboss.resteasy.test.providers;
11
2 import org.jboss.logging.Logger;
2 import org.jboss.resteasy.logging.Logger;
33 import org.jboss.resteasy.plugins.providers.jaxb.XmlNamespacePrefixMapper;
4 import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
54 import org.jboss.resteasy.test.providers.resource.jaxbNameSpacePrefix.JaxbNameSpacePrefixItems;
65 import org.jboss.resteasy.test.providers.resource.jaxbNameSpacePrefix.JaxbNameSpacePrefixPurchaseOrderType;
76 import org.jboss.resteasy.test.providers.resource.jaxbNameSpacePrefix.JaxbNameSpacePrefixItem;
2322 */
2423 public class JaxbNamespacePrefixTest {
2524
26 private static final LogMessages logger = Logger.getMessageLogger(LogMessages.class, JaxbNamespacePrefixTest.class.getName());
25 private static final Logger logger = Logger.getLogger(JaxbNamespacePrefixTest.class);
2726
2827 /**
2928 * @tpTestDetails Create xml schema from provided class and set "namespacePrefixMapper" for the Marshaller
0 package org.jboss.resteasy.test.providers;
1
2 import java.lang.annotation.Annotation;
3 import java.lang.reflect.Type;
4
5 import javax.annotation.Priority;
6 import javax.ws.rs.core.Response;
7 import javax.ws.rs.ext.ExceptionMapper;
8 import javax.ws.rs.ext.ParamConverter;
9 import javax.ws.rs.ext.ParamConverterProvider;
10 import javax.ws.rs.ext.Provider;
11
12 import org.jboss.resteasy.spi.ResteasyProviderFactory;
13 import org.junit.Assert;
14 import org.junit.Test;
15
16
17 /**
18 * @tpSubChapter Providers
19 * @tpChapter Unit tests
20 * @tpTestCaseDetails Correct storage of ParamConverterProviders and ExceptionMappers of equal @Priority
21 * @tpSince RESTEasy 3.5
22 */
23 public class PriorityEqualityTest {
24
25 public static class TestException extends Exception {
26 private static final long serialVersionUID = 1L;
27 }
28
29 @Provider
30 @Priority(20)
31 public static class ExceptionMapper1 implements ExceptionMapper<TestException> {
32
33 @Override
34 public Response toResponse(TestException exception) {
35 return Response.ok().status(444).entity("1").build();
36 }
37 }
38
39 @Provider
40 @Priority(20)
41 public static class ExceptionMapper2 implements ExceptionMapper<TestException> {
42
43 @Override
44 public Response toResponse(TestException exception) {
45 return Response.ok().status(444).entity("BBB").build();
46 }
47 }
48
49 public static class Foo {
50 private String foo;
51 public Foo(String foo) {this.foo = foo;}
52 public String getFoo() {return foo;}
53 }
54
55 public static class FooParamConverter implements ParamConverter<Foo> {
56 private String foo;
57
58 public FooParamConverter(String foo) {
59 this.foo = foo;
60 }
61
62 @Override
63 public Foo fromString(String value)
64 {
65 return new Foo(foo);
66 }
67
68 @Override
69 public String toString(Foo value)
70 {
71 return value.getFoo();
72 }
73 }
74
75 @Provider
76 @Priority(20)
77 public static class ParamConverterProvider1 implements ParamConverterProvider {
78
79 @SuppressWarnings("unchecked")
80 @Override
81 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
82 return (ParamConverter<T>) new FooParamConverter("1");
83 }
84 }
85
86 @Provider
87 @Priority(20)
88 public static class ParamConverterProvider2 implements ParamConverterProvider {
89
90 @SuppressWarnings("unchecked")
91 @Override
92 public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
93 return (ParamConverter<T>) new FooParamConverter("2");
94 }
95 }
96
97 //////////////////////////////////////////////////////////////////////////////
98
99 /**
100 * @tpTestDetails ResteasyProviderFactory should store multiple ParamConvertProviders
101 * with the same @Priority.
102 * @tpSince RESTEasy 3.5
103 */
104 @Test
105 public void testParamConverterProvidersFromClass() throws Exception {
106 ResteasyProviderFactory factory = new ResteasyProviderFactory();
107 factory.register(ParamConverterProvider1.class);
108 factory.register(ParamConverterProvider2.class);
109 Assert.assertEquals(2, factory.getParamConverterProviders().size());
110 }
111
112 /**
113 * @tpTestDetails ResteasyProviderFactory should store multiple ParamConvertProviders
114 * with the same @Priority.
115 * @tpSince RESTEasy 3.5
116 */
117 @Test
118 public void testParamConverterProvidersObjects() throws Exception {
119 ResteasyProviderFactory factory = new ResteasyProviderFactory();
120 factory.registerProviderInstance(new ParamConverterProvider1());
121 factory.registerProviderInstance(new ParamConverterProvider2());
122 Assert.assertEquals(2, factory.getParamConverterProviders().size());
123 }
124
125 /**
126 * @tpTestDetails ResteasyProviderFactory should store a single ExceptionMapper for
127 * a given Exception and @Priority.
128 * @tpSince RESTEasy 3.5
129 */
130 @Test
131 public void testExceptionMappersFromClass() throws Exception {
132 ResteasyProviderFactory factory = new ResteasyProviderFactory();
133 factory.register(ExceptionMapper1.class);
134 factory.register(ExceptionMapper2.class);
135 Assert.assertEquals(1, factory.getExceptionMappers().size());
136 }
137
138 /**
139 * @tpTestDetails ResteasyProviderFactory should store a single ExceptionMapper for
140 * a given Exception and @Priority.
141 * @tpSince RESTEasy 3.5
142 */
143 @Test
144 public void testExceptionObjects() throws Exception {
145 ResteasyProviderFactory factory = new ResteasyProviderFactory();
146 factory.registerProviderInstance(new ExceptionMapper1());
147 factory.registerProviderInstance(new ExceptionMapper2());
148 Assert.assertEquals(1, factory.getExceptionMappers().size());
149 }
150 }
00 package org.jboss.resteasy.test.providers;
11
2 import org.jboss.resteasy.plugins.providers.DefaultTextPlain;
2 import org.jboss.resteasy.plugins.providers.DefaultBooleanWriter;
33 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
44 import org.jboss.resteasy.spi.ResteasyProviderFactory;
55 import org.jboss.resteasy.test.providers.resource.ProviderFactoryPrecedenceBase;
6666
6767 MessageBodyWriter<Boolean> writer = factory.getMessageBodyWriter(Boolean.class, null, null, new MediaType("text", "plain"));
6868 Assert.assertNotNull("No writer exists for the given media type", writer);
69 Assert.assertEquals("The type of the writer is incorrect", writer.getClass(), DefaultTextPlain.class);
69 Assert.assertEquals("The type of the writer is incorrect", writer.getClass(), DefaultBooleanWriter.class);
7070 }
7171
7272 /**
127127 }
128128
129129 private void verifyPlainWriter(ResteasyProviderFactory factory) {
130 MessageBodyWriter writer2 = factory.getMessageBodyWriter(Boolean.class, null, null, MediaType.TEXT_PLAIN_TYPE);
130 MessageBodyWriter writer2 = factory.getMessageBodyWriter(Character.class, null, null, MediaType.TEXT_PLAIN_TYPE);
131131 Assert.assertNotNull("No writer exists for the given media type", writer2);
132132 Assert.assertTrue("The type of the writer is incorrect", writer2 instanceof ProviderFactoryPrecendencePlainTextWriter);
133133 }
00 package org.jboss.resteasy.test.providers;
11
22 import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
3 import org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor;
4 import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
5 import org.jboss.resteasy.spi.ResteasyDeployment;
36 import org.jboss.resteasy.spi.ResteasyProviderFactory;
7 import org.jboss.resteasy.test.providers.namespace.mapping.NamespaceMappingResource;
48 import org.jboss.resteasy.test.providers.resource.ProviderFactoryStrParamUnmarshaller;
59 import org.junit.Assert;
610 import org.junit.Before;
711 import org.junit.Test;
812
913 import javax.ws.rs.Priorities;
14 import javax.ws.rs.WebApplicationException;
1015 import javax.ws.rs.container.ContainerRequestContext;
1116 import javax.ws.rs.container.ContainerRequestFilter;
1217 import javax.ws.rs.container.ContainerResponseContext;
1318 import javax.ws.rs.container.ContainerResponseFilter;
19 import javax.ws.rs.container.DynamicFeature;
20 import javax.ws.rs.container.ResourceInfo;
21 import javax.ws.rs.core.FeatureContext;
22 import javax.ws.rs.ext.Provider;
23 import javax.ws.rs.ext.ReaderInterceptor;
24 import javax.ws.rs.ext.ReaderInterceptorContext;
25
26 import java.io.IOException;
1427 import java.lang.reflect.Field;
1528 import java.sql.Date;
1629 import java.util.List;
90103 Assert.assertEquals(priorityOverride, order);
91104 }
92105
106 @Test
107 public void testDeploymentStart()
108 {
109 ResteasyProviderFactory orig = ResteasyProviderFactory.peekInstance();
110 try
111 {
112 ResteasyProviderFactory.setInstance(null);
113
114 ResteasyProviderFactory rpf1 = new ResteasyProviderFactory();
115 RegisterBuiltin.register(rpf1);
116 rpf1.registerProvider(MyInterceptor.class);
117 ResteasyDeployment dep1 = new ResteasyDeployment();
118 dep1.setProviderFactory(rpf1);
119 dep1.setDeploymentSensitiveFactoryEnabled(true);
120 dep1.start();
121
122 ResteasyProviderFactory rpf2 = new ResteasyProviderFactory();
123 RegisterBuiltin.register(rpf2);
124 rpf2.register(new DynamicFeature()
125 {
126 @Override
127 public void configure(ResourceInfo resourceInfo, FeatureContext context)
128 {
129 if (ResteasyProviderFactory.getInstance().isRegistered(MyInterceptor.class))
130 {
131 Assert.fail("Second deployment consuming provider factory from first deployment");
132 }
133
134 }
135 });
136 ResteasyDeployment dep2 = new ResteasyDeployment();
137 dep2.setProviderFactory(rpf2);
138 dep2.setDeploymentSensitiveFactoryEnabled(true);
139 dep2.getResourceClasses().add(NamespaceMappingResource.class.getName());
140 dep2.start();
141
142 dep1.stop();
143 dep2.stop();
144 }
145 finally
146 {
147 ResteasyProviderFactory.setInstance(orig);
148 }
149 }
150
151 @Provider
152 public static class MyInterceptor implements ReaderInterceptor
153 {
154 @Override
155 public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException
156 {
157 // TODO Auto-generated method stub
158 return null;
159 }
160 }
93161 }
0 package org.jboss.resteasy.test.providers.sse;
1
2 import java.util.ArrayList;
3 import java.util.List;
4
5 import javax.ws.rs.core.GenericEntity;
6 import javax.ws.rs.core.GenericType;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.sse.OutboundSseEvent;
9
10 import org.jboss.resteasy.plugins.providers.sse.OutboundSseEventImpl;
11 import org.jboss.resteasy.test.providers.resource.ContractsData;
12 import org.junit.Assert;
13 import org.junit.Test;
14
15 /***
16 *
17 * @author Nicolas NESMON
18 *
19 */
20 public class OutboundSseEventImplTest {
21
22 @Test
23 public void Should_ReturnTextPlainMediaType_When_MediaTypeIsNotSet() throws Exception {
24 OutboundSseEvent outboundSseEvent = new OutboundSseEventImpl.BuilderImpl().comment("comment").build();
25 Assert.assertEquals(MediaType.TEXT_PLAIN_TYPE, outboundSseEvent.getMediaType());
26 }
27
28 @Test(expected = NullPointerException.class)
29 public void Should_ThrowNullPointerException_When_MediaTypeIsNull() throws Exception {
30 new OutboundSseEventImpl.BuilderImpl().mediaType(null).build();
31 }
32
33 @Test
34 public void testGetOutboundSseEventGetMediaType() throws Exception {
35 OutboundSseEvent outboundSseEvent = new OutboundSseEventImpl.BuilderImpl()
36 .mediaType(MediaType.APPLICATION_XML_TYPE).comment("comment").build();
37 Assert.assertEquals(MediaType.APPLICATION_XML_TYPE, outboundSseEvent.getMediaType());
38 }
39
40 @Test()
41 public void Should_ThrowNullPointerException_When_DataIsNull() throws Exception {
42 OutboundSseEvent.Builder builder = new OutboundSseEventImpl.BuilderImpl();
43 try {
44 builder.data(String.class, null);
45 Assert.fail("A NullPointerException was expected");
46 } catch (NullPointerException e) {
47 }
48 try {
49 builder.data(new GenericType<String>() {
50 }, null);
51 Assert.fail("A NullPointerException was expected");
52 } catch (NullPointerException e) {
53 }
54 try {
55 builder.data(null);
56 Assert.fail("A NullPointerException was expected");
57 } catch (NullPointerException e) {
58 }
59 }
60
61 @Test()
62 public void Should_ThrowNullPointerException_When_TypeOrGenericTypeIsNull() throws Exception {
63 OutboundSseEvent.Builder builder = new OutboundSseEventImpl.BuilderImpl();
64 try {
65 builder.data((Class<?>) null, "data");
66 Assert.fail("A NullPointerException was expected");
67 } catch (NullPointerException e) {
68 }
69 try {
70 builder.data((GenericType<?>) null, "data");
71 Assert.fail("A NullPointerException was expected");
72 } catch (NullPointerException e) {
73 }
74 }
75
76 @Test(expected = IllegalArgumentException.class)
77 public void Should_ThrowIllegalArgumentException_When_CommentAndDataAreNull() throws Exception {
78 OutboundSseEvent.Builder builder = new OutboundSseEventImpl.BuilderImpl();
79 builder.comment("comment").build();
80 builder.comment(null).build();
81 }
82
83 @Test()
84 public void Should_ReturnTheExactDataType_When_DataIsAGenericEntity() throws Exception {
85 GenericEntity<List<String>> genericEntity = new GenericEntity<List<String>>(new ArrayList<>()) {
86 };
87 OutboundSseEvent outboundSseEvent = new OutboundSseEventImpl.BuilderImpl().data(genericEntity).build();
88 Assert.assertEquals(ArrayList.class, genericEntity.getRawType());
89 Assert.assertEquals(genericEntity.getRawType(), outboundSseEvent.getType());
90 Assert.assertEquals(genericEntity.getType(), outboundSseEvent.getGenericType());
91 }
92
93 @Test
94 public void testGetOutboundSseEventGetType() throws Exception {
95 OutboundSseEvent outboundSseEvent = new OutboundSseEventImpl.BuilderImpl()
96 .data(ContractsData.class, new ContractsData()).build();
97 Assert.assertEquals(ContractsData.class, outboundSseEvent.getType());
98 Assert.assertEquals(ContractsData.class, outboundSseEvent.getGenericType());
99 }
100
101 @Test
102 public void testGetOutboundSseEventGetTypeNull() throws Exception {
103 OutboundSseEvent outboundSseEvent = new OutboundSseEventImpl.BuilderImpl()
104 .comment("comment").build();
105 Assert.assertEquals(null, outboundSseEvent.getType());
106 }
107 }
3939 */
4040 @Test
4141 public void testQueryParamatersClear() throws URISyntaxException {
42 ContainerRequestContext containerRequestContext = new PreMatchContainerRequestContext(request);
42 ContainerRequestContext containerRequestContext = new PreMatchContainerRequestContext(request, null, null);
4343
4444 logger.info("request uri: " + containerRequestContext.getUriInfo().getRequestUri());
4545
3737
3838 MediaType mediaType = MediaType.valueOf(type);
3939
40 PreMatchContainerRequestContext context = new PreMatchContainerRequestContext(request);
40 PreMatchContainerRequestContext context = new PreMatchContainerRequestContext(request, null, null);
4141 processor.filter(context);
4242
4343 List<MediaType> list = request.getHttpHeaders().getAcceptableMediaTypes();
5959 List<MediaType> expected = Arrays.asList(MediaType.TEXT_XML_TYPE, MediaType.TEXT_PLAIN_TYPE, MediaType.TEXT_HTML_TYPE, MediaType.APPLICATION_XHTML_XML_TYPE);
6060
6161 MockHttpRequest request = MockHttpRequest.get("foo?" + acceptParamName + "=" + expected.get(0) + "," + expected.get(1));
62 PreMatchContainerRequestContext context = new PreMatchContainerRequestContext(request);
62 PreMatchContainerRequestContext context = new PreMatchContainerRequestContext(request, null, null);
6363
6464 request.accept(expected.get(2));
6565 request.accept(expected.get(3));
8787 List<MediaType> expected = Arrays.asList(MediaType.TEXT_PLAIN_TYPE, MediaType.TEXT_HTML_TYPE);
8888
8989 MockHttpRequest request = MockHttpRequest.get("foo");
90 PreMatchContainerRequestContext context = new PreMatchContainerRequestContext(request);
90 PreMatchContainerRequestContext context = new PreMatchContainerRequestContext(request, null, null);
9191 request.accept(expected.get(0));
9292 request.accept(expected.get(1));
9393
123123 "foo?" + acceptParamName + "=" + param1 + "&" +
124124 acceptParamName + "=" + param2);
125125
126 PreMatchContainerRequestContext context = new PreMatchContainerRequestContext(request);
126 PreMatchContainerRequestContext context = new PreMatchContainerRequestContext(request, null, null);
127127 processor.filter(context);
128128
129129 List<MediaType> actual = request.getHttpHeaders().getAcceptableMediaTypes();
105105 dispatcher.getRegistry().removeRegistrations(resourceclass);
106106 }
107107
108 /**
109 * Check that MockHttpResponse handles a user set character set.
110 * @throws Exception
111 */
112 @Test
113 public void testCharsetHeader() throws Exception
114 {
115 Method get = ProgrammaticResource.class.getMethod("get", String.class);
116 Method setter = ProgrammaticResource.class.getMethod("setHeaders", HttpHeaders.class);
117 Field uriInfo = ProgrammaticResource.class.getDeclaredField("uriInfo");
118 Field configurable = ProgrammaticResource.class.getDeclaredField("configurable");
119 Constructor<?> constructor = ProgrammaticResource.class.getConstructor(Configurable.class);
120
121 ResourceClass resourceclass = ResourceBuilder.rootResource(ProgrammaticResource.class)
122 .constructor(constructor).param(0).context().buildConstructor()
123 .method(get).get().path("test").produces("text/html;charset=UTF-16").param(0).queryParam("a").buildMethod()
124 .field(uriInfo).context().buildField()
125 .field(configurable).context().buildField()
126 .setter(setter).context().buildSetter()
127 .buildClass();
128 dispatcher.getRegistry().addPerRequestResource(resourceclass);
129
130 MockHttpRequest request = MockHttpRequest.get("/test?a=hello");
131 MockHttpResponse response = new MockHttpResponse();
132 dispatcher.invoke(request, response);
133 Assert.assertEquals(response.getContentAsString(), "hello");
134
135 }
136
108137 }
00 package org.jboss.resteasy.test.util;
11
2 import org.jboss.resteasy.spi.MarshalledEntity;
2 import org.jboss.resteasy.spi.StringConverter;
33 import org.jboss.resteasy.test.util.resource.TypesTestProvider;
44 import org.jboss.resteasy.test.util.resource.TypesTestProviderSubclass;
55 import org.jboss.resteasy.util.Types;
2828 assertEquals("Wrong count of parameters", 1, parameters.length);
2929 assertEquals("Wrong type of exception", NullPointerException.class, (Class<?>) parameters[0]);
3030
31 parameters = Types.getActualTypeArgumentsOfAnInterface(TypesTestProvider.class, MarshalledEntity.class);
31 parameters = Types.getActualTypeArgumentsOfAnInterface(TypesTestProvider.class, StringConverter.class);
3232 assertEquals("Wrong count of parameters", 1, parameters.length);
3333 assertEquals("Wrong type of parameter", Integer.class, (Class<?>) parameters[0]);
3434 }
4444 assertEquals("Wrong count of parameters", 1, parameters.length);
4545 assertEquals("Wrong type of exception", NullPointerException.class, (Class<?>) parameters[0]);
4646
47 parameters = Types.getActualTypeArgumentsOfAnInterface(TypesTestProviderSubclass.class, MarshalledEntity.class);
47 parameters = Types.getActualTypeArgumentsOfAnInterface(TypesTestProviderSubclass.class, StringConverter.class);
4848 assertEquals("Wrong count of parameters", 1, parameters.length);
4949 assertEquals("Wrong type of parameter", Integer.class, (Class<?>) parameters[0]);
5050 }
44 import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
55 import org.jboss.resteasy.test.util.resource.UriBuilderResource;
66 import org.junit.Assert;
7 import org.junit.Ignore;
78 import org.junit.Test;
89
910 import javax.ws.rs.core.UriBuilder;
10321033 builder.build();
10331034 }
10341035 }
1036
1037 // RESTEASY-1718 checks
1038 {
1039 Assert.assertEquals("http://foo", UriBuilder.fromUri("http://foo").build().toString());
1040 Assert.assertEquals("http://foo:8080", UriBuilder.fromUri("http://foo:8080").build().toString());
1041 Assert.assertEquals("http://[::1]", UriBuilder.fromUri("http://[::1]").build().toString());
1042 Assert.assertEquals("http://[::1]:8080", UriBuilder.fromUri("http://[::1]:8080").build().toString());
1043
1044 Assert.assertEquals("http://[0:0:0:0:0:0:0:1]", UriBuilder.fromUri("http://[0:0:0:0:0:0:0:1]").build().toString());
1045 Assert.assertEquals("http://[0:0:0:0:0:0:0:1]:8080", UriBuilder.fromUri("http://[0:0:0:0:0:0:0:1]:8080").build().toString());
1046 Assert.assertEquals("http://foo", UriBuilder.fromUri("http://{host}").build("foo").toString());
1047 Assert.assertEquals("http://foo:8080", UriBuilder.fromUri("http://{host}:8080").build("foo").toString());
1048 }
1049
1050 }
1051
1052 @Test
1053 public void additionalCheckForIPv6() throws Exception {
1054
1055 Assert.assertEquals("http://[0:0:0:0:0:0:0:1]", UriBuilder.fromUri("http://[0:0:0:0:0:0:0:1]").build().toString());
1056 Assert.assertEquals("http://[::1]", UriBuilder.fromUri("http://[::1]").build().toString());
1057
1058 // URI substitues square brackets with their escaped representation
1059 Assert.assertEquals("http://%5B0:0:0:0:0:0:0:1%5D", UriBuilder.fromUri("http://{host}").build("[0:0:0:0:0:0:0:1]").toString());
1060 Assert.assertEquals("http://%5B0:0:0:0:0:0:0:1%5D:8080", UriBuilder.fromUri("http://{host}:8080").build("[0:0:0:0:0:0:0:1]").toString());
1061
1062 // inspiration from https://stackoverflow.com/a/17871737
1063 Assert.assertEquals("http://[1:2:3:4:5:6:7:8]", UriBuilder.fromUri("http://[1:2:3:4:5:6:7:8]").build().toString());
1064 Assert.assertEquals("http://[1::]", UriBuilder.fromUri("http://[1::]").build().toString());
1065 Assert.assertEquals("http://[1:2:3:4:5:6:7::]", UriBuilder.fromUri("http://[1:2:3:4:5:6:7::]").build().toString());
1066 Assert.assertEquals("http://[1::8]", UriBuilder.fromUri("http://[1::8]").build().toString());
1067 Assert.assertEquals("http://[1:2:3:4:5:6::8]", UriBuilder.fromUri("http://[1:2:3:4:5:6::8]").build().toString());
1068 Assert.assertEquals("http://[1::7:8]", UriBuilder.fromUri("http://[1::7:8]").build().toString());
1069 Assert.assertEquals("http://[1:2:3:4:5::7:8]", UriBuilder.fromUri("http://[1:2:3:4:5::7:8]").build().toString());
1070 Assert.assertEquals("http://[1:2:3:4:5::8]", UriBuilder.fromUri("http://[1:2:3:4:5::8]").build().toString());
1071 Assert.assertEquals("http://[1::6:7:8]", UriBuilder.fromUri("http://[1::6:7:8]").build().toString());
1072 Assert.assertEquals("http://[1:2:3:4::6:7:8]", UriBuilder.fromUri("http://[1:2:3:4::6:7:8]").build().toString());
1073 Assert.assertEquals("http://[1:2:3:4::8]", UriBuilder.fromUri("http://[1:2:3:4::8]").build().toString());
1074 Assert.assertEquals("http://[1::5:6:7:8]", UriBuilder.fromUri("http://[1::5:6:7:8]").build().toString());
1075 Assert.assertEquals("http://[1:2:3::5:6:7:8]", UriBuilder.fromUri("http://[1:2:3::5:6:7:8]").build().toString());
1076 Assert.assertEquals("http://[1:2:3::8]", UriBuilder.fromUri("http://[1:2:3::8]").build().toString());
1077 Assert.assertEquals("http://[1::4:5:6:7:8]", UriBuilder.fromUri("http://[1::4:5:6:7:8]").build().toString());
1078 Assert.assertEquals("http://[1:2::4:5:6:7:8]", UriBuilder.fromUri("http://[1:2::4:5:6:7:8]").build().toString());
1079 Assert.assertEquals("http://[1:2::8]", UriBuilder.fromUri("http://[1:2::8]").build().toString());
1080 Assert.assertEquals("http://[1::3:4:5:6:7:8]", UriBuilder.fromUri("http://[1::3:4:5:6:7:8]").build().toString());
1081 Assert.assertEquals("http://[1::8]", UriBuilder.fromUri("http://[1::8]").build().toString());
1082 Assert.assertEquals("http://[::2:3:4:5:6:7:8]", UriBuilder.fromUri("http://[::2:3:4:5:6:7:8]").build().toString());
1083 Assert.assertEquals("http://[::3:4:5:6:7:8]", UriBuilder.fromUri("http://[::3:4:5:6:7:8]").build().toString());
1084 Assert.assertEquals("http://[::8]", UriBuilder.fromUri("http://[::8]").build().toString());
1085 Assert.assertEquals("http://[::]", UriBuilder.fromUri("http://[::]").build().toString());
1086
1087 // link-local format
1088 Assert.assertEquals("http://[fe80::7:8%eth0]", UriBuilder.fromUri("http://[fe80::7:8%eth0]").build().toString());
1089 Assert.assertEquals("http://[fe80::7:8%1]", UriBuilder.fromUri("http://[fe80::7:8%1]").build().toString());
1090 Assert.assertEquals("http://[fe80::7:8%eth0]:8080", UriBuilder.fromUri("http://[fe80::7:8%eth0]:8080").build().toString());
1091 Assert.assertEquals("http://[fe80::7:8%1]:80", UriBuilder.fromUri("http://[fe80::7:8%1]:80").build().toString());
1092
1093 Assert.assertEquals("http://[::255.255.255.255]", UriBuilder.fromUri("http://[::255.255.255.255]").build().toString());
1094 Assert.assertEquals("http://[::ffff:255.255.255.255]", UriBuilder.fromUri("http://[::ffff:255.255.255.255]").build().toString());
1095 Assert.assertEquals("http://[::ffff:0:255.255.255.255]", UriBuilder.fromUri("http://[::ffff:0:255.255.255.255]").build().toString());
1096
1097 Assert.assertEquals("http://[2001:db8:3:4::192.0.2.33]", UriBuilder.fromUri("http://[2001:db8:3:4::192.0.2.33]").build().toString());
1098 Assert.assertEquals("http://[64:ff9b::192.0.2.33]", UriBuilder.fromUri("http://[64:ff9b::192.0.2.33]").build().toString());
10351099 }
10361100
10371101 public void printParse(String uri) {
00 package org.jboss.resteasy.test.util.resource;
11
2 import org.jboss.resteasy.spi.MarshalledEntity;
2 import org.jboss.resteasy.spi.StringConverter;
33
44 import javax.ws.rs.core.Response;
55 import javax.ws.rs.ext.ExceptionMapper;
66
7 public class TypesTestProvider implements ExceptionMapper<NullPointerException>, MarshalledEntity<Integer> {
7 public class TypesTestProvider implements ExceptionMapper<NullPointerException>, StringConverter<Integer> {
88
99 public Response toResponse(NullPointerException exception) {
1010 return null;
1111 }
1212
13 @Override
14 public byte[] getMarshalledBytes()
15 {
16 return null;
17 }
13 public Integer fromString(String str) {
14 return null;
15 }
1816
19 @Override
20 public Integer getEntity()
21 {
22 return null;
23 }
17 public String toString(Integer value) {
18 return null;
19 }
2420
2521 }
33 <parent>
44 <groupId>org.jboss.resteasy</groupId>
55 <artifactId>resteasy-jaxrs-all</artifactId>
6 <version>3.1.4.Final</version>
6 <version>3.5.0.Final</version>
77 <relativePath>../pom.xml</relativePath>
88 </parent>
99
2424 <version>${project.version}</version>
2525 </dependency>
2626 <dependency>
27 <groupId>org.jboss.resteasy</groupId>
28 <artifactId>resteasy-client</artifactId>
29 <version>${project.version}</version>
30 </dependency>
31 <dependency>
3227 <groupId>junit</groupId>
3328 <artifactId>junit</artifactId>
3429 <scope>compile</scope>
32033203 // / Returns an Enumeration of the header names.
32043204 public Enumeration getHeaderNames()
32053205 {
3206 return new Vector(new HashSet(reqHeaderNames)).elements();
3206 return reqHeaderNames.elements();
32073207 }
32083208
32093209 // / Gets the current valid session associated with this request, if
00 package org.jboss.resteasy.plugins.server.tjws;
11
22 import org.junit.Assert;
3 import org.jboss.resteasy.client.ClientRequest;
34 import org.jboss.resteasy.test.TestPortProvider;
45 import org.junit.After;
56 import org.junit.Before;
910 import javax.servlet.http.HttpServlet;
1011 import javax.servlet.http.HttpServletRequest;
1112 import javax.servlet.http.HttpServletResponse;
12 import javax.ws.rs.client.Invocation.Builder;
13
1413 import java.io.File;
1514 import java.io.IOException;
1615 import java.net.URI;
4948 });
5049 server.start();
5150
52 Builder request = TestPortProvider.createTarget("/hello").request();
53 Assert.assertEquals("world", request.get().readEntity(String.class));
51 ClientRequest request = TestPortProvider.createClientRequest("/hello");
52 Assert.assertEquals("world", request.get(String.class).getEntity());
5453 }
5554
5655 @Test
7170
7271 private void checkText(String uri, final String text) throws Exception
7372 {
74 Builder request = TestPortProvider.createTarget(uri).request();
75 Assert.assertEquals(text, request.get().readEntity(String.class));
73 ClientRequest request = TestPortProvider.createClientRequest(uri);
74 Assert.assertEquals(text, request.get(String.class).getEntity());
7675 }
7776
7877